繁体   English   中英

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

[英]Parsing string separated by commas in C - Arduino

我希望能够在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);
  }

但是液晶屏不显示变量。 我该怎么办? :)

要使用定界符解析字符串,请考虑使用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, ",");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM