I'm sure I'm making a simple newbie mistake here. What I need to happen is do some work when an interrupt (INT 0) is detected; like light an LED and also print some text on an LCD. When I run the sketch below, the LED stays constantly lit and the LCD prints the text regardless of any interrupt being detected (I have a sensor attached to it--which I know works fine).
Any tips/advice you can give would be greatly appreciated!
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x20,20,4);
volatile boolean flag;
const int led = 5;
// Interrupt Service Routine (ISR)
void isr ()
{
flag = true;
} // end of isr
void setup ()
{
attachInterrupt (0, isr, RISING); // attach interrupt handler
pinMode (led, OUTPUT);
lcd.init(); // initialize the lcd
lcd.backlight();
} // end of setup
void loop ()
{
if (flag)
{
// interrupt has occurred
digitalWrite(led,HIGH);
lcd.clear();
lcd.print("Detected");
}
} // end of loop
I'm a newbie to Arduino myself and am yet to get my hands on any hardware though I have got some programming background from many years ago.
I know you have solved the issue by initialising the flag as suggested, though I thought I'd chip in and add to what has already been said.
I'm not sure how much programming experience you have but one thing I learn early was "uninitialized variables are bad news". The reason is they can cause unpredictable behaviour.
This is especially true when you consider in C (unlike most other programming languages) there is no true boolean variables - they are stored as unsigned integers.
a value of 0 is interpreted as False
any other (non-zero) value is interpreted as true.
This means that is you define a boolean variable it's more than likely to be "true" - unless you initialise it to 0 (false).
If you already know this then feel free to ignore me an hopefully it helps someone else...
I'm a newbie to Arduino myself and am yet to get my hands on any hardware though I have got some programming background from many years ago.
I know you have solved the issue by initialising the flag as suggested, though I thought I'd chip in and add to what has already been said.
I'm not sure how much programming experience you have but one thing I learn early was "uninitialized variables are bad news". The reason is they can cause unpredictable behaviour.
This is especially true when you consider in C (unlike most other programming languages) there is no true boolean variables - they are stored as unsigned integers.
a value of 0 is interpreted as False
any other (non-zero) value is interpreted as true.
This means that is you define a boolean variable it's more than likely to be "true" - unless you initialise it to 0 (false).
If you already know this then feel free to ignore me an hopefully it helps someone else...