Wednesday, October 26, 2011

Task 40 - Timer0 Polling routine - toggle LED on/off

/*
 * Project:      Timer_0_Polling_Experiment
 * Author:      Peter Brook tidied by Jane-Maree Howard on..
 * Date:          ..Wednesday 26/10/2011
 * Platform:    Arduino 22
 * Purpose:     To visually demonstrate Timer0 polling
 * Operation:  Polls Timer0 prescaled by 1024; toggles LED on/off every second
 *      Declare: toggle variable; counter vble; ToggleLED() routine 
 *      Setup():  Serial port @9600baud; Prints opening statement; delays 5 seconds
 *                      set TImerMaSK0 to zero - turn of Timer0 interrupt;
 *                      set Timer/CounterControlRegister0B to DEC5; prescaler /s by 1024;
 *      Loop():    idle until TimerInterruptFlagRegister0 == 1;
 *                      reset TIFR0; count 1 'tick'(from 0 to 60, 61 'ticks');
 *                      @ 60'ticks', reset 'ticks' & toggle LED on/off
 */
int     state = 1;        // LED toggle vble - init. OFF!      
byte  ticks = 0;        // counts up towards 60, the LED toggle value

void setup()
{
  Serial.begin(9600);  // Serial port @ 9600 baud
  Serial.println("\n\tInitial state is OFF\n\t");
  delay(5000);            // wait 5 seconds 
  // initialize digital pin 13 as an output.
  // Pin 13 has an LED connected on most Arduino boards:

  pinMode(13, OUTPUT);
  //after this, can't use 'delay() any more
  TIMSK0 = 0;          // turn off Interrupt for Timer0
  TCCR0B = 5;         // Prescaler divides by 1024;  BIN101 = DEC5
}//setup()

void loop()
{
   while(byte(TIFR0 &0x01) ==0) // loop till flag goes up
   {/* do nothing */}                       
   TIFR0 = 1;                // clear flag
   ticks++;                     // count a tick
 
   if (ticks == 60)          // preset value
   {
      ticks=0;                  // reset 'ticks'
      Serial.print("\tTT ");
      ToggleLED();        // toggle LED
   }//if()
}// loop()

void ToggleLED()
{
  if (state==1)
  {
    digitalWrite(13,LOW);                    // LED turns OFF
    state = 0;                                          // toggle 'state' vble
    Serial.print("I've toggled OFF");   // Serial Monitor o/p
  }//if()
  else
  {
    digitalWrite(13,HIGH);                    // LED turns ON
    state=1;                                             // toggle 'state' vble
    Serial.println("I've toggled ON "); // Serial Monitor o/p
  }//else()
}//ToggleLED() 



In the code, the initial state of the on-board LED (pin 13) is OFF.


The SM output records the first toggle ("TT") & the LED
(of course ) stays OFF.

From then on, the LED's recorded toggled state matches that of the on-board LED (pin 13)

No comments:

Post a Comment