Skip to content

Instantly share code, notes, and snippets.

@m1ari
Last active December 25, 2015 09:29
Show Gist options
  • Save m1ari/6954557 to your computer and use it in GitHub Desktop.
Save m1ari/6954557 to your computer and use it in GitHub Desktop.
serial read with statemachine.
#include <stdio.h>
#include <string.h>
/* On Linux systems you might need to run the following command first to
* stop the system buffering until a newline:
* stty -icanon
*/
void main (){
char NMEA_string[70] = "";
char buffer = 0;
int n = 0;
int state = 0;
while (1){
//buffer = Serial.read(); // Read Character
buffer = getchar();
printf(" > Got %c (%d)\n",buffer,state);
switch(state){
case 0: // Waiting for a $
if (buffer == '$'){
state=1;
n=0;
memset(NMEA_string,0,70); // Clear NMEA_string
}
break;
case 1: // Got a string
if ((buffer=='\r') || (buffer == '\n')){ // End of string
// Parse the string
printf("Got String: %s\n", NMEA_string);
state=0;
} else {
NMEA_string[n++]=buffer;
}
if (n >=68) { // Stop at 68 (69 chars) so there's still a NULL at the end.
printf("Error: NMEA_string has overflown (%s)\n", NMEA_string);
state=0;
}
break;
default:
printf("Error: Bad state %d\n",state);
state=0;
break;
} // Close switch
} // Close while
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment