1

我正在mkr wifi 1010和mega之间编写一个串行通信程序,其中mkr向mega发送一个H或L char,mega通过读取char并将其板载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);
    }
  }
}

据我所知,这两个不同的 mkr 程序做同样的事情并以完全相同的方式发送串行数据,只是一个是阻塞的,一个是非阻塞的。为什么无延迟代码不闪烁?

4

1 回答 1

1

在无延迟发件人代码中:

int byteToSend

应该

char byteToSend

并在接收器代码中:

int incomingByte

应该

char incomingByte

这解决了这个问题。

于 2020-10-04T13:57:24.600 回答