uni

University stuff
git clone git://git.margiolis.net/uni.git
Log | Files | Refs | README | LICENSE

tmr0.c (1353B)


      1 #include "tmr0.h"
      2 #include "util.h"
      3 
      4 #define TMR0_REQ_MAX 2
      5 
      6 struct timer_req {
      7 	ev_handler handler;	/* ISR callback */
      8 	uint16_t rate;		/* Interval */
      9 	uint16_t cnt;		/* Current time */
     10 };
     11 
     12 static void tmr0_isr(void) __interrupt;
     13 
     14 static struct timer_req	reqs[TMR0_REQ_MAX];
     15 
     16 static void
     17 tmr0_isr(void) __interrupt
     18 {
     19 	struct timer_req *r;
     20 	uint8_t i;
     21 
     22 	if (INTCONbits.TMR0IF != 1)
     23 		return;
     24 	for (i = 0; i < TMR0_REQ_MAX; i++) {
     25 		r = &reqs[i];
     26 		if (r->handler == NULL)
     27 			continue;
     28 		if (++r->cnt == r->rate) {
     29 			r->handler();
     30 			r->cnt = 0;
     31 		}
     32 	}
     33 	TMR0 = TMR0_DELAY;
     34 	INTCONbits.TMR0IF = 0; /* Clear interrupt flags */
     35 }
     36 
     37 void
     38 tmr0_init(void)
     39 {
     40 	memset(reqs, 0, sizeof(reqs));
     41 	OPTION_REG = 0;
     42 	OPTION_REG |= TMR0_CLK0 | TMR0_PRESCALAR_256;
     43 	TMR0 = TMR0_DELAY;
     44 	INTCONbits.TMR0IE = 1;	/* TMR0 Interrupt Enable */
     45 	INTCONbits.GIE = 1;	/* Global Interrupt Enable */
     46 	INTCONbits.PEIE = 1;	/* Peripheral Interrupt Enable */
     47 }
     48 
     49 void
     50 tmr0_delay_ms(uint16_t t)
     51 {
     52 	while (t--) {
     53 		while (INTCONbits.TMR0IF == 0)
     54 			;	/* nothing */
     55 		INTCONbits.TMR0IF = 0;
     56 		TMR0 = TMR0_DELAY;
     57 	}
     58 }
     59 
     60 int
     61 tmr0_set_event(ev_handler handler, uint16_t rate)
     62 {
     63 	struct timer_req *r;
     64 	uint8_t i;
     65 
     66 	for (i = 0; i < TMR0_REQ_MAX; i++) {
     67 		r = &reqs[i];
     68 		if (r->handler != NULL)
     69 			continue;
     70 		r->handler = handler;
     71 		r->rate = rate;
     72 		r->cnt = 0;
     73 		return (1);
     74 	}
     75 	return (0);
     76 }