Hello everybody,
I have been working on this project for a while now, I am getting quite close but I am having an issue with my encoder, it seems if I rotate my encode at anything other than quite slow it misses pulses. I thought initially this was bouncing however with my count remaining consistently low it would appear it is simply missing pulses. If I rotate the encoder slowly, say around 15 RPM there are no issues and I get a consistent number however much about that and my numbers begin to drop. I am hoping you guys can give me some insight as to what might be going on here... This is the encoder in question...
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3f, 20, 4); // set the LCD
//address to 0x3f for a 16 chars and 2 line display
const int clkPin = 3; //the clk attach to pin2
const int dtPin = 2; //the dt attach to pin3
const int swPin = 4 ; //the number of the button
int encoderVal = 0;//raw counts from encoder
const float distancePerCount = 1 ; //adjust as required
float totalDistance = 0.0;
//added variable for interrupt handler
volatile int count = 0;
void setup()
{
lcd.init(); // initialize the lcd
// Print a message to the LCD.
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Belt Length :");
//set clkPin,dePin,swPin as INPUT
pinMode(clkPin, INPUT_PULLUP);
pinMode(dtPin, INPUT_PULLUP);
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);
Serial.begin(9600); // initialize serial communications at 9600 bps
attachInterrupt(digitalPinToInterrupt(clkPin), isrA, CHANGE);
attachInterrupt(digitalPinToInterrupt(dtPin), isrB, CHANGE);
}
void loop()
{
int change = getEncoderTurn();
if (change != 0)
{
encoderVal = encoderVal + change;
totalDistance = encoderVal * distancePerCount;
Serial.println(encoderVal); //print the encoderVal on the serial monitor
Serial.println(totalDistance, 2); //print float with 2 dp
lcd.setCursor(5, 1);
//lcd.print(encoderVal);
lcd.print(totalDistance, 2);
}
if (digitalRead(swPin) == LOW) //if button pull down
{
//encoderVal = .157;
encoderVal = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Belt Length :");
}
}
int getEncoderTurn(void)
{
noInterrupts();
int result = count;
count = 0;//reset count
interrupts();
return result;
}
void isrA() {
if (digitalRead(dtPin) != digitalRead(clkPin)) {
count ++;
} else {
count --;
}
}
void isrB() {
if (digitalRead(clkPin) == digitalRead(dtPin)) {
count ++;
} else {
count --;
}
}