【问题标题】:Serial communication on ArduinoArduino上的串行通信
【发布时间】:2023-12-01 17:49:01
【问题描述】:

我有一个学校作业,我需要使用串行消息 #ON% 打开 LED,并使用 #OFF% 关闭 LED。 # 和 % 是正确字符串的标识符。所以我做了这个代码:

(bericht 是荷兰语的意思)

String readString = "";
int recievedCharacter;
String bericht = "";

int ledPin = 6;


void setup() {
  Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
 pinMode(ledPin, OUTPUT);
}

void loop() 
{

  while (Serial.available() > 0)
  { 
    delay(4);    
    char readChar = (char) Serial.read(); // 'Convert' to needed type
    bericht += + readChar;         // concatenate char to message

  }

  if(bericht.startsWith("#"))
  {

    if(bericht == "#ON%")
   {
      Serial.println(bericht);
      Serial.println("goed"); 
      digitalWrite(ledPin, HIGH);
      //message = "";
    }



    if(bericht == "#OFF%")
    {
      Serial.println("goed"); 
      digitalWrite(ledPin, LOW);
      //message = "";
    }
  }
}

问题是程序永远不会进入 if(bericht == "#ON%") 部分...

对不起,如果这是一个愚蠢的问题,但是通过大量的谷歌搜索我无法弄清楚......

【问题讨论】:

    标签: arduino communication


    【解决方案1】:

    问题出在这里:

    bericht += + readChar;         // concatenate char to message // XXX '+ char' => int
    

    这实际上将一个整数附加到消息中。删除+:

    bericht += readChar;         // concatenate char to message // Goed!
    

    【讨论】:

    • 啊,真的!我一直想念的那些愚蠢的事情! :P 非常感谢,明天将首先尝试!
    最近更新 更多