c - Arduino 从串口读取字符串

标签 c arduino

#include <stdio.h>

#define LED 13

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int i;
  char command[5];
  for (i = 0; i < 4; i++) {
    command[i] = Serial.read();
  }
  command[4] = '\0';

  Serial.println(command);

  if (strcmp(command, "AAAA") == 0) {
    digitalWrite(LED, HIGH);
    Serial.println("LED13 is ON");
  } else if (strcmp(command, "BBBB") == 0) {
    digitalWrite(LED, LOW);
    Serial.println("LED13 is OFF");
  }
}

我正在尝试使用 Arduino 的串口读取一个 4 个字符长的字符串,当它是 AAAA 时打开 LED,当它是 BBBB 时关闭串口。

但是,当我输入“AAAA”时,它显示为“AAAÿ”,中间有很多“ÿ”。

我认为我正在正确阅读所有内容,但效果不是很好,知道我做错了什么吗?

最佳答案

String txtMsg = "";  
char s;

void loop() {
    while (serial.available() > 0) {
        s=(char)serial.read();
        if (s == '\n') {
            if(txtMsg=="HIGH") {  digitalWrite(13, HIGH);  }
            if(txtMsg=="LOW")  {  digitalWrite(13, LOW);   }
            // Serial.println(txtMsg); 
            txtMsg = "";  
        } else {  
            txtMsg +=s; 
        }
    }
}

关于c - Arduino 从串口读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10451128/

相关文章:

c - 从随机 id 中检索元素的最佳算法

c - C 中 system() 的问题

使用arduino发送到串口时ubuntu崩溃

security - 温度传感器和网络服务器泛滥

python - 树莓派 : issue communicating via I2C

c - 如何在C中获取数组参数的实际大小?

c - http 服务器响应(套接字)的 header 和内容之间存在差异

c - void 影响程序的输出

debugging - 如何调试在 Arduino 硬件上运行的 Arduino 代码?

c++ - Arduino C++ 代码 : can you use virtual functions and exceptions?