Arduino Uno - 电灯开关

Arduino Uno - Light Switch

我正在编写的程序的功能是通过 USB 端口将传入的模拟数据从传感器传输到我计算机上的程序。为了找点乐子,我决定在程序中添加一个按钮,它将 on/off 变成 lamp。 lamp 将连接到一个继电器,该继电器连接到 arduino。我知道如何对其进行编程,但我想知道这是否会中断传感器数据传输?

当按下按钮时,我将从arduino获取灯的当前状态(HIGH(1)或LOW(0)),然后写入arduino(HIGH(1)或LOW(0))取决于当前状态。由于与传感器输出相关的原因,我在 arduino 程序的每个循环之间有 5 秒的延迟;然而,我想我必须改变这个,这样当按下按钮时,arduino 循环不会错过它,或者这是不可能的?

我想我在某处读到您不能 transmit/receive 在同一条串行线上传输数据...在这种情况下,我将需要 Mega。

您必须记住并将 Arduino 视为单线程设备。当它正在做 anything 时,它无法做任何其他事情。时期!然而,对于串口,缓冲区仍将接收 RX 上的传入数据,但是如果在阻塞时发生溢出情况,则无法进行管理。

请参阅以下内容,直接取自 Arduino 参考资料

Certain things do go on while the delay() function is controlling the Atmega chip however, because the delay function does not disable interrupts. Serial communication that appears at the RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will work as they should. Reference

现在说,当您将循环之间的延迟设置为 5 秒时 (delay(5000)),您实际上是在阻止它执行几乎完全停止的任何其他操作。

Arduino 框架公开了一个计数器 (millis()),该计数器基本上是 运行s 从启动那一刻起大约 50 天,以一 (1) 毫秒为增量。参见 Arduino - millis()

在您的应用程序中,您将定义(记住)由于 运行 造成的循环以及所述循环何时完成,以便不允许另一个循环进入 运行 直到 millis() counter 比你的计数多了一个定义的数量。 (记得将计数定义为 long

然后你要做的是将你的循环移出到单独的函数中,这些函数只有在 if 语句 return 为真时才会执行...

例如……

long interval = 5000; // Define interval outside of the main loop
long previousCount = 0; // Used to store milli count when finished
int loopPosition = 1;

void loop()
 {
   if ((long)millis() - previousCount >= 5000 )
      // This if statement will only return true every 5 seconds (5000ms)
     {
        if (loopPosition == 1) 
          {
            function_One();
            previousCount = millis(); // Redefine previousCount to now
            loopPosition++; // Increment loop position
          }

        else if (loopPosition == 2)
          {
            function_Two();
            previousCount = millis();
            loopPosition--; // Decrement loop position
          }

     }

 // Do Anything Here You Want
 // - While ever the if statement above returns false
 //   the loop will move to this without hesitation so
 //   you can do things like monitor a pin low / high scenario.     

 }

void function_One()
 {
   // Do Your First Loop
 }

void function_Two()
 {
   // Do Your Second Loop
 }

以上将阻止您正在使用的任何延迟阻止令人敬畏,并且更重要的是,如果在正确的场景下正确实施,几乎可以使延迟过时。

关于您的串行数据评论,就像我在本文开头所说的那样,Arduino 一次只能做一件事。即使使用 Mega,也无法在 完全 同时发送和接收。例如,像 'Uno' 这样的电路板只能有一个串行接口,而 'Mega' 有四个。

祝你好运....
注意-对于阅读本文的初学者,以下教程/示例以相当简单的术语涵盖了我上面的内容,并且是进一步令人敬畏的重要组成部分! Arduino - Blink Without Delay