在Same Arduino脚本中使用Serial.print和digitalWrite

Mar*_*ram 5 arduino arduino-uno

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

当我运行下面的代码时,我能够每隔2秒将"闪烁"打印到串行监视器,但是,灯仍然一直打开.当我删除该行

Serial.begin(9600);
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Bil*_*lla 12

是什么导致这种行为?

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

Arduino Serial参考文档:

Serial用于Arduino板与计算机或其他设备之间的通信.所有Arduino板都至少有一个串口(也称为UART或USART):Serial.它通过USB在数字引脚0(RX)和1(TX)以及计算机上进行通信.因此,如果在草图中的功能中使用它们,则不能将引脚0和1用于数字输入或输出.

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

因此,当您这样做serial.begin(9600);时将串行数据传输的数据速率(以每秒位数(波特)为单位)设置为9600.因此,您在此功能中使用了串行引脚,之后您无法使用引脚0和1进行数字输入或输出(如LED ).当您发表评论时,serial.begin(9600);您的引脚可以自由使用,从而获得输出.

如何避免这个问题?

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

以下代码将获得您期望的结果(我在其中使用了引脚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);
}
Run Code Online (Sandbox Code Playgroud)