Hey everyone,
I am willing to measure angle of a boom, when it is lifted from it's pivot point. For this purpose, I thought of using optical rotary encoder, as CW and CCW counter, thus giving me required pulses. But i can not make the programme work as it keeps on counting on its own.
here is my code.
int led = 13; // just to check my condition
int cw=2; // Encoder pin A at 2
int ccw=4; // Encoder pin B at 4
int valP=0; // to read A which is positive direction or cw
int counter=0;
int valN=0; // to read B which is in negative direction or ccw
void setup(){
pinMode(led, OUTPUT); // declaring to see change
pinMode(cw, INPUT_PULLUP);
pinMode(ccw,INPUT_PULLUP);
Serial.begin(9600);
}
void loop(){
valP = digitalRead(cw); // read input value as direction
valN = digitalRead(ccw);
if (valP=HIGH && valP!=valN)
{
counter=counter+1;
Serial.println(counter);
}
if (valN=HIGH && valN==valP)
{
counter=counter-1;
Serial.println(counter);
}
if(counter>=50){
digitalWrite(led, HIGH);
}else{
digitalWrite(led, LOW);
}
}
well, @ jremington......I have the ground common, but it didn't make any difference. And yes, I have an LED attached with the pins 2 and 3. They keep on blinking but pretty much dim, even if am not rotating the shaft.
This encoder is totempole type encoder, which is actually putting a glitch in my mind.
The error that you are making is that you need to detect when PinA or PinB changes state.
Example 1 is using your approach of testing whether or not the two pins are the same or different after pinA changes from low to high.
int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;
void setup() {
pinMode (encoder0PinA,INPUT);
pinMode (encoder0PinB,INPUT);
Serial.begin (9600);
}
void loop() {
n = digitalRead(encoder0PinA);
if ((encoder0PinALast == LOW) && (n == HIGH)) {
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos--;
} else {
encoder0Pos++;
}
Serial.print (encoder0Pos);
Serial.print ("/");
}
encoder0PinALast = n;
}
This algorithm counts only 1/4 of the available quadrature counts, which may be sufficient for your encoder and the resolution you require. Once you understand this basic code, you can uses other algorithms which test for rising and falling changes on one or both pins, and read, 1,2, or all 4 of the available quadrature counts.
To control the serial printing, you need to print only after the count changes, or perhaps with your application only the max counts on either side. Please be aware that the serial printing is slow, and may not keep up with your counts, or may cause you to miss some counts.
For now, move the encoder slowly, and work to understand the fundamentals of the quadrature states and the counts.