From 43257b8acee3414abe766a7b1225f1a24cfeea0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?King=20K=C3=A9vin?= Date: Sat, 26 Jul 2014 20:30:39 -0700 Subject: [PATCH] use interrupts for switches --- pic/MDR/MDR.c | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/pic/MDR/MDR.c b/pic/MDR/MDR.c index 1d1a179..ef46cea 100644 --- a/pic/MDR/MDR.c +++ b/pic/MDR/MDR.c @@ -46,6 +46,7 @@ #define sleep() __asm sleep __endasm /* variables */ +static uint8_t switches; /* save the last switch state */ /* configuration bits */ uint16_t __at(_CONFIG1) __CONFIG1 = _FCMEN_ON & /* enable fail-safe clock monitor */ @@ -68,11 +69,13 @@ void init (void) { TRISB |= SWITCH1|SWITCH2; /* switches are inputs (with external pull-ups) */ TRISB &= ~(LED|MEMORY_CLK|MEMORY_DATA); /* LED is I2C memory are outputs */ led_off(); /* starting state */ -/* - IOC |= (SWITCH1|SWITCH2|SWITCH3|SWITCH4); // enable interrupt for the switches - GPIE = 1; // enable interrupt on GPIO - last_gpio = GPIO; // save current state + IOCIE = 1; /* enable interrupt on individual GPIO (typo in the lib) */ + IOCBP |= (SWITCH1|SWITCH2); /* enable interrupt when switch is released */ + IOCBN |= (SWITCH1|SWITCH2); /* enable interrupt when switch is pressed */ + switches = PORTB; /* save current switch state */ + +/* T1CON = _T1CKPS1 | _T1CKPS0; // set prescaler to 8 // 0 is set per default, but just be sure TMR1ON = 0; // stop timer 1 @@ -81,16 +84,32 @@ void init (void) { TMR1IF = 0; // clear interrupt PIE1 = 1; // enable timer 1 interrupt PEIE = 1; // enable timer interrupt - - GIE = 1; // enable interrups */ + GIE = 1; /* golablly enable interrupts */ } /* funcion called on interrupts */ /* interrupt 0 is only one on PIC16 */ static void interrupt(void) __interrupt 0 { + if (IOCIF) { /* GPIO interrupt (typo in library?) */ + if (IOCBF&(SWITCH1|SWITCH2)) { /* switch activity */ + switches ^= PORTB; /* figure out which switch changed */ + if (switches&SWITCH1) { /* switch 1 changed */ + if (PORTB&SWITCH1) { /* switch 1 released */ + led_off(); + } else { /* switch 1 pressed */ + led_on(); + } + } + if (switches&SWITCH2) { /* switch 2 changed */ + } + switches = PORTB; /* save current switch state */ + IOCBF &= ~(SWITCH1|SWITCH2); /* clear switch interrupts */ + } + IOCIF = 0; /* clear GPIO interrupt */ + } } void main (void) @@ -98,11 +117,6 @@ void main (void) init(); /* configure micro-controller */ led_on(); while (1) { /* a microcontroller runs forever */ - if (PORTB&SWITCH1) { - led_off(); - } else { - led_on(); - } // sleep(); /* sleep to save power */ } }