#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD settings
LiquidCrystal_I2C lcd(0x27, 20, 4); // Adjust I2C address if necessary
// TCRT5000 and reset button pins
const int tcrt5000Pin = 2; // Digital pin for TCRT5000
const int resetButtonPin = 3; // Digital pin for reset button
int counter = 0; // Count detected events
bool previousState = HIGH; // Previous state of the TCRT5000 sensor
const int counterLimit = 20; // Maximum count limit
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
// Display initial message
lcd.setCursor(0, 0);
lcd.print("TCRT5000 Counter:");
lcd.setCursor(0, 1);
lcd.print("Count: ");
lcd.setCursor(7, 1);
lcd.print(counter);
// Initialize the pins
pinMode(tcrt5000Pin, INPUT_PULLUP);
pinMode(resetButtonPin, INPUT_PULLUP); // Use internal pull-up resistor
// Start serial monitor for debugging
Serial.begin(9600);
}
void loop() {
// Read the current state of the sensor
bool currentState = digitalRead(tcrt5000Pin);
// Detect a transition from HIGH to LOW (light to dark) if below the limit
if (previousState == HIGH && currentState == LOW && counter < counterLimit) {
counter++; // Increment the counter
// Update the LCD with the new count
lcd.setCursor(7, 1);
lcd.print(" "); // Clear old value
lcd.setCursor(7, 1);
lcd.print(counter);
Serial.print("Line detected - Counter incremented to: ");
Serial.println(counter);
}
// Check if the reset button is pressed
if (digitalRead(resetButtonPin) == LOW) {
counter = 0; // Reset the counter
// Update the LCD
lcd.setCursor(7, 1);
lcd.print(" "); // Clear old value
lcd.setCursor(7, 1);
lcd.print(counter);
Serial.println("Counter reset to zero");
delay(200); // Debounce delay
}
// Update the previous state
previousState = currentState;
// Add a small delay to debounce the sensor
delay(50);
}