void receiveByte( uint8_t value )
{
static bool start_byte_received = false;
if ( start_byte_received == false )
{
if ( value == 0xFF )
{
Serial.print( "start byte received" );
start_byte_received = true;
}
}
else
{
static uint8_t bytes[9];
static uint8_t counter = 0;
bytes[ counter ] = value;
if ( ++counter == 9 )
{
Serial.print( ", data received" );
start_byte_received = false;
counter = 0;
uint8_t checksum = 0;
for ( uint8_t i = 1; i < 8; ++i )
{
checksum += bytes[i];
}
if ( bytes[8] != checksum )
{
Serial.println( ", checksum is invalid" );
}
else
{
Serial.print( ", checksum is valid, data : " );
for ( uint8_t i = 0; i < 8; ++i )
{
Serial.print( "0x" );
Serial.print( bytes[i], HEX );
Serial.print( ' ' );
}
Serial.println();
}
}
}
}
void setup()
{
Serial.begin( 9600 );
// simulate sensor sending data
const uint8_t sensor_bytes[] =
{
0x00, 0x00, 0x00, 0x2A, // ... end of an incomplete sequence
0xFF, 0x01, 0x07, 0x01, 0x00, 0x22, 0x00, 0x00, 0x00, 0x2A, // valid sequence
0xFF, 0x01, 0x07, 0x01, 0x01, 0x35, 0x00, 0x00, 0x00, 0x3E, // valid sequence
0xFF, 0x01, 0x07, 0x01, 0x01, 0x35, 0x00, 0x00, 0x00, 0x3D, // invalid checksum (error in datasheet?)
0xFF, 0x01, 0x07, 0x01, 0x00, 0x44, 0x00, 0x00, 0x00, 0x4C, // valid sequence
0xFF, 0x01, 0x07, 0x01, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x08, // valid sequence
0xFF, 0x01, 0x07, 0x02, 0x02, // start of an incomplete sequence ...
};
const size_t sensor_bytes_size = sizeof( sensor_bytes ) / sizeof( sensor_bytes[0] );
for ( uint8_t i = 0; i < sensor_bytes_size; ++i )
{
receiveByte( sensor_bytes[i] );
}
}
void loop()
{
// normally you would do
/*
while ( Serial.available() )
{
receiveByte( Serial.read() );
}
*/
}