Thursday, September 22, 2011

Task 31B -- Making Use of Interrupts

..
Again the schematic is from the Code Project/Interrupts site.

(I had to use a 150Ohm resistor because i couldn't find my push-switch!
  It didn't work quite as well - i should really find that switch! - but i
  suspect my wobbly hand had a lot to do with it; i could try 'de-bouncing'
  the 'switch', but delay() won't work inside the interrupt-triggered function  

  (find the switch, stoopid!)  )


This time, however,  the code makes use of a Hardware Interrupt, as follows:


/*
 * Project:     Interrupts_part_B_621task31
 * Author:     DaveAuld, tidied (not much! :-) ) by Jane-Maree Howard
 * Date:          23 Feb 2010
 * Platform:   Arduino 22
 * Purpose:    To demonstrate a simple interrupt-triggered LED-switch
 * Operation:  Description:
 *             "Set up the Arduino as per the schematic
 *              and upload the code below to the microprocessor.
 *              We will use the same schematic diagram and
 *              modify the code to make use of hardware interrupts.
 *              Now when you upload the code, the LED changes state
 *              whenever the button is pressed
 *              even though the code is still running the same long delay
 *              in the main loop.

 *              [This is code PART B in the downloaded source file.]"
 */
int pbIn = 0;                               // Interrupt 0 is on DIGITAL PIN 2!
int ledOut = 4;                           // The output LED pin
volatile int state = LOW;      // The input state toggle

void setup()
{
  // Set up the digital pin 2 to an Interrupt and Pin 4 to an Output
  pinMode(ledOut, OUTPUT);

  //Attach the interrupt to the input pin and monitor for ANY Change
  attachInterrupt(pbIn, stateChange, CHANGE);
}//setup()

void loop()
{
  //Simulate a long running process or complex task
  for (int i = 0; i < 100; i++)
  {
    // do nothing but waste some time
    delay(50); // Jane-Maree increases delay time from 10ms to 50ms
  }//for()
}//loop()

void stateChange()
{
  state = !state;
  digitalWrite(ledOut, state);
}//stateChange()
//END

2 comments:

  1. Another task bites the dist - but it's slow going!

    ReplyDelete
  2. Actually, i think the erratic behaviour of the switch is due also to the CHANGE criterion for triggering the interrupt. If i'm not quick enough, maybe TWO CHANGES occur in the blink of an eye, & nothing seems to have happened.. Hmmm..

    Debouncy-bouncy-bouncy.. (hehe)

    ReplyDelete