pic_therm

PIC16F877A and BME280 thermometer
git clone git://git.margiolis.net/pic_therm.git
Log | Files | Refs | README | LICENSE

tmr0.c (1355B)


      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 	/* Clear interrupt flags */
     35 	INTCONbits.TMR0IF = 0;
     36 }
     37 
     38 void
     39 tmr0_init(void)
     40 {
     41 	memset(reqs, 0, sizeof(reqs));
     42 	OPTION_REG = 0;
     43 	OPTION_REG |= TMR0_CLK0 | TMR0_PRESCALAR_256;
     44 	TMR0 = TMR0_DELAY;
     45 	INTCONbits.TMR0IE = 1;	/* TMR0 Interrupt Enable */
     46 	INTCONbits.GIE = 1;	/* Global Interrupt Enable */
     47 	INTCONbits.PEIE = 1;	/* Peripheral Interrupt Enable */
     48 }
     49 
     50 void
     51 tmr0_delay_ms(uint16_t t)
     52 {
     53 	while (t--) {
     54 		while (INTCONbits.TMR0IF == 0)
     55 			;	/* nothing */
     56 		INTCONbits.TMR0IF = 0;
     57 		TMR0 = TMR0_DELAY;
     58 	}
     59 }
     60 
     61 int
     62 tmr0_set_event(ev_handler handler, uint16_t rate)
     63 {
     64 	struct timer_req *r;
     65 	uint8_t i;
     66 
     67 	for (i = 0; i < TMR0_REQ_MAX; i++) {
     68 		r = &reqs[i];
     69 		if (r->handler != NULL)
     70 			continue;
     71 		r->handler = handler;
     72 		r->rate = rate;
     73 		r->cnt = 0;
     74 		return (0);
     75 	}
     76 	return (-1);
     77 }