在同一个 Arduino 脚本中使用 Serial.print 和 digitalWrite

Using Serial.print and digitalWrite in Same Arduino Script

我正在使用 Arduino Uno 和 Windows 7。我的目标是让 LED 灯闪烁,当它闪烁时,它会打印出 "Blink" 到串行监视器。

当我 运行 下面的代码时,我能够每 2 秒将 "Blink" 打印到串行监视器,但是,灯一直亮着。当我删除行

Serial.begin(9600);

指示灯会闪烁,但不会打印任何内容。我运行ning的代码如下:

int LED3 = 0;
void setup() {
  // When I comment out the line below, the lights flash as intended, but 
  // nothing prints.  When I have the line below not commented out, 
  // printing works, but the lights are always on (ie do not blink). 

  Serial.begin(9600);  // This is the line in question.
  pinMode (LED3, OUTPUT);
}

void loop() {
  Serial.println("Blink");
  digitalWrite (LED3, HIGH);
  delay(1000);
  digitalWrite (LED3, LOW);
  delay(1000);
}

我不清楚导致此行为的原因,希望能解释为什么会发生这种情况以及如何避免此问题。谢谢!

Arduino 使用引脚 0 和 1 进行串行通信。 Pin 0 是 RX,1 是 TX,所以当你试图让同样连接到 pin 0 的 LED 闪烁时,两者开始互相踩踏。

尝试将 LED 移到不同的引脚并更新您的草图以匹配,它应该会开始工作。

此页面包含有关 Arduino 串行连接的信息:https://www.arduino.cc/en/Reference/Serial

祝黑客愉快

what causes this behavior ?

引脚 0 和 1 用于串行通信。确实不可能将引脚 0 和 1 用于外部电路,并且仍然能够利用串行通信或将新草图上传到电路板。

来自Arduino Serial reference documentation

Serial is used for communication between the Arduino board and a computer or other devices. All Arduino boards have at least one serial port (also known as a UART or USART): Serial. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Thus, if you use them in functions in your sketch, you cannot also use pins 0 and 1 for digital input or output.

试想一下,一个引脚如何同时进行串行和数字操作?是的,这就是您想要做的 !! 。您以波特率将 pin 设置为串行,然后使用它使 LED 闪烁。

因此,当您执行 serial.begin(9600); 时,它会将串行数据传输的数据速率(波特)设置为 9600.Thus 您在此函数中使用了串行引脚,之后您将无法使用引脚 0 和 1 用于数字输入或输出(如 LED)。当您评论 serial.begin(9600); 时,您的引脚可以免费使用,因此您可以获得输出。

how to avoid this problem ?

将 LED 从引脚 0 更改为数字引脚。

下面的代码会得到你期望的结果(我在里面使用了pin 7):

int LED3 = 7; //I have changed pin to 7 ( you can use any except 0 and 1 )
void setup() {
  // When I comment out the line below, the lights flash as intended, but 
  // nothing prints.  When I have the line below not commented out, 
  // printing works, but the lights are always on (ie do not blink). 

  Serial.begin(9600);  // This is the line in question.
  pinMode (LED3, OUTPUT);
}

void loop() {
  Serial.println("Blink");
  digitalWrite (LED3, HIGH);
  delay(1000);
  digitalWrite (LED3, LOW);
  delay(1000);
}