Hey guys I have a setup with 2 mercury sensors which control a solenoid when either mercury switch is activated. My problem is that the mercury switches have a lot of bounce in them and I'm not sure how to integrate a debouncer into my code. The time from the signal of the mercury switch to the firing of the solenoid is key to my application so I'm trying not to delay that firing too long. I attached my code for any guidance. I'm new at this so please bear with me.
const int RightTilt = 2; // the pin that the Right Mercury Sensor is attached to
const int LeftTilt = 4; // the pin that the Left Mercury Sensor is attached to
const int Solenoid = 12; // the pin that the Solenoid is attached to
int FallCounter = 0; // Counter for the number of falls presses
int RightState = 0; // current state of the Right Sensor
int LeftState = 0; // current state of the Left Sensor
int lastButtonStateLeft = 0; // previous state of the Left Sensor
int lastButtonStateRight = 0; // previous state of the Right Sensor
void setup() {
// initialize the Sesnor pins as inputs:
pinMode(RightTilt, INPUT);
pinMode(LeftTilt, INPUT);
// initialize the Solenoid as an output:
pinMode(Solenoid, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the Sensor input pins:
RightState = digitalRead(RightTilt);
LeftState = digitalRead(LeftTilt);
// compare the buttonState to its previous state
if (RightState != lastButtonStateRight or LeftState != lastButtonStateLeft) {
// if the state has changed, increment the counter
if (RightState ==LOW or LeftState ==LOW) {
// if the current state is HIGH then a Sensor
// went from off to on:
FallCounter++;
digitalWrite(Solenoid, HIGH);
delay(300);
digitalWrite(Solenoid, LOW);
Serial.println("ON");
Serial.print("Number of falls: ");
Serial.println(FallCounter);
}
else {
// if the current state is LOW then a Sensor
// went from on to off:
digitalWrite(Solenoid, LOW);
Serial.println("OFF");
}
// save the current state as the last state,
//for next time through the loop
lastButtonStateRight = RightState;
lastButtonStateLeft = LeftState;
}
}