I am working on a project using a Rotary Encoder and I am trying to receive the output from the encoder. As it stands I am able to get a count for degrees of change and direction of rotation, however depending on the speed the encoder spins I get a varying rotational output. For example if I rotate it slowly I can get 100's of counts for 180 degrees of rotation, but if I do so fast, then I could get 10 or so counts.
I believe my Arduino is running too slow to count each of the signals from the encoder, I measured the wavelength of a signal to be ~25 us when spun quickly but using the following code I found that my arduino is running at a loop rate of 200 loops per second.
void loop() {
if(counter <= 1000){
counter++;
Serial.println(counter);
}
}
The code for the Rotary Encoder: Dt and CLK pin representing the 2 signal wires, both being pulled up
void loop(){
//take clk pin state
clkState = digitalRead(clkPin);
//if clk state changed then wheel is rotating, react to rising edge to avoid double count
if(clkState != preClkState && clkState == HIGH){
Serial.write(digitalRead(dtPin));
//check direction of spin based on dtpin
if(digitalRead(dtPin)== HIGH){
counter++;
clockwiseDirection = true;
}else{
counter--;
clockwiseDirection = false;
}
//output values
Serial.write("Direction: ");
if(clockwiseDirection){
Serial.write("Clockwise | Counter: ");
}else{
Serial.write("Counter Clockwise | Counter: ");
}
Serial.print((int)counter);
Serial.print("\n");
}
//update pre pos
preClkState = clkState;
}