Created
August 4, 2021 19:31
-
-
Save gary9716/6dbb6f96eff2fcfbc0f51b116683c284 to your computer and use it in GitHub Desktop.
Convert gray code signal to corresponding angle for absolute rotary encoder(E6CP-AG5C with resolution 360 degrees) in Arduino
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
#define PIN_0 (2) //2^0 | |
#define PIN_1 (3) //2^1 | |
#define PIN_2 (4) //2^2 | |
#define PIN_3 (5) //2^3 | |
#define PIN_4 (6) //2^4 | |
#define PIN_5 (7) //2^5 | |
#define PIN_6 (8) //2^6 | |
#define PIN_7 (9) //2^7 | |
#define PIN_8 (10) //2^8 | |
#define TO_INVERT_SIG (1) //In my case, I need to invert the signal to get the correct result. | |
const int offset = 76; //angle offset | |
const int numPins = 9; | |
int8_t pinArray[numPins] = { | |
PIN_0, | |
PIN_1, | |
PIN_2, | |
PIN_3, | |
PIN_4, | |
PIN_5, | |
PIN_6, | |
PIN_7, | |
PIN_8 | |
}; | |
void setup() { | |
// put your setup code here, to run once: | |
Serial.begin(9600); | |
for(int i = 0;i < numPins;i++) { | |
pinMode(pinArray[i], INPUT_PULLUP); | |
} | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
Serial.println(ConvertGrayCode(), DEC); | |
delay(50); | |
} | |
int ConvertGrayCode() { | |
int finalResult = 0; | |
int val = 0; | |
int curXORVal = 0; | |
int i = numPins - 1; //start from MSB | |
//assign first value | |
#if TO_INVERT_SIG == 1 | |
val = 1 - digitalRead(pinArray[i]); | |
#else | |
val = digitalRead(pinArray[i]); | |
#endif | |
finalResult = ((val & 1) << i); | |
for(i = numPins - 2;i >= 0;i--) { | |
#if TO_INVERT_SIG == 1 | |
val = 1 - digitalRead(pinArray[i]); | |
#else | |
val = digitalRead(pinArray[i]); | |
#endif | |
curXORVal = ((finalResult >> (i + 1)) & 1) ^ (val & 1); | |
finalResult |= ((curXORVal & 1) << i); | |
} | |
return finalResult - offset; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment