Difference between revisions of "CSC231 Arduino Interrupt Program Example"
Line 69: | Line 69: | ||
</pre></code> | </pre></code> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | [[Category:CSC231]][[Category:Arduino]] |
Latest revision as of 18:33, 8 October 2010
--D. Thiebaut 14:53, 1 December 2008 (UTC)
/*
testInterrupts
D. Thiebaut
An example program for testing interrupts.
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 counter is incremented.
The loop function checks whether the counter changed, and if
so, switches the state of the LED and displays the value of
the counter.
*/
int pin = 13;
int state = LOW;
int lastCounter = -1;
/* volatile variables are forced to reside in RAM, not in registers */
volatile int counter= 0;
/* -------------------------------------------------
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 ) {
state = !state;
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() {
counter++;
}