[英]Arduino MKR Wifi 1010 Serial Communication with Arduino Mega
我正在 mkr wifi 1010 和 mega 之间编写一个串行通信程序,其中 mkr 向 mega 发送 H 或 L 字符,然后 mega 通过读取字符并将其板载 LED 设置为高或低来做出响应,具体取决于字符。 当我在 mkr 上使用 delay(#) 时,代码工作得很好,mega 的 LED 灯会时不时地闪烁。
但是,当我创建无延迟代码时,mega 的 LED 不会闪烁。 它要么保持低位,要么保持高位,大部分时间保持低位。 我通过读取串行端口检查了 mkr 代码,它确实在两个版本的代码中以正确的间隔交替发送 72(H) 和 76(L)。
接线图:
MKR Mega
gnd -> gnd
tx -> rx
rx -> tx
在 mkr 的 rx 引脚之前,我已将 mega 的 tx 引脚电平转换为 3.3v。
mkr延迟代码:
void setup()
{
uint32_t baudRate = 9600;
Serial1.begin(baudRate);
}
void loop()
{
Serial1.print('H');
delay(500);
Serial1.print('L');
delay(500);
}
mkr 无延迟代码:
unsigned long curT = 0;
unsigned long prevT = 0;
const int interval = 500;
int byteToSend = 'L';
void setup()
{
uint32_t baudRate = 9600;
Serial1.begin(baudRate);
}
void loop()
{
curT = millis();
if (curT - prevT > interval)
{
if (byteToSend == 'L')
{
byteToSend = 'H';
}
else
{
byteToSend = 'L';
}
Serial1.print(byteToSend);
prevT = curT;
}
}
超级代码:
const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0)
{
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H')
{
digitalWrite(ledPin, HIGH);
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L')
{
digitalWrite(ledPin, LOW);
}
}
}
据我所知,这 2 个不同的 mkr 程序做完全相同的事情并以完全相同的方式发送串行数据,只是一个是阻塞的,一个是非阻塞的。 为什么无延迟代码不闪烁?
在无延迟发件人代码中:
int byteToSend
应该
char byteToSend
并在接收器代码中:
int incomingByte
应该
char incomingByte
这解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.