#define BTIME_PERIOD 10
#define DEBNC_PERIOD 50
#define BPIN1 8
#define BPIN2 6
#define NBTN 2
struct btn {
uint8_t pin;
uint8_t state;
uint32_t dtime_last_time;
};
struct btn btns[] = {
{ BPIN1, 0, 0 },
{ BPIN2, 0, 0 },
};
#define RTIME_PERIOD 100
#define RPIN1 4
#define RPIN2 5
#define NRLY 2
struct rly {
uint8_t pin;
uint8_t state;
};
struct rly rlys[] = {
{ RPIN1, 0 },
{ RPIN2, 0 },
};
uint32_t ctime;
uint32_t btime_last_time = 0;
uint32_t rtime_last_time = 0;
void
setup()
{
int i;
for (i = 0; i < NBTN; i++) {
pinMode(btns[i].pin, INPUT_PULLUP);
}
for (i = 0; i < NRLY; i++) {
pinMode(rlys[i].pin, OUTPUT);
digitalWrite(rlys[i].pin, LOW);
}
}
void
loop()
{
ctime = millis();
if (ctime > btime_last_time + BTIME_PERIOD) {
btime_last_time = 0;
// debounce tactile buttons
for (int bi = 0; bi < NBTN; bi++) {
struct btn *btn = &btns[bi];
if (digitalRead(btn->pin) == LOW) {
if (btn->dtime_last_time == 0) {
// start debounce timing
btn->dtime_last_time = ctime;
} else if (ctime > btn->dtime_last_time + DEBNC_PERIOD) {
// yes, pin as been LOW for DEBNC_PERIOD
btn->dtime_last_time = 0;
btn->state = 1; // button pressed
}
} else {
btn->dtime_last_time = 0; // nope, just a "bounce"
}
}
}
if (ctime > rtime_last_time + RTIME_PERIOD) {
rtime_last_time = 0;
// now evaluate buttons and change relays however
struct btn *btn;
btn = &btns[0];
if (btn->state == 1) {
btn->state = 0;
digitalWrite(rlys[1].pin, LOW);
digitalWrite(rlys[0].pin, HIGH);
}
btn = &btns[1];
if (btn->state == 1) {
btn->state = 0;
digitalWrite(rlys[0].pin, LOW);
digitalWrite(rlys[1].pin, HIGH);
}
}
}