parsing s serial string

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
andywatson
 
Posts: 28
Joined: Wed Feb 16, 2011 12:40 am

parsing s serial string

Post by andywatson »

I have an Uno using MySoftSerial to receive a string of numbers on one of the Uno's digital input pins. The serial data is coming from a sensor connected to the Uno, and the sensor outputs a string once a minute in the following format: "234 93 242x" and is followed by a carriage return. I want to separate the string into the 3 integers that are space delimited, throwing away anything that is not an integer(the last character or two), then I want to store the ints so I can do some math and then write them to external memory.

I'm having trouble figuring out how to parse out the individual numbers from serial string. Can someone point me in the right direction? Thanks.

User avatar
tastewar
 
Posts: 408
Joined: Thu Mar 17, 2011 10:16 am

Re: parsing s serial string

Post by tastewar »

I suspect sscanf would work for you...

http://www.nongnu.org/avr-libc/user-man ... fd8f5dca6f

smindinvern
 
Posts: 46
Joined: Sat Dec 25, 2010 9:19 pm

Re: parsing s serial string

Post by smindinvern »

this should do:

Code: Select all

#include <stdio.h>
#include <errno.h>

{
        char *input = "234 93 242x\r";        // just an example, fill this from the serial input
        char *nptr, *endptr = input;
        long int values[3];
        int i;

        for (i = 0; i < 3; i++) {
                values[i] = strtol(nptr, &endptr, 10);
                if (!endptr || endptr == nptr || errno == ERANGE)
                        return -1;        // error
        }
}

User avatar
fat16lib
 
Posts: 595
Joined: Wed Dec 24, 2008 1:54 pm

Re: parsing s serial string

Post by fat16lib »

Here is a C++ extractor that can parse this string.

This sample sketch parses the string and prints the result:

Code: Select all

#include <SdFat.h>
// test string
char buf[] = "234 93 242x\r";

void setup() {
  int i, j, k;
  Serial.begin(9600); 
  // create an input buffer stream
  ibufstream ib(buf);
  // parse line with three ints and test for errors
  if (ib >> i >> j >> k) {
    // print result for success
    Serial.println(i);
    Serial.println(j);
    Serial.println(k);
  } else {
    //  process error
    Serial.println("error");
  }
}
void loop() {}
The new version of SdFat has C++ extraction operators, >>, and insertion operators, <<, for parsing and formatting strings in memory and files.

The beta is here http://code.google.com/p/beta-lib/downloads/list

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”