Skip to content

Instantly share code, notes, and snippets.

@larsch
Created August 17, 2016 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsch/a973680064a01cd5d07749606f0ae1b7 to your computer and use it in GitHub Desktop.
Save larsch/a973680064a01cd5d07749606f0ae1b7 to your computer and use it in GitHub Desktop.
#include <avr/interrupt.h>
#include <avr/io.h>
volatile uint8_t rotaryPosition = 0;
void __attribute__((constructor)) init_rotary()
{
EICRA |= _BV(ISC00); // enable interrupt on change INT0 (for rotary encoder)
EIMSK |= (1 << INT0); // enable INT0 (for rotary encoder)
DDRD &= ~(_BV(PORTD3) | _BV(PORTD4) | _BV(PORTD5)); // input mode (rotary encoder clk, dt, sw)
PORTD |= _BV(PORTD3) | _BV(PORTD4) | _BV(PORTD5); // enable pull-up (rotary encoder clk, dt, sw)
}
ISR(INT0_vect)
{
static bool last_clk = 1;
const uint8_t pind = PIND;
bool clk = pind & _BV(PIND2);
if (clk != last_clk) {
bool dt = pind & _BV(PIND3);
rotaryPosition += (dt == clk) ? -1 : 1;
last_clk = clk;
}
}
bool readSwitch()
{
return PIND & _BV(PIND4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment