hej robtillaart,
i really like your slim solution for this task!
Now i'm trying to do the same thing but with a UDP input. So i combined your code with the UDP example. Unfortunately it seams like switch...case dose not like to work with the char from the packetBuffer. But why? Now i got totally stuck and i need a little hint.
here is the code:
//
// FILE: parsePacket.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.1.00
// PURPOSE: demo
// DATE: 2014-dec-29
// URL:
//
// Released to the public domain
//
#include <SPI.h> // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 0, 222);
unsigned int localPort = 8888; // local port to listen on
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged"; // a string to send back
EthernetUDP Udp; // An EthernetUDP instance to let us send and receive packets over UDP
int field[30];
uint8_t idx = 0;
bool done = false;
void setup()
{
Ethernet.begin(mac, ip);
Udp.begin(localPort);
Serial.begin(9600);
Serial.println("Start ");
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize > 0)
{
Udp.read(packetBuffer, packetSize); // read the packet into packetBuffer
Serial.println();
Serial.print("recieved massage: ");
Serial.println(packetBuffer);
done = parsePacket(packetBuffer);
for(int i=0;i<UDP_TX_PACKET_MAX_SIZE;i++) packetBuffer[i] = 0; //cleer buffer
}
if (done) // ready to process a package
{
Serial.print("fields:\t");
Serial.println(idx);
for (int i = 0; i < idx; i++)
{
Serial.print(i);
Serial.print("\t");
Serial.println(field[i]);
}
Serial.println("done");
}
// do other things here
}
bool parsePacket(int c)
{
bool ready = false;
switch (c)
{
case '0'...'9':
field[idx] = field[idx] * 10 + c - '0';
break;
case ',':
idx++;
field[idx] = 0;
break;
case '<':
idx = 0;
field[idx] = 0;
break;
case '>':
idx++;
ready = true;
break;
default:
; // skip
}
return ready;
}