I have a relay that switches between two LEDs if I enter any value into the serial port.
My goal is to be able to start the loop by entering any key into the serial port, then when I press the button for the loop to stop, press the button again and the loop continues.
I made a simple loop, and if the interrupt pin receives a RISING signal it should go into a debounce function, then return to the loop.
I can get the loop to work by using the serial port, but as soon as the interrupt pin receives a signal it just starts the loop over again. If I press the button before I start the loop the LEDs will cycle as intended. I just need to reverse this essentially so that the button will cycle the LEDs then return to the loop.
Thanks for looking, any and all help is appreciated.
I made a little video to help explain what I'm trying to do:
https://drive.google.com/file/d/0B-RQblMzZ2qOdXcwUWRUd1Y5bDQ/view?usp=sharing
Here is my code:
int relay = 12; //sets relay to 12
int pause = 1500; //sets pause
const int buttonPin = 2; //sets button to 2
int relayState = HIGH; //sets the relay state to high
int buttonState; //the current reading of the button pin
int lastButtonState = LOW; //the previous reading from button pin
unsigned long lastDebounceTime = 0; //the last time the output pin was toggled
unsigned long debounceDelay = 50; //the deounce time;
void setup(){
Serial.begin(9600); //open serial port at 9600
Serial.println("Enter any key"); //takes the reading of any value
pinMode(relay,OUTPUT); //designates the relay pin as output
pinMode(buttonPin,INPUT); //designates the button pin as input
attachInterrupt(0,emrgcy,RISING); //sets pin 2 as the interrupt pin, if it recieves a high signal it will go into the emrgcy function
}
void loop() {
{ if(Serial.available()>0) //when the serial port receives a value greater than zero it will begin the
//loop to the relay
{
digitalWrite(relay,HIGH);
delay(pause);
digitalWrite(relay,LOW);
delay(pause);
}
}
}
void emrgcy(){
int reading = digitalRead(buttonPin); //read the state of the switch into a variable
digitalWrite(relay, relayState); //sets the relay to high
if (reading != lastButtonState){ //if the switch changed, due to noise or pressing;
lastDebounceTime = millis(); //reset the debouncing timer
}
if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState){
buttonState = reading;
if(buttonState == HIGH){ //only toggle the LED if the new button state is high
relayState = !relayState;
}
}
}
digitalWrite(relay, relayState);
lastButtonState = reading;
}