Created
September 30, 2024 21:06
-
-
Save ar00n/c2c0e064b6826cbebecbcf93d6f3aa02 to your computer and use it in GitHub Desktop.
Arduino program to control an 8 relay board from a Serial connection
This file contains hidden or 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
// Takes an input from Serial (11111110) and turns on 1-7 relays and turns off relay 8. | |
// the setup function runs once when you press reset or power the board | |
void setup() { | |
pinMode(2, OUTPUT); | |
pinMode(3, OUTPUT); | |
pinMode(4, OUTPUT); | |
pinMode(5, OUTPUT); | |
pinMode(6, OUTPUT); | |
pinMode(7, OUTPUT); | |
pinMode(8, OUTPUT); | |
pinMode(9, OUTPUT); | |
digitalWrite(2, HIGH); | |
digitalWrite(3, HIGH); | |
digitalWrite(4, HIGH); | |
digitalWrite(5, HIGH); | |
digitalWrite(6, HIGH); | |
digitalWrite(7, HIGH); | |
digitalWrite(8, HIGH); | |
digitalWrite(9, HIGH); | |
Serial.begin(9600); | |
} | |
// Array of relay board pins | |
char currentPins[8] = {'0', '0', '0', '0', '0', '0', '0', '0'}; | |
// Used to store input from serial connection (eg. 11111111) (all on) | |
char inputStr[8]; | |
// the loop function runs over and over again forever | |
void loop() { | |
while (Serial.available() == 0) {} //wait for data available | |
int inputLength = Serial.readBytesUntil('\n', inputStr, 9); //read until timeout | |
if (inputLength != 8) { | |
Serial.println("ERR_LEN"); | |
return; | |
} | |
for (int i = 0; i < inputLength; i++) { | |
if (inputStr[i] != '0' && inputStr[i] != '1') { | |
Serial.println("ERR_CHAR"); | |
return; | |
} | |
} | |
for (int i = 0; i < inputLength; i++) { | |
if (currentPins[i] == inputStr[i]) { | |
continue; | |
} | |
const int pin = i + 2; | |
if (inputStr[i] == '0') { | |
digitalWrite(pin, HIGH); | |
} else { | |
digitalWrite(pin, LOW); | |
} | |
currentPins[i] = inputStr[i]; | |
} | |
Serial.println("DONE"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment