我使用的是Arduino Uno和Windows 7。我的目标是有一个LED灯闪烁,当它闪烁时,它打印出“眨眼”到串行显示器。
当我运行下面的代码,我可以打印出“眨眼”到串行监视器每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);
}我不清楚是什么导致了这种行为,我希望能解释一下为什么会发生这种情况,以及如何避免这个问题。谢谢!
发布于 2017-05-10 06:39:36
是什么导致了这种行为?
引脚0和1用于串行通信。它真的不可能使用插脚0和1的外部电路,仍然能够利用串行通信或上传新的草图到董事会。
串行通信用于Arduino板与计算机或其他设备之间的通信。所有Arduino板至少有一个串行端口(也称为UART或USART):串行。它在数字引脚0 (RX)和1 (TX)上进行通信,并通过USB与计算机通信。因此,如果在草图中的函数中使用它们,则不能使用引脚0和1进行数字输入或输出。
想想看,一个引脚怎么能同时作用于串行和数字?是的,这就是你想要做的,!!。以波特率将引脚设置为串行,然后将其用于制作LED闪烁。
因此,当您执行serial.begin(9600);时,它将串行数据传输的每秒比特速率( you )设置为960。因此您在此函数中使用了串行引脚,之后不能使用引脚0和1进行数字输入或输出(如LED )。当您评论serial.begin(9600);时,您的引脚可以自由使用,从而获得输出。
如何避免这个问题?
将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);
}发布于 2017-05-10 00:55:09
Arduino使用引脚0和1进行串行通信。引脚0是RX和1是TX,所以当你试图闪光灯的LED也连接到引脚0,这两个开始践踏彼此。
尝试移动LED到一个不同的引脚和更新你的草图匹配,它应该开始工作。
此页面包含有关Arduino串行连接的信息:https://www.arduino.cc/en/Reference/Serial。
快乐黑客
https://stackoverflow.com/questions/43881852
复制相似问题