Difference between revisions of "CSC231 Arduino Interrupt Program Example"
(New page: --~~~~ ---- <code><pre> /* testInterrupts D. Thiebaut An example program for testing interrupts. Hardware setup: Pin 3 is connected to Vcc through a 1KOhm resistor, and to ground thro...) |
|||
Line 7: | Line 7: | ||
D. Thiebaut | D. Thiebaut | ||
− | An example program for testing interrupts. | + | An example program for testing interrupts, taken from Arduino |
+ | documentation. | ||
Hardware setup: Pin 3 is connected to Vcc through a 1KOhm | Hardware setup: Pin 3 is connected to Vcc through a 1KOhm |
Revision as of 09:54, 1 December 2008
--D. Thiebaut 14:53, 1 December 2008 (UTC)
/*
testInterrupts
D. Thiebaut
An example program for testing interrupts, taken from Arduino
documentation.
Hardware setup: Pin 3 is connected to Vcc through a 1KOhm
resistor, and to ground through a pushbutton switch. If the
switch is not pressed, Pin 3 sees a high voltage through the
resistor. If the switch is pressed, Pin 3 sees a low voltage
through the switch, connecting it to Ground.
Every time the user presses or depresses the switch, an
interrupt is generated and the LED attached to Pin 13
switches state. A counter is incremented for every interrupt
and is displayed in the serial window.
*/
int pin = 13;
/* volatile variables are forced to reside in RAM,
not in registers */
volatile int state = LOW;
volatile int counter= 0;
volatile int lastCounter = -1;
/* -------------------------------------------------
setup: defines the hardware setup, and the blink function
as the one to be called whenever the level on Pin
3 changes
--------------------------------------------------- */
void setup() {
Serial.begin(9600);
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);
}
/* -------------------------------------------------
loop: if there's a change in the counter, show the
new values on the LED and by displaying the
counter
--------------------------------------------------- */
void loop() {
if ( counter != lastCounter ) {
digitalWrite(pin, state);
Serial.println( counter );
lastCounter = counter;
}
}
/* -------------------------------------------------
blink: this is the interrupt routine. It must be
a void function, without parameters. It is called
at random times, asynchronously to the rest of this
code, and changes the variable state and increments
the counter.
--------------------------------------------------- */
void blink() {
state = !state;
counter++;
}