// 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, 16, 2);
#define outputA 2 //CLK pin
#define outputB 3 //DT pin
#define rstbtn 4 //reset button pin
int counter = 0;
const float pi = 3.14; // Pi value
const int R = 7; //Radius of the wheel from center to edge
const int N = 40; //no of steps for one rotation
float distance = 0;
void setup() {
// Initialize LCD
lcd.begin(16,2);
lcd.print (" Hosszmero ");
lcd.setCursor (0, 1);
lcd.print ("Measuring Wheel");
delay(2000);
lcd.clear();
// Initialize encoder pins
pinMode(outputA, INPUT);
pinMode(outputB, INPUT);
pinMode(rstbtn, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(outputA), readEncoder, FALLING);
}
void readEncoder() {
int bValue = digitalRead(outputB);
if (bValue == HIGH) {
counter++; // Clockwise
}
if (bValue == LOW) {
counter--; // Counterclockwise
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
void resetCounter() {
noInterrupts();
counter = 0;
interrupts();
}
void loop() {
distance = ((2*pi*R)/N) * getCounter();
lcd.setCursor(0, 0);
lcd.print("Distance: in cms");
lcd.setCursor(8, 1);
lcd.print(distance);
lcd.print(" ");
if (digitalRead(rstbtn) == LOW) {
resetCounter();
}
}