fork download
  1. #include <iostream>
  2.  
  3.  
  4. void receiveByte( uint8_t byte )
  5. {
  6. printf( "receiveByte( 0x%02X )\n", byte );
  7.  
  8. static const uint8_t header[] = { 0x23, 0x00, 0x18, 0x22 };
  9. static uint8_t headerIndex = 0;
  10.  
  11. static uint8_t bytes[3];
  12. static uint8_t bytesIndex = 0;
  13.  
  14. if ( headerIndex != 4 )
  15. {
  16. if ( byte == header[ headerIndex ] )
  17. {
  18. if ( ++headerIndex == 4 )
  19. {
  20. printf( "-> header received\n" );
  21. }
  22. }
  23. else
  24. {
  25. headerIndex = 0;
  26. }
  27. }
  28. else if ( bytesIndex != 3 )
  29. {
  30. bytes[ bytesIndex ] = byte;
  31.  
  32. if ( ++bytesIndex == 3 )
  33. {
  34. printf( "-> bytes received\n" );
  35.  
  36. for ( uint8_t i = 0; i < 3; i++ )
  37. {
  38. printf(" bytes[%hhu] = 0x%02X\n", i, bytes[i] );
  39. }
  40.  
  41. // reset for next data
  42. headerIndex = 0;
  43. bytesIndex = 0;
  44. }
  45. }
  46. }
  47.  
  48.  
  49. int main()
  50. {
  51.  
  52. // simulate receiving bytes from source
  53.  
  54. uint8_t bytes[] = { 0x23, 0xEB, 0x54, 0x23, 0x00, 0x18, 0x22, 0x45, 0x72, 0xAE, 0xA8, 0x23, 0xEB, 0x54, 0x23, 0x00, 0x18, 0x21, 0x99, 0xAA, 0x54, 0x23, 0x00, 0x18, 0x22, 0x11, 0x22, 0x33, 0x23 };
  55.  
  56. for (uint8_t i = 0; i < sizeof( bytes ) / sizeof( uint8_t ); i++ )
  57. {
  58. receiveByte( bytes[i] );
  59. }
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 5500KB
stdin
Standard input is empty
stdout
receiveByte( 0x23 )
receiveByte( 0xEB )
receiveByte( 0x54 )
receiveByte( 0x23 )
receiveByte( 0x00 )
receiveByte( 0x18 )
receiveByte( 0x22 )
-> header received
receiveByte( 0x45 )
receiveByte( 0x72 )
receiveByte( 0xAE )
-> bytes received
   bytes[0] = 0x45
   bytes[1] = 0x72
   bytes[2] = 0xAE
receiveByte( 0xA8 )
receiveByte( 0x23 )
receiveByte( 0xEB )
receiveByte( 0x54 )
receiveByte( 0x23 )
receiveByte( 0x00 )
receiveByte( 0x18 )
receiveByte( 0x21 )
receiveByte( 0x99 )
receiveByte( 0xAA )
receiveByte( 0x54 )
receiveByte( 0x23 )
receiveByte( 0x00 )
receiveByte( 0x18 )
receiveByte( 0x22 )
-> header received
receiveByte( 0x11 )
receiveByte( 0x22 )
receiveByte( 0x33 )
-> bytes received
   bytes[0] = 0x11
   bytes[1] = 0x22
   bytes[2] = 0x33
receiveByte( 0x23 )