Created
October 12, 2017 19:45
-
-
Save larsch/1a2c58c541cb4f96659d4fae33d865a8 to your computer and use it in GitHub Desktop.
Rotary Encoder Interrupt Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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