Akash Kollipara
Published

Preemptive Multitasking Scheduler for AVR

Multitasking on AVR

IntermediateFull instructions provided3,035
Preemptive Multitasking Scheduler for AVR

Things used in this project

Story

Read more

Code

Scheduler Source File

C/C++
/*
 * main.c
 *
 * Created: 27-06-2016 09:29:09 PM
 * Author : Akash Kollipara
 */ 

uint8_t R=0, currentTaskId=0, nextTaskId=0;

typedef enum status{t_ready, t_busy} status;

typedef struct TaskControlBlock		//defines and controls a task for this scheduler
{
	uint8_t task_id;
	enum status state;
	unsigned int stack_pointer_begin;
	unsigned int stack_pointer_end;
	void (*fnctpt)(void);
} tcb;
tcb task[maxTask];

int main(void)
{
    	cli();
	//initialization 
	timer_init();				//initializes timer for scheduler
	Neutron_kernel_init();		//initializes the kernel
	
	//setting up first task parameters
	StackPointer=task[0].stack_pointer_begin;
	currentTaskId=task[0].task_id;
	if(task[0].state==t_ready)
		task[0].state=t_busy;
	sei();
	//running first task
	task[0].fnctpt();
	
    	while (1);
}

ISR(TIMER0_COMPA_vect)
{
	uint8_t q=0;
	PORTB^=(1<<PORTB5);
	cli();
	//getting the termination pointer of individual stacks
	task[currentTaskId].stack_pointer_end=StackPointer;
	for(q=0; q<maxTask; q++)
	{
		if(task[q].state==t_ready)
		{
			//setting up task parameters 
			task[q].state=t_busy;
			currentTaskId=task[q].task_id;		//sets task_id for saving context in corresponding task's stack
			StackPointer=task[q].stack_pointer_begin;
			sei();
			task[q].fnctpt();		//execute task if not priorly executed
		}
		R=q;
	}
	if(R==maxTask-1)	//checks if all the tasks are in queue
	{
		if(nextTaskId==maxTask) nextTaskId=0;		//resets the the task_id if it exceeds maxTask
		if(task[nextTaskId].state==t_busy)
		{
			//pointing stack to start context restoring
			StackPointer=task[nextTaskId].stack_pointer_end;
			currentTaskId=nextTaskId;				//when next interrupt occurs, this var is used as the task_id for getting stack end pointer
			nextTaskId=task[nextTaskId].task_id+1;	//increments the task_id for next call of scheduler
		}
	}
}

Credits

Akash Kollipara

Akash Kollipara

7 projects • 12 followers

Comments