Test Switches from Priyank Bolia on Vimeo.
#include <avr/io.h>
#include <util/delay.h>
void delay_ms(uint16_t t)
{
while (t--)
_delay_ms(1);
}
void leds_update(uint8_t index)
{
uint8_t mask = _BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4) | _BV(PB5)
| _BV(PB6) | _BV(PB7);
if (index < 8)
{
PORTB = (PORTB & ~mask) | _BV(index);
}
}
int main (void)
{
uint8_t selection;
uint8_t state_sw0, state_sw1;
uint8_t prev_state_sw0, prev_state_sw1;
/* Setup PB0-7 as outputs */
DDRB = _BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4) | _BV(PB5)
| _BV(PB6) | _BV(PB7);
/* Setup PC0 and PC1 as inputs with pull-up */
DDRC &= ~(_BV(DDC0) | _BV(DDC1));
PORTC |= _BV(DDC0) | _BV(DDC1);
/* The first selected led is led 0 */
selection = 0;
leds_update(selection);
/* Init the switches state */
prev_state_sw0 = 0;
prev_state_sw1 = 0;
/* Main loop */
for(;;)
{
/* Read the current switch state */
state_sw0 = (PINC & _BV(DDC0));
state_sw1 = (PINC & _BV(DDC1));
if (state_sw0 && !prev_state_sw0)
{
/* The switch 0 has been pressed */
if (selection < 7)
{
selection++;
leds_update(selection);
}
}
if (state_sw1 && !prev_state_sw1)
{
/* The switch 1 has been pressed */
if (selection > 0)
{
selection--;
leds_update(selection);
}
}
prev_state_sw0 = state_sw0;
prev_state_sw1 = state_sw1;
/* Wait for 20ms */
delay_ms(20);
}
return(0);
}
#include <util/delay.h>
void delay_ms(uint16_t t)
{
while (t--)
_delay_ms(1);
}
void leds_update(uint8_t index)
{
uint8_t mask = _BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4) | _BV(PB5)
| _BV(PB6) | _BV(PB7);
if (index < 8)
{
PORTB = (PORTB & ~mask) | _BV(index);
}
}
int main (void)
{
uint8_t selection;
uint8_t state_sw0, state_sw1;
uint8_t prev_state_sw0, prev_state_sw1;
/* Setup PB0-7 as outputs */
DDRB = _BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4) | _BV(PB5)
| _BV(PB6) | _BV(PB7);
/* Setup PC0 and PC1 as inputs with pull-up */
DDRC &= ~(_BV(DDC0) | _BV(DDC1));
PORTC |= _BV(DDC0) | _BV(DDC1);
/* The first selected led is led 0 */
selection = 0;
leds_update(selection);
/* Init the switches state */
prev_state_sw0 = 0;
prev_state_sw1 = 0;
/* Main loop */
for(;;)
{
/* Read the current switch state */
state_sw0 = (PINC & _BV(DDC0));
state_sw1 = (PINC & _BV(DDC1));
if (state_sw0 && !prev_state_sw0)
{
/* The switch 0 has been pressed */
if (selection < 7)
{
selection++;
leds_update(selection);
}
}
if (state_sw1 && !prev_state_sw1)
{
/* The switch 1 has been pressed */
if (selection > 0)
{
selection--;
leds_update(selection);
}
}
prev_state_sw0 = state_sw0;
prev_state_sw1 = state_sw1;
/* Wait for 20ms */
delay_ms(20);
}
return(0);
}
This sample is stolen from http://elasticsheep.com/2009/10/adding-switches/, with minor variations.