Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Created February 1, 2017 17:12
Show Gist options
  • Save sourceperl/13a029071d138aa0a7bdc0df4814fdee to your computer and use it in GitHub Desktop.
Save sourceperl/13a029071d138aa0a7bdc0df4814fdee to your computer and use it in GitHub Desktop.
Arduino modbus RTU frame sender (for test purpose)
/*
Arduino modbus RTU frame sender (for test purpose)
*/
// some modbus frames
const uint8_t f1[] = {0x0a, 0x03, 0x00, 0x00, 0x00, 0x01};
const uint8_t f2[] = {0x0b, 0x03, 0x00, 0x00, 0x00, 0x10};
// some functions
uint16_t crc16(const uint8_t *buf, uint8_t len)
{
uint16_t crc = 0xFFFF;
for (int pos = 0; pos < len; pos++)
{
crc ^= (uint16_t)buf[pos];
for (int i = 8; i != 0; i--)
{
if ((crc & 0x0001) != 0)
{
crc >>= 1;
crc ^= 0xA001;
}
else
crc >>= 1;
}
}
return crc;
}
uint16_t send_frame(const uint8_t *buf, uint8_t len)
{
// compute CRC
int16_t crc = crc16(buf, len);
// send frame body and CRC
Serial.write(buf, len);
Serial.write(crc & 0xff);
Serial.write(crc>>8 & 0xff);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
send_frame(f1, sizeof(f1));
delay(500);
send_frame(f2, sizeof(f2));
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment