#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
int x = 0; // This will hold the count of state changes
int inputPin = A0; // Pin to read input from the sensor
int state = 0; // Current state of input pin
const int buzzerPin = 12; // Pin connected to the buzzer
const int ledPin = 4; // Pin connected to the LED
unsigned long previousMillis = 0; // Last time the alert was triggered
const long interval = 60000; // Interval at which to beep and blink (1 minute)
const long ledOnDuration = 1000; // Duration the LED should stay on (1 second for demonstration)
unsigned long ledTurnedOnAt = 0; // When the LED was last turned on
bool ledIsOn = false; // State of the LED
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0);
lcd.print(" Tachometer (WC) ");
lcd.setCursor(0, 1);
lcd.print(x);
lcd.print(" =RPM ");
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(inputPin, INPUT);
}
void loop() {
unsigned long currentMillis = millis();
int sensorValue = digitalRead(inputPin);
// Check for state changes and update counter
if (state == 0 && sensorValue == HIGH) {
state = 1;
x += 1;
lcd.setCursor(0, 1);
lcd.print(x);
lcd.print(" =RPM "); // Clear any leftover characters
} else if (sensorValue == LOW) {
state = 0;
}
// Manage timing for buzzer and LED
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
digitalWrite(buzzerPin, HIGH); // Turn on buzzer
digitalWrite(ledPin, HIGH); // Turn on LED
ledIsOn = true;
ledTurnedOnAt = currentMillis;
}
if (ledIsOn && (currentMillis - ledTurnedOnAt >= ledOnDuration)) {
digitalWrite(ledPin, LOW); // Turn off LED
digitalWrite(buzzerPin, LOW); // Turn off buzzer after a short beep
ledIsOn = false;
}
}