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

标签 arduino arduino-uno

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

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

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

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

最佳答案

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.



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

所以,当你这样做时 serial.begin(9600);它将串行数据传输的每秒比特数(波特)设置为 9600。因此您在此功能中使用了串行引脚,之后您不能将引脚 0 和 1 用于数字输入或输出(如 LED)。当您发表评论时 serial.begin(9600);您的引脚可以自由使用,因此您可以获得输出。

how to avoid this problem ?



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

关于arduino - 在同一个 Arduino 脚本中使用 Serial.print 和 digitalWrite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881852/

相关文章:

c++ - 递增if语句arduino

c++ - 带正交编码器 600ppr 的 Arduino RPM 代码

arduino - FastLED 和简单计数器的问题

c# - 从 C# 桌面应用程序获取 Arduino Uno Controller 的唯一标识值

c - 距离传感器测距误差估计

c++ - 了解神秘的C++语句

arduino - 射频三角测量(定位)

c++ - 调用不带参数的函数,即使它们已定义?

c++ - 我可以有一个跳过索引的一维 bool 数组吗?

android - 将 android 设备与 arduino 配对(使用 nRF8001 Bluefruit LE Breakout)