Archive for the ‘Uncategorized’ Category

Scheduler for Arduino – Blink LEDs periodically

#include

//variables for LED blinking
boolean flag0 = 0;
boolean flag1 = 0;
boolean flag2 = 0;
boolean flag3 = 0;
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;
boolean toggle3 = 0;

//counter for tasks
long int count = 0;

//variable to store number of times button pressed
int buttonpress = 0;

void setup()
{

//set pins as outputs
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);

//Serial display to show number of times button pressed
Serial.begin(9600);
pinMode(A0, INPUT);

//Enable watchdog timer with timeout of 4 seconds
wdt_enable(WDTO_4S);

cli();//stop interrupts

//set timer1 interrupt at 1Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 1 hz increments
OCR1A = 15625;// = (16*10^6) / (15625 * 1024) (1024 Prescalar)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12 and CS10 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);

PCICR =0x02; // Enable PCINT1 interrupt
PCMSK1 = 0b00000001; // Select Pin A0

sei();//allow interrupts

}//end setup

ISR(TIMER1_COMPA_vect)
{//timer1 interrupt 1 Hz

count++;

if(count == 801)
{
count = 0;
}

flag0 = 0;

if(count % 2 == 0)
flag1 = 0;

if(count % 4 == 0)
flag2 = 0;

if(count % 8 == 0)
flag3 = 0;

}

ISR(PCINT1_vect)
{ // Interrupt service routine. Interrupt on A0 pin change

if (digitalRead(A0)==0)
{
buttonpress++;
Serial.print("button press = ");
Serial.println(buttonpress);
}
}

void loop()
{

if(flag0 == 0) // Task1 – Blink LED every 1 s on pin 10
{
digitalWrite(10,toggle0);
toggle0 = !toggle0;
flag0 = 1;
}

if(flag1 == 0) // Task2 – Blink LED every 2 s on pin 11
{
digitalWrite(11,toggle1);
toggle1 = !toggle1;
flag1 = 1;
}

if(flag2 == 0) // Task3 – Blink LED every 4 s on pin 12
{
digitalWrite(12,toggle2);
toggle2 = !toggle2;
flag2 = 1;
}

if(flag3 == 0) // Task 4 – Blink LED every 8 s on pin 13
{
digitalWrite(13,toggle3);
toggle3 = !toggle3;
flag3 = 1;
}

//Reset the watchdog timer
wdt_reset();
}