CSC231 Arduino Interrupt Program Example

From dftwiki3
Revision as of 10:51, 1 December 2008 by Thiebaut (talk | contribs)
Jump to: navigation, search

--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 LED attached to Pin 13 
switches state.  A counter is incremented for every interrupt
and is displayed in the serial window.
*/


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++;
}