// 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 LED 13
#define outputA 2 //CLK pin
#define outputB 3 //DT pin
#define rstbtn 4 //reset button pin
int counter = 0;
int x = 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
pinMode(LED, OUTPUT); // Declare the LED as an output
digitalWrite(LED, HIGH); // Turn the LED on
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(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()
{
if (x == 0)
{
distance = ((2*pi*R)/N) * getCounter();
lcd.setCursor(0, 0);
lcd.print("Distance: in cms");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" ");
if(distance >= 5.49)
{
lcd.clear();
digitalWrite(LED, LOW); // Turn the LED on
lcd.setCursor(0, 0);
lcd.print("point");
lcd.setCursor(0, 1);
lcd.print("reached");
resetCounter();
x = 1;
}
}
if (digitalRead(rstbtn) == LOW)
{
resetCounter();
x = 0;
}
}