Last active
November 20, 2021 19:10
-
-
Save maxpromer/72c0dc8e2f5e155d3e10afad44d76a94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Dev by IOXhop.com */ | |
#define DE_RE_PIN 4 | |
#define MODE_SEND HIGH | |
#define MODE_RECV LOW | |
void setup() { | |
pinMode(DE_RE_PIN, OUTPUT); | |
digitalWrite(DE_RE_PIN, MODE_RECV); | |
Serial.begin(115200); | |
Serial2.begin(9600, SERIAL_8N1, 16, 17); // Rx, Tx | |
Serial2.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; | |
digitalWrite(DE_RE_PIN, MODE_SEND); | |
Serial2.write(buff, sizeof(buff)); | |
Serial2.flush(); // wait MODE_SEND completed | |
digitalWrite(DE_RE_PIN, MODE_RECV); | |
if (!Serial2.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
'Serial2' was not declared in this scope