/* ------------------------------------------------------------ */ /* switch debounce */ /* * 10 Jul 2014 dpa Switch debounce example code * * A bumper switch is connected to the microprocessor * PORTE_DATA, pin 7, configured as an input, and pulled * high by a 4.7k resistor. Switch closure pulls the * pin to ground. * * Debounce code samples the switch a 1kHz, looking * for 6 consecutive switch closures or openings. * So latency is 6ms. * * PORTE_DATA and PORTE_DDR are specific to the MC68332 * processor. Change these to match your micro hardware ports. * * Code inspired by excellent online article from: * http://www.ganssle.com/debouncing.htm */ /* ------------------------------------------------------------ */ #define BUMPER 0x80 /* MC68332 PORTE pin 7 */ #define OPEN 0 #define CLOSED 1 #define SWITCH_CLOSED_DEBOUNCE 6 #define SWITCH_OPEN_DEBOUNCE 6 /* Note that debounce timing for OPEN and CLOSED can be different * if required by the physical switch. */ /* ------------------------------------------------------------ */ /* debounce state vector, called from 1kHz interrupt */ void (*switch_state)(); /* vector for debounce Finite State Machine */ /* ------------------------------------------------------------ */ /* global debounce output variable */ int bump_switch; /* bumper switch state, read by bumper behavior code */ /* ------------------------------------------------------------ */ /* local debounce variables */ int switch_count; /* debounce count */ /* ------------------------------------------------------------ */ void switch_state1() /* switch open, looking for closed */ { void extern switch_state2(); if ((PORTE_DATA & BUMPER) == 0) { /* 0 means switch has closed */ switch_count++; if (switch_count > SWITCH_CLOSED_DEBOUNCE) { bump_switch = CLOSED; switch_count = 0; switch_state = switch_state2; } } else { switch_count = 0; /* reset switch count if switch not closed or bouncing */ } } /* ------------------------------------------------------------ */ void switch_state2() /* switch closed, looking for open */ { if (PORTE_DATA & BUMPER) { /* true means switch has opened */ switch_count++; if (switch_count > SWITCH_OPEN_DEBOUNCE) { bump_switch = OPEN; switch_count = 0; switch_state = switch_state1; } } else { switch_count = 0; /* reset switch count if switch not open or bouncing */ } } /* ------------------------------------------------------------ */ /* switch debounce. run from 1kHz interrupt */ void switch_debounce_service() { if (switch_state) (*switch_state)(); } /* ------------------------------------------------------------ */ int switch_init() { PORTE_DDR &= 0xef; /* set PORTE pin 7 to input */ switch_count = 0; /* reset switch count */ bump_switch = OPEN; /* init switch state to OPEN */ switch_state = switch_state1; /* init switch state looking for closed */ return 0; } /* ------------------------------------------------------------ */ /* EOF */