#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define pinoCLK 7
#define pinoDT 6
LiquidCrystal_I2C lcd(0x27, 16, 2);
float contador = 0.0;
int estadoAtualCLK;
int estadoAnteriorCLK;
unsigned long lastRotationTime = 0; // Variable to store the time of the last rotation
String encdir = "";
const float encoderResolution = 360.0; // Change this value based on your encoder's resolution
const float wheelCircumference = 2.0; // Change this value based on the size of the wheel
void setup()
{
pinMode(pinoCLK, INPUT);
pinMode(pinoDT, INPUT);
estadoAnteriorCLK = digitalRead(pinoCLK);
lcd.init();
lcd.setBacklight(HIGH);
}
void loop()
{
estadoAtualCLK = digitalRead(pinoCLK);
if (estadoAtualCLK != estadoAnteriorCLK)
{
if (digitalRead(pinoDT) != estadoAtualCLK)
{
contador-=0.5;
encdir = "HOR";
}
else
{
contador+=0.5;
encdir = "ANTH";
}
unsigned long currentTime = millis(); // Get the current time in milliseconds
// Calculate the time elapsed since the last full rotation
unsigned long rotationTime = currentTime - lastRotationTime;
// Calculate speed in RPM
float rpm = 60000.0 / rotationTime;
// Calculate speed in km/h
float kmh = (rpm * wheelCircumference * 60) / (encoderResolution * 1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Valor: ");
lcd.print(contador, 1); // Display value with one decimal place
lcd.setCursor(0, 1);
lcd.print("Speed : ");
lcd.print(kmh, 2); // Display speed in km/h with two decimal places
lastRotationTime = currentTime; // Update the last rotation time
}
estadoAnteriorCLK = estadoAtualCLK;
}