Skip to content

Instantly share code, notes, and snippets.

@larsch
Created October 12, 2017 19:45
Show Gist options
  • Save larsch/1a2c58c541cb4f96659d4fae33d865a8 to your computer and use it in GitHub Desktop.
Save larsch/1a2c58c541cb4f96659d4fae33d865a8 to your computer and use it in GitHub Desktop.
Rotary Encoder Interrupt Handler
//
// Rotary Encoder Driver
//
// Copyright (C) 2016 by Lars Christensen <[email protected]>
// MIT License
//
#include "rotary.hpp"
#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