EmbeddedSystems/EmbeddedSystemsTHM/rotaryEncoder.c

140 lines
2.0 KiB
C
Raw Normal View History

2021-12-17 22:26:41 +01:00
/*
* rotaryEncoder.c
*
* Created: 16/12/2021 16:34:05
* Author: n0x
*/
#include "rotaryEncoder.h"
#define ROTA PORTC7 /* define Rotary Encoder Button A */
#define ROTB PORTC6 /* define Rotary Encoder Button B */
2021-12-17 22:26:41 +01:00
#define ROTBUTTON PORTC5
/* enums */
enum{
LEFT1, LEFT2, LEFT3, RIGHT1, RIGHT2, RIGHT3,
2021-12-17 22:26:41 +01:00
INIT, WAIT
} RotaryState = INIT; /* Enum for the rotary enc */
2021-12-17 22:26:41 +01:00
int16_t count;
void
drehgeber_init(void)
{
DDRC &= ~(7<<DDC5); /* Set bit 5-7 of Data Direction Register C as input */
PORTC |= (7<<PORTC5); /* Initialize bit 5-7 of PORTC as for pull up resistor */
2021-12-17 22:26:41 +01:00
/* With external interrupt */
PCICR |= (1<<PCIE2);
PCMSK2 |= (1<<PCINT23)|(1<<PCINT22);
}
ISR(PCINT2_vect)
{
drehgeber_process();
}
void
drehgeber_process(void)
{
/* calculate the value of Button A and B of rotary encoder */
uint8_t a, b, enc;
2021-12-17 22:26:41 +01:00
a = ((PINC & (1<<ROTA)) == 0);
b = ((PINC & (1<<ROTB)) == 0)<<1;
enc = a+b;
2021-12-17 22:26:41 +01:00
switch(RotaryState)
{
case INIT:
RotaryState = WAIT;
break;
2021-12-17 22:26:41 +01:00
case WAIT:
if(enc == 1)
{
RotaryState = LEFT1;
}
if(enc == 2)
{
RotaryState = RIGHT1;
}
break;
2021-12-17 22:26:41 +01:00
case LEFT1:
if(enc == 3)
{
RotaryState = LEFT2;
}
if(enc == 0)
{
RotaryState = WAIT;
}
break;
2021-12-17 22:26:41 +01:00
case LEFT2:
if(enc == 2)
{
RotaryState = LEFT3;
}
if(enc == 1)
{
RotaryState = LEFT1;
}
break;
2021-12-17 22:26:41 +01:00
case LEFT3:
if(enc == 0)
{
/* Increment counter and wait */
count++;
RotaryState = WAIT;
}
if(enc == 3)
{
RotaryState = LEFT2;
}
break;
2021-12-17 22:26:41 +01:00
case RIGHT1:
if(enc == 3)
{
RotaryState = RIGHT2;
}
if(enc == 0)
{
RotaryState = WAIT;
}
break;
2021-12-17 22:26:41 +01:00
case RIGHT2:
if(enc == 1)
{
RotaryState = RIGHT3;
}
if(enc == 2)
{
RotaryState = RIGHT1;
}
break;
2021-12-17 22:26:41 +01:00
case RIGHT3:
if(enc == 0)
{
/* Decrement counter and wait */
count--;
RotaryState = WAIT;
}
if(enc == 3)
{
RotaryState = RIGHT2;
}
break;
2021-12-17 22:26:41 +01:00
}
}
int16_t drehgeber_get(void)
{
return count;
}