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

时间:2017-05-10 00:37:07

标签: arduino arduino-uno

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

当我运行下面的代码时,我可以打印出#34; Blink"然而,每2秒对串行监视器一直亮着。当我删除该行

Serial.begin(9600);

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

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);
}

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

2 个答案:

答案 0 :(得分:12)

  

导致这种行为的原因是什么?

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

来自Arduino Serial reference documentation

  

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);
}

答案 1 :(得分:3)

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

尝试将LED移动到另一个引脚并更新草图以匹配,它应该开始工作。

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

快乐的黑客攻击

相关问题