c programing logic for reading sensor over UART -


i'm trying read data sensor connected mcu on uart. when powered sensor outputs continuously ascii capital “r”, followed 4 ascii character digits representing distance in millimeters, followed carriage return (ascii 13).

i wondering if me figure out logic reading e.g. 9999 variable called reading.

should use blocking or non blocking function , how isolate characters if data streaming in?

first go blocking version. suppose expect missing chars @ beginning, because sensor may start streaming chars before read data. if uart gets full, might need it. sample code be:

#define cr (13) uart_t my_uart; // need setup uart_status_t status; uint8_t c; int status; char distance[255] = { 0 }; // whatever, large enough int seen_r = 0; // have not yet seen 'r'  int offset = 0;  while ((status = uart_read(my_uart, &c, &status)) == 0) {    if (seen_r)     {       if (c == cr)       {           printf("distance: %s\n", distance);           seen_r = 0;           memset(distance, 0, sizeof(distance));       }       if (offset < sizeof(distance)-1)       {           distance[offset++] = (char)c;       }       else       {           printf("unexpected size, reset!\n");            seen_r = 0;           memset(distance, 0, sizeof(distance));       }    }    else    {       if (c != 'r') continue;       seen_r = 1;    } } 

of course untested code, may give hints. basically, have state machine starts 'r' , ends cr.


Comments