Hello!
I use encoder without Z output as wind direction sensor.
I have 400 counts per revolution from encoder.
When i start code - i use simple reset after push button to zero setting.
But i have trouble - if encoder rotates clockwise - everything ok - output going up, if encoder rotates counter clockwise - output going down and crossing zero...
So how i can convert encoder values from -2,147,483,648 to 2,147,483,647 (long type) to 0 359 out.
The encoder has 400 steps but can count 2 or 4 times that or at 4 transitions per step = 1600 counts per revolution so for incredible detail try this code:
#define DataPin 3
#define ClockPin 2
volatile int Ctr;
volatile byte Flag;
void E1() {
if (digitalRead(DataPin))( digitalRead(ClockPin)) ? Ctr ++ : Ctr --;
else ( digitalRead(ClockPin)) ? Ctr -- : Ctr ++;
Ctr = Ctr % 1600; // only use a number from 0 to 1599 the % returns the remainder after dividing by 1600
Flag = true;
}
void E2() {
if (digitalRead(ClockPin))( digitalRead(DataPin)) ? Ctr -- : Ctr ++;
else ( digitalRead(DataPin)) ? Ctr ++ : Ctr --;
Ctr = Ctr % 1600; // only use a number from 0 to 1599 the % returns the remainder after dividing by 1600
Flag = true;
}
void EncodetInterruptSetup() {
attachInterrupt(digitalPinToInterrupt(DataPin), E1 , CHANGE);
attachInterrupt(digitalPinToInterrupt(ClockPin), E2, CHANGE);
}
void setup() {
Serial.begin(115200);
EncodetInterruptSetup();
}
void loop() {
int C;
float Deg;
if (Flag) {
cli (); // clear interrupts flag
C = Ctr;
sei ();
Deg = ((float)C) * 0.225;
Flag = false;
Serial.println(Deg, 4);
}
}
This should limit the count to 1 revolution worth or 1600 counts * 0.225 degrees per count = 360°
Then convert it to degrees as a floating point number
Z
I am assuming this is the encoder you are using: