Complete beginner here, trying to learn...
I am trying to use a normally closed push button to change the state of a relay each time the button is pushed and released. I'm trying to do this by taking the 'contacts closing' event (on pin 2) to switch power on or off to pin 12. I started with the basic 'Button' sketch and modified it. Here's what I presently have:
// Constants:
const int SwitchPin = 2; // the pin that the switch is attached to
const int RelayPin = 12; // the pin that the relay is attached to
// Variables:
int SwitchState = 0; // current state of the switch
int PreviousSwitchState = 0; // previous state of the switch
int RelayState = 0; // current state of relay pin
void setup() {
// initialize switch pin (2) as an input:
pinMode(SwitchPin, INPUT);
// initialize relay pin (12) as an output:
pinMode(RelayPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
//Look for switch Off to On event
void loop() {
// read the switch pin (2):
SwitchState = digitalRead(SwitchPin);
// read the relay pin (12):
RelayState = digitalRead(RelayPin);
// compare the SwitchState to its previous state
if (SwitchState != PreviousSwitchState) {
// if the state has changed, check change direction
if (SwitchState == HIGH){
// if the current state is HIGH then the switch
// went from off to on, ie the NC push button was released:
if (SwitchState == LOW)
RelayState = HIGH;
else
RelayState = LOW;}
}
}
The sketch compiles and uploads without problem. I tested my Arduino (a Mega 2560), using Blink, it works fine.
I wired a breadboard as per the attached file (hope this is readable). On opening and then closing the contacts, I expected to see the voltage on pin 12 change from 0 to 5V, or vice versa. Nothing happens - it's always zero.
I tried changing the output to pin 13, hoping to see the on board LED light and then extinguish - this didn't happen either. The problem seems to lie with the code.
Would someone be kind enough to help me out here?
Many thanks,
Ian