Created
December 14, 2022 23:39
-
-
Save wamphlett/f488a7d1218c25b557727ffb41353346 to your computer and use it in GitHub Desktop.
Ultracade Power Management
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
// store informatino about each pin mapping | |
typedef struct mapping_ { | |
int switchPin; // the switch pin | |
int relayPin; // the relay pin | |
int lastSwitchState; // the last recorded switch state | |
int currentRelayState; // the current state of the relay | |
unsigned long lastDebounceTime; // the last time the switch state changed | |
} mapping_t; | |
// switch pin to relay pin mapping | |
mapping_t pinMapping[] = { | |
{4, 3}, | |
{6, 5}, | |
}; | |
// define a delay before changing the current relay state to protect | |
// against debounce | |
unsigned long debounceDelay = 50; | |
void setup() { | |
// for each mapping, configure the relevant pins | |
for (int x = 0; x < sizeof(pinMapping)/sizeof(pinMapping[0]); x++) { | |
// configure the pin modes | |
pinMode(pinMapping[x].switchPin, INPUT_PULLUP); | |
pinMode(pinMapping[x].relayPin, OUTPUT); | |
// ensure the current and last states are initiated | |
int currentRelayState = digitalRead(pinMapping[x].switchPin); | |
pinMapping[x].lastSwitchState = currentRelayState; | |
pinMapping[x].currentRelayState = currentRelayState; | |
pinMapping[x].lastDebounceTime = millis(); | |
} | |
} | |
void loop() { | |
for (int x = 0; x < sizeof(pinMapping)/sizeof(pinMapping[0]); x++) { | |
// read the current state of the switch | |
int currentState = digitalRead(pinMapping[x].switchPin); | |
// if the current switch state does not match the previous switch state, | |
// record the time the change was made and update the last switch state. | |
if (currentState != pinMapping[x].lastSwitchState) { | |
pinMapping[x].lastDebounceTime = millis(); | |
pinMapping[x].lastSwitchState = currentState; | |
} | |
// if the switch state is still different than the current relay state | |
// after the defined debounce time, update the relay state to match the new | |
// switch state | |
if ((millis() - pinMapping[x].lastDebounceTime) > debounceDelay) { | |
if (pinMapping[x].currentRelayState != currentState) { | |
pinMapping[x].currentRelayState = currentState; | |
} | |
} | |
// write the current relay state to the relay pin | |
digitalWrite(pinMapping[x].relayPin, pinMapping[x].currentRelayState); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment