// Compiled and tested with no errors
// DIY Measuring wheel using Arduino and Rotary encoder with reset button
// source - www.circuitschools.com
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
#define outputA 2 //CLK pin
#define outputB 8 //DT pin
#define outputC 3 //CLK pin
#define outputD 9 //DT pin
#define rstbtnX 4 //reset button pin
#define rstbtnY 7 //reset button pin
int counterX = 0;
int counterY = 0;
const float pi = 3.14; // Pi value
const int XR = 5; //Radius of the wheel from center to edge
const int XN = 360; //no of steps for one rotation
const int YR = 5; //Radius of the wheel from center to edge
const int YN = 360; //no of steps for one rotation
float distanceY = 0;
float distanceX = 0;
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.print ("CIRCUITSCHOOLS..");
lcd. setCursor (0, 1);
lcd.print ("Measuring Wheel");
delay(2000);
lcd.clear();
// Initialize encoder pins
pinMode(outputA, INPUT);
pinMode(outputB, INPUT);
pinMode(outputC, INPUT);
pinMode(outputD, INPUT);
pinMode(rstbtnX, INPUT_PULLUP);
pinMode(rstbtnY, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(outputA), readEncoderX, FALLING);
attachInterrupt(digitalPinToInterrupt(outputC), readEncoderY, FALLING);
}
void readEncoderX() {
int bValue = digitalRead(outputB);
if (bValue == HIGH) {
counterX++; // Clockwise
}
if (bValue == LOW) {
counterX--; // Counterclockwise
}
}
void readEncoderY() {
int bValue = digitalRead(outputD);
if (bValue == HIGH) {
counterY++; // Clockwise
}
if (bValue == LOW) {
counterY--; // Counterclockwise
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounterX() {
int result;
noInterrupts();
result = counterX;
interrupts();
return result;
}
void resetCounterX() {
noInterrupts();
counterX = 0;
interrupts();
}
// Get the counter value, disabling interrupts.
// ThiEncs make sure readoder() doesn't change the value
// while we're reading it.
int getCounterY() {
int result;
noInterrupts();
result = counterY;
interrupts();
return result;
}
void resetCounterY() {
noInterrupts();
counterY = 0;
interrupts();
}
void loop() {
distanceX = ((2*pi*XR)/XN) * getCounterX();
distanceY = ((2*pi*YR)/YN) * getCounterY();
lcd.setCursor(0, 0);
lcd.print("DistanceX: in mms");
lcd.setCursor(0, 1);
lcd.print(distanceX);
lcd.print(" ");
lcd.setCursor(0, 2);
lcd.print("DistanceY: in mms");
lcd.setCursor(0, 3);
lcd.print(distanceY);
lcd.print(" ");
if (digitalRead(rstbtnX) == LOW) {
resetCounterX();
}
if (digitalRead(rstbtnY) == LOW) {
resetCounterY();
}
}