Parsing string separated by commas in C - Arduino

1.2k views Asked by At

I would like to be able to parse a string separated by commas on my Arduino. I send to my device text string like

Somebody,Natalia Le Rose,, 

which is generated by 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();

and it receives my sketch

#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);
  }

but the lcd does not show the variables. What should I do? :)

1

There are 1 answers

0
Kane Anderson On

For parsing strings using a delimeter, consider using strtok. You should create a buffer that your Serial reads into, then parse that

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, ",");
}