这只是一个简单的测试程序。我正在尝试在连接到它的 LCD 屏幕上“接收”Arduino 打印件。我认为是我的 if 语句导致了错误,有什么想法吗?
目前,当“发送”被放入串行监视器时,没有任何反应。
代码如下:
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
char serialinput; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
serialinput = Serial.read();
if (serialinput == 'send')
{
lcd.print("received");
}
}
}
您正在从串行端口读取一个字节(C 中的 char
),但您尝试将其与字符串进行比较:
如果你想阅读 4 char
并将其与 "send"
进行比较那么你将不得不做类似的事情:
#include <LiquidCrystal.h>
#include <string.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
char serialinput [5] = {0}; // for incoming serial data
// 4 char + ending null char
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
memmove (serialinput, &serialinput[1], 3); // Move 3 previous char in the buffer
serialinput [3] = Serial.read(); // read char at the end of input buffer
if (0 == strcmp(serialinput, "send")) // Compare buffer content to "send"
{
lcd.print("received");
}
}
}
假设<string.h>
header 在 Arduino SDK 中有效
PS:C代码中的乱码字符串写在"
之间(双引号)。 '
用于字符。