Need help parsing serial ASCII stream please

I am fairly new to C++ programming and I'm working on a project that will read and parse a 2400baud serial ASCII data stream. For now I'm using an Arduino Uno as my prototyping platform. The stream is comma delimited, continuously repeating, and formatted exactly like this:

V=13.7,FV=13.7,V2=00.0,A=00.1,FA=00.1,AH=0.18,%=100,W=0.82,DSC=1.87,DSE=1.98,

I have no problem opening the serial port, setting the baud rate, and seeing the ASCII stream… but I need a help with the parsing of the stream. I think that strtok (split string into tokens) is probably the best function to do this as I need (some of) the numbers as integers and (some of) the text as descriptors.

The data I currently need from the stream are the ints from the descriptors V, A, W and %. I guess I may also need to store these ints in a buffer so I can use/output them?

For now I would be happy just to realtime serial.print the output (using the above stream as the example) as:

Volts 13.7
Amps 00.1
Watts 0.82
Percent 100


Any advice or sample code would be appreciated.
Thanks in advance!
-Mark
You would need to add error-handling for badly formed input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>

// split a string into comma delimited segments
// http://www.mochima.com/tutorials/vectors.html
std::vector<std::string> split_on_commas( const char* cstr )
{
    std::vector<std::string> segments ;

    // http://latedev.wordpress.com/2011/11/16/c-stringstreams/
    std::istringstream stm( cstr ) ;

    std::string token ;

    // http://www.cplusplus.com/reference/string/string/getline/
    while( std::getline( stm, token, ',' ) ) segments.push_back(token) ;

    return segments ;
}

// given a string of the form abcd=nnn.nn, extract then into a (string,double) pair
// http://www.cplusplus.com/reference/utility/pair/
std::pair< std::string, double > make_mame_value_pair( const std::string& token )
{
    std::istringstream stm( token ) ;

    std::string name ;
    double value ;

    std::getline( stm, name, '=' ) ;
    stm >> value ;

    // http://www.stroustrup.com/C++11FAQ.html#uniform-init
    return { name, value } ;
}

int main()
{
    // place a chunk of the streaming data into a null-terminated string
    char cstr[] = "V=13.7,FV=13.7,V2=00.0,A=00.1,FA=00.1,AH=0.18,%=100,W=0.82,DSC=1.87,DSE=1.98," ;
    std::cout << cstr << '\n' ;

    // http://www.stroustrup.com/C++11FAQ.html#for
    for( const auto& tok : split_on_commas(cstr) )
    {
        auto pair = make_mame_value_pair(tok) ;
        std::cout << "name: '" << pair.first << "'  value: " << pair.second << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/3080e64dc4809d73
Thank you JLBorges. I'll give that a try.
-Mark
Topic archived. No new replies allowed.