解析在C - Arduino中用逗号分隔的字符串

时间:2015-06-12 14:53:10

标签: c arduino lcd

我希望能够在我的Arduino上解析用逗号分隔的字符串。 我发送给我的设备文本字符串,如

Somebody,Natalia Le Rose,, 

由C#

生成
        //creating string that will be send to arduino
    string message = SongTitleNotification + "," + SongArtistNotification + "," + FacebookNotification + "," + GmailNotification;

    //sending message

    SerialPort port = new SerialPort("COM4", 9600);
    port.Open();
    port.Write(message);
    port.Close();

它接收我的草图

#include <LiquidCrystal.h>
#include <string.h>
#include <stdio.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(20, 4);
  Serial.begin(9600);
}

void loop()
{

 while (Serial.available() > 0) {
    lcd.clear();
    delay(100);
    // look for the next valid integer in the incoming serial stream:
    char title = Serial.parseInt();
    // do it again:
    char artist = Serial.parseInt();
    // do it again:
    char fb = Serial.parseInt();
    char gmail = Serial.parseInt();

    lcd.print(title);
    lcd.setCursor(0,1);
    lcd.print(artist);
    lcd.setCursor(0,2);
    lcd.print(fb);
    lcd.setCursor(0,3);
    lcd.print(gmail);

    }
    delay(3500);
  }

但是lcd没有显示变量。 我该怎么办? :)

1 个答案:

答案 0 :(得分:0)

要使用分隔符解析字符串,请考虑使用strtok。您应该创建一个Serial读入的缓冲区,然后解析

char buffer[50];
uint8_t bufferReadIndex = 0;
while (Serial.available() > 0) {
    buffer[bufferReadIndex++] = Serial.read();
}
char* stringPtr;
stringPtr = strtok(&buffer, ",");
while (stringPtr != NULL)
{
    Serial.println(stringPtr);
    stringPtr = strtok(NULL, ",");
}