Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active October 3, 2019 06:15
Show Gist options
  • Save gustavorv86/1fd9090dcbb618c9ffd4424ee19aadc5 to your computer and use it in GitHub Desktop.
Save gustavorv86/1fd9090dcbb618c9ffd4424ee19aadc5 to your computer and use it in GitHub Desktop.
Raspberry PI Rotary Encoder Function Example
/*
Wiring
01 3.3V DC POWER --------------- +
06 GROUND ---------------------- GND
11 GPIO17 (GPIO_GEN0) ---------- CLK
12 GPIO18 (GPIO_GEN1) ---------- DT
13 GPIO19 (GPIO_GEN2) ---------- SW
Compile:
gcc -Wall -lwiringPi rotary_encoder_example.c -o rotary_encoder_example.bin
Run:
./rotary_encoder_example.bin
*/
#include <stdio.h>
#include <wiringPi.h>
// pin wiring
#define PIN_CLK 0
#define PIN_DT 1
#define PIN_SW 2
// rotaryRead statuses
#define ROTATION_NONE 0
#define ROTATION_LEFT 1
#define ROTATION_RIGHT 2
#define ROTATION_BUTTON 3
void rotarySetup(int pin_clk, int pin_dt, int pin_sw) {
// pin configuration
pinMode(pin_clk, INPUT);
pinMode(pin_dt, INPUT);
pinMode(pin_sw, INPUT);
pullUpDnControl(pin_sw, PUD_UP);
}
int rotaryRead(int pin_clk, int pin_dt, int pin_sw) {
// read DT status
int last_dt_status = digitalRead(pin_dt);
int current_dt_status = 0;
int flag_change = 0;
while(digitalRead(pin_clk) == 0){
// read DT while CLK equals 0
current_dt_status = digitalRead(pin_dt);
flag_change = 1;
}
if(flag_change == 1){
if(last_dt_status==0 && current_dt_status==1){
return ROTATION_LEFT;
}
if(last_dt_status==1 && current_dt_status==0){
return ROTATION_RIGHT;
}
}
if(digitalRead(pin_sw) == 0){
delay(200);
return ROTATION_BUTTON;
}
return ROTATION_NONE;
}
int main(void) {
if(wiringPiSetup() < 0){
printf("ERROR: wiringPiSetup \n");
return 1;
}
rotarySetup(PIN_CLK, PIN_DT, PIN_SW);
while(1){
int stat = rotaryRead(PIN_CLK, PIN_DT, PIN_SW);
if(stat != ROTATION_NONE) {
if(stat == ROTATION_LEFT) {
printf("left \n");
}
if(stat == ROTATION_RIGHT) {
printf("right \n");
}
if(stat == ROTATION_BUTTON) {
printf("button \n");
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment