/*
Arduino Forum
Topics: Flipflop type of code?
Category: Using Arduino
Sub-Category: Programming Questions
Link: https://forum.arduino.cc/t/flipflop-type-of-code/1156858/25
*/
#define lockPin 2
#define unlockPin 3
#define mirrorPin 9
#define ledPin 11
#define PULSE_DELAY 50
#define DEBOUNCE_PERIOD 10
typedef struct {
bool input;
bool state;
unsigned long startDebounceTime;
bool debounce(bool bounce);
} debounce_t;
bool debounce_t::debounce(bool bounce) {
bool prevPounce = input;
input = bounce;
if (bounce & !prevPounce) {
startDebounceTime = millis();
}
if (bounce != state) {
if (millis() - startDebounceTime >= DEBOUNCE_PERIOD) {
state = bounce;
}
}
return state;
}
debounce_t lock;
debounce_t unlock;
bool locked;
bool prevLocked;
bool pulse;
unsigned long startPuleTime;
void setup() {
Serial.begin(9600);
pinMode(lockPin, INPUT_PULLUP);
pinMode(unlockPin, INPUT_PULLUP);
pinMode(mirrorPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
lock.debounce(!digitalRead(lockPin));
unlock.debounce(!digitalRead(unlockPin));
prevLocked = locked;
// Reset-Set (Reset Dominant)
// --------------------------
// | LOCK | UNLOCK | LOCKED |
// --------------------------
// | 0 | 0 | X |
// | 0 | 1 | 0 |
// | 1 | 0 | 1 |
// | 1 | 1 | 0 |
// --------------------------
// X = LAST STATE
// locked = (locked | lock.state) & !unlock.state;
// Set-Reset (Set Dominant)
// --------------------------
// | LOCK | UNLOCK | LOCKED |
// --------------------------
// | 0 | 0 | X |
// | 0 | 1 | 0 |
// | 1 | 0 | 1 |
// | 1 | 1 | 1 |
// --------------------------
// X = LAST STATE
locked = (locked & !unlock.state) | lock.state;
digitalWrite(ledPin, locked);
PulseCondition();
digitalWrite(mirrorPin, pulse);
}
void PulseCondition() {
if (locked != prevLocked) {
startPuleTime = millis();
pulse = true;
}
if (pulse) {
if (millis() - startPuleTime >= PULSE_DELAY) {
pulse = false;
}
}
}LOCK
UNLOCK
LOCKED
MIRROR
NC
NO
NC
NO