Hi,
I've been running through a few tutorials to get my head around Rotary encoders whilst getting back into coding in AVR Studio instead of Arduino. Unfortunately I'm away and cant test the code, would you look at it and see if i've made any errors and or can improve on it? I've tried to comment it to keep it easy to understand.
All it does is setup PCINT6 to look for a logical change and call the ISR to track what change it was and either increase or decrease a variable.
Many thanks,
Dave
/* * RotaryEncoder.c * * Created: 3/21/2011 10:15:54 AM * Author: daharrod */ #include#include #define STATE_PIN 5 #define PHASE_PIN 6 #define RENCBTN_PIN 7 #define RENC_DDR DDRB #define RENC_PORT PORTB #define SETBIT(ADDRESS,BIT) (ADDRESS |= (1<<BIT)) #define CLEARBIT(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT)) #define FLIPBIT(ADDRESS,BIT) (ADDRESS ^= (1<<BIT)) #define CHECKBIT(ADDRESS,BIT) (ADDRESS & (1<<BIT)) volatile int RENC_POS; volatile int RENC_PHASE_STATUS; void SetupRENC() { //Setup I/O for STATE_PIN and PHASE_PIN RENC_DDR |= (1<<PB6) | (1<<PB5); //Set PB5/6 to Input //Enable Pin Change Interrupt on PB6 PCIFR |= (1<<PCIF0); PCMSK0 |= (1<<PCINT6); //Check status of STATE_PIN, determine Rising or Falling Interrupts. //Clear Interrupt Flag before changing EIMSK |= (1<<INT6); //Setup Interrupt type (Change) EICRB |= (1<<ISC60); //Set start conditions RENC_PHASE_STATUS = (PINB & (1<<PB6)); //Enable Global interrupts sei(); //Setup Global int for RENC_POS RENC_POS = 0; } //PinChange Interrupt Handler void ISR(PCINT0_vect) { int TEMP_STATE_STATUS; int TEMP_PHASE_STATUS; //Get New STATE_PIN Level TEMP_STATE_STATUS = (PINB & (1<<PB5)); TEMP_PHASE_STATUS = (PINB & (1<<PB6)); if ((RENC_PHASE_STATUS == 0) && (TEMP_PHASE_STATUS == 1)) { if(TEMP_PHASE_STATUS) { RENC_POS--; } else { RENC_POS++; } } if ((RENC_PHASE_STATUS ==1) && (TEMP_PHASE_STATUS == 0)) { if(TEMP_PHASE_STATUS) { RENC_POS++; } else { RENC_POS--; } } RENC_PHASE_STATUS = TEMP_PHASE_STATUS; //New ints to old ints. }; int main(void) { //Setup Functions SetupRENC(); while(1) { } }