forked from astine/rotaryencoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotaryencoder.c
51 lines (40 loc) · 1.32 KB
/
rotaryencoder.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "rotaryencoder.h"
int numberofencoders = 0;
void updateEncoders()
{
struct encoder *encoder = encoders;
for (; encoder < encoders + numberofencoders; encoder++)
{
int MSB = digitalRead(encoder->pin_a);
int LSB = digitalRead(encoder->pin_b);
int encoded = (MSB << 1) | LSB;
int sum = (encoder->lastEncoded << 2) | encoded;
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoder->value++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoder->value--;
encoder->lastEncoded = encoded;
}
}
struct encoder *setupencoder(int pin_a, int pin_b)
{
if (numberofencoders > max_encoders)
{
printf("Maximum number of encodered exceded: %i\n", max_encoders);
return NULL;
}
struct encoder *newencoder = encoders + numberofencoders++;
newencoder->pin_a = pin_a;
newencoder->pin_b = pin_b;
newencoder->value = 0;
newencoder->lastEncoded = 0;
pinMode(pin_a, INPUT);
pinMode(pin_b, INPUT);
pullUpDnControl(pin_a, PUD_UP);
pullUpDnControl(pin_b, PUD_UP);
wiringPiISR(pin_a,INT_EDGE_BOTH, updateEncoders);
wiringPiISR(pin_b,INT_EDGE_BOTH, updateEncoders);
return newencoder;
}