/* File **********THREAD1.C*********** Statically allocated thread example Jonathan W. Valvano */ #include #include struct TCB { struct TCB *Next; /* Link to Next TCB */ unsigned char *SP; /* Stack Pointer */ unsigned char Id; /* 1,2 or 4 */ unsigned char MoreStack[50]; /* additional stack */ unsigned char CCR; /* Initial CCR */ unsigned char RegB; /* Initial RegB */ unsigned char RegA; /* Initial RegA */ unsigned int RegX; /* Initial RegX */ unsigned int RegY; /* Initial RegY */ void (*PC)(void); /* Initial Program Counter */ }; int Sub(int j){ int i; PORTC=1; /* Port C shows which program is being executed */ i=j+1; return(i);} void ProgA(){ int i; i=5; while(1) { PORTC=2; i=Sub(i);}} void ProgB(){ int i; i=6; while(1) { PORTC=4; i=Sub(i);}} typedef struct TCB TCBType; typedef TCBType * TCBPtr; TCBType sys[3]={ { &sys[1], /* Pointer to Next */ &sys[0].MoreStack[49], /* Initial SP */ 1, /* Id */ { 0}, 0x40,0,0,0,0, /* CCR,B,A,X,Y */ ProgA, }, /* Initial PC */ { &sys[2], /* Pointer to Next */ &sys[1].MoreStack[49], /* Initial SP */ 2, /* Id */ { 0}, 0x40,0,0,0,0, /* CCR,B,A,X,Y */ ProgA, }, /* Initial PC */ { &sys[0], /* Pointer to Next */ &sys[2].MoreStack[49], /* Initial SP */ 4, /* Id */ { 0}, 0x40,0,0,0,0, /* CCR,B,A,X,Y */ ProgB, } }; /* Initial PC */ TCBPtr RunPt; /* Pointer to thread currently running */ #pragma interrupt_handler ThreadSwitch() void ThreadSwitch(){ asm(" ldx _RunPt\n" " sts 2,x"); RunPt=RunPt->Next; PORTB=RunPt->Id; /* PortB shows which thread is running */ asm(" ldx _RunPt\n" " lds 2,x"); TOC3=TCNT+20000; /* Thread runs for 10 ms */ TFLG1=0x20; } /* acknowledge by clearing TOC3F */ main(){ DDRC=0xFF; /* PortC are outputs */ RunPt=&sys[0]; /* Specify first thread to run */ asm(" sei"); TOC3vector=&ThreadSwitch; TFLG1 = 0x20; /* Clear OC3F */ TMSK1 = 0x20; /* Arm TOC3 */ TOC3=TCNT+20000; PORTB=RunPt->Id; asm(" ldx _RunPt\n" " lds 2,x\n" " cli\n" " rti");} /* Launch First Thread */