//
// MysterySerialReceiver.ino
// https://wokwi.com/arduino/projects/310261647915614785
// MysterySerialSender.ino (this sketch)
// https://wokwi.com/arduino/projects/310250258016764481
//
//
// Create packages of 8 byte
// 0x75, 0x60, 0x??, 0x??, 0x??, 0x??, 0x??, checksum
// The checksum is a 2's complement ?
// Set _SERIAL_ to the used serial bus.
#define _SERIAL_ Serial
uint32_t counter;
void setup()
{
_SERIAL_.begin( 9600); // 9600, 8N1
}
void loop()
{
int x = random( 10);
if( x == 0)
{
// send wrong data, with right checksum
byte buf12[12];
buf12[0] = 0x75;
buf12[1] = 0x60;
buf12[2] = 0x75;
buf12[3] = 0x60;
buf12[4] = 0x75;
buf12[5] = 0x60;
buf12[6] = (byte) random( 256);
buf12[7] = checksum( buf12);
buf12[8] = (byte) random( 256);
buf12[9] = checksum( &buf12[2]);
buf12[10] = (byte) random( 256);
buf12[11] = checksum( &buf12[4]);
_SERIAL_.write( buf12, sizeof( buf12));
}
else if( x == 1)
{
// send data with wrong checksum
byte buf[8];
buf[0] = 0x75;
buf[1] = 0x60;
buf[2] = (byte) random( 256);
buf[3] = (byte) random( 256);
buf[4] = (byte) random( 256);
buf[5] = (byte) random( 256);
buf[6] = (byte) random( 256);
buf[7] = (byte) (checksum( buf) + 1 + random( 250)); // to be sure the checksum is wrong
_SERIAL_.write( buf, sizeof( buf));
}
else if( x == 2)
{
// send totally wrong data
int n = random( 1, 50);
for( int i=0; i<n; i++)
{
_SERIAL_.write( (byte) random( 256));
}
}
else
{
// send valid data
byte buf8[8];
buf8[0] = 0x75;
buf8[1] = 0x60;
buf8[2] = (byte) (counter >> 24); // counter value (for valid data only)
buf8[3] = (byte) (counter >> 16);
buf8[4] = (byte) (counter >> 8);
buf8[5] = (byte) counter;
buf8[6] = (byte) random( 256); // just a spare byte
buf8[7] = checksum( buf8);
_SERIAL_.write( buf8, sizeof( buf8));
counter++;
}
// random gap, max 50ms, 50% chance no gap
if( random( 2) == 0)
{
delay( random( 50));
}
}
byte checksum( byte data[])
{
byte total;
for( int i=0; i<7; i++)
{
total += data[i];
}
byte chk = (byte) (256 - (int) total);
return( chk);
}