Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created February 14, 2021 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxpromer/96d63fe6012e1d33136ad0c3547063a5 to your computer and use it in GitHub Desktop.
Save maxpromer/96d63fe6012e1d33136ad0c3547063a5 to your computer and use it in GitHub Desktop.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 8); // RX, TX
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
mySerial.setTimeout(100);
}
uint16_t CRC16(uint8_t *buf, int len) {
uint16_t crc = 0xFFFF;
for (uint16_t pos = 0; pos < len; pos++) {
crc ^= (uint16_t)buf[pos]; // XOR byte into least sig. byte of crc
for (int i = 8; i != 0; i--) { // Loop over each bit
if ((crc & 0x0001) != 0) { // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
} else { // Else LSB is not set
crc >>= 1; // Just shift right
}
}
}
return crc;
}
void relayWrite(uint8_t n, bool setToON) {
if (n < 1 || n > 4) {
return;
}
uint8_t buff[] = {
0x01, // Devices Address
0x05, // Function code
0x00, // Start Address HIGH
n - 1, // Start Address LOW
setToON ? 0xFF : 0x00, // Data 1 HIGH
0x00, // Data 1 LOW
0, // CRC LOW
0 // CRC HIGH
};
uint16_t crc = CRC16(&buff[0], 6);
buff[6] = crc & 0xFF;
buff[7] = (crc >> 8) & 0xFF;
mySerial.write(buff, sizeof(buff));
mySerial.flush(); // wait MODE_SEND completed
delay(100);
if (!mySerial.find("\x01\x05")) {
Serial.println("Write to Relay error !");
return;
}
}
void loop() {
relayWrite(1, HIGH); // Relay 1 -> ON
delay(1000);
relayWrite(1, LOW); // Relay 1 -> OFF
relayWrite(2, HIGH); // Relay 2 -> ON
delay(1000);
relayWrite(2, LOW); // Relay 2 -> OFF
relayWrite(3, HIGH); // Relay 3 -> ON
delay(1000);
relayWrite(3, LOW); // Relay 3 -> OFF
relayWrite(4, HIGH); // Relay 4 -> ON
delay(1000);
relayWrite(4, LOW); // Relay 4 -> OFF
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment