I'm having trouble following a simple push button code interrupt example. When I push a button it triggers an interrupt and lights up and LED.
However, I wrote code into the main program loop to blink an LED. When the interrupt occurs I wanted it to keep the LED lit up, or at least show that the interrupt occurred. I'm not sure how to do this because I cannot add "delay" or "serial.Print" into the ISR. Right now the Arduino just keeps blinking away no matter what, even when my INPUT pin goes HIGH...as if it never sees the interrupt. Any suggestions appreciated.
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
volatile int buttonState = 0;
void setup() {
// put your setup code here, to run once:
pinMode (ledPin, OUTPUT);
pinMode (buttonPin, INPUT);
attachInterrupt(0,pin_ISR, CHANGE);
}
void loop() {
digitalWrite (ledPin, LOW);
delay(100);
// put your main code here, to run repeatedly:
digitalWrite (ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay (100);
}
void pin_ISR() {
buttonState = digitalRead(buttonPin);
digitalWrite(ledPin, buttonState);
}
}
You're using a Ferrari to carry a peanut. It carries it pretty well and you get practise driving the Ferrari but it's still the wrong tool for the job.
It is not totally clear to me what you want to do. You want the LED to light and stay lit for some detectable amount of time, like 500ms? That has a higher priority than the 200ms OFF / 100ms ON cycle? Every time the button CHANGEs or just when the button changes to HIGH?
If you want to continue practicing with interrupts, one possible solution to your poor specification might be...
const int LED_OFF_TIME = 200; //milliseconds - normal blink rate dark period
const int LED_ON_TIME = 100; //milliseconds - normal blink rate light period
void loop() {
digitalWrite(ledPin, LOW || buttonState); //if button is held down, the LED won't go off
delay(LED_OFF_TIME);
digitalWrite(ledPin, HIGH);
delay(LED_ON_TIME);
}
Thank-you, I will try that. I will try to clarify. I'm attempting to have the Arduino sleep (low power), then wake up with an interrupt and do a task, then back to sleep until the interrupt occurs again. I haven't gotten to the sleep part so I didn't mention that but hopefully that helps to clarify.
In more general terms the usual way to respond to an interupt is something like
void main() {
if (buttonState != last_buttonState) {
// an interupt occurred- do something about it
// then remember for next time.
last_buttonState=buttonState
};
// other stuff here
}
As you probably already know a single press of a mechanical button switch is likely to generate many interupts due to switch bounce so your program will have to cope with that.