This is my attempt to realise multitasking (well almost) through interrupts. In this example, Task 1 is: Toggle LED connected to PB1 at 2Hz (Timer 1 is used, OCR1 can hold values upto 65535), Task 2 is: Toggle LED connected to PB3 at 61Hz (since Timer2 OCR2 is 8bit). It seems to be working too.
- Have i understood the concept of multitasking right?
- How can i allocate time slices for a "Task" or is it not possible in this case?
- Can i replace the "Task" from toggling LED to ADC measurement or receiving bytes on USART? Or would that be realised differently?
Here is my Program:
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#define COMP_REG_VAL 61250
void timer1_init()
{
DDRB |= 1<<PB1; // Set PortB Pin1 as output
TIFR1 |= 1<<OCF1A; // Clear Output compare flag
TIMSK1 |= 1<<OCIE1A; // Enable Interrupt on Output compare match
TCCR1B |= ( (1<<CS12) | (1<<WGM12) ); // Prescaler Fosc/256 ===> 62500
}
void timer2_init()
{
DDRB |= 1<<PB3; // Set Port B pin3 as Output
TIFR2 |= 1<<OCF2A; // Clear Output compare flag
TIMSK2 |= 1<<OCIE2A; // Enable Interrupt on Output compare match
TCCR2A |= ( (1<<WGM20) | (1<<WGM21) ); //FAST PWM mode
TCCR2B |= ( (1<<WGM22) | (1<<CS22) | (1<<CS21) | (1<<CS20) ); //Fast PWM MOde, Prescaler=fosc/1024
}
int main (void)
{
sei();
timer1_init();
timer2_init();
OCR1A = COMP_REG_VAL/2;
OCR2A = 255;
while(1)
{
}
}
ISR(TIMER1_COMPA_vect)
{
PORTB ^= (1<<PB1); // Toggle Pin when overflow occurs
}
ISR(TIMER2_COMPA_vect)
{
PORTB ^= (1<<PB3); // Toggle Pin when overflow occurs
}