#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize I2C LCD (Try 0x3F if 0x27 doesn't work)
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo barrierServo;
// Pin Definitions matching your wiring
const int irSensorPin = 2; // IR Obstacle Sensor OUT
const int switchPin = 3; // Manual Override Push Switch
const int greenLedPin = 4; // Green Status LED
const int redLedPin = 5; // Red Status LED
const int servoPin = 6; // Servo Motor PWM Signal
const int buzzerPin = 8; // Active Buzzer
void setup() {
// Initialize Serial Monitor for debugging
Serial.begin(9600);
// Configure Pin Modes
pinMode(irSensorPin, INPUT);
pinMode(switchPin, INPUT_PULLUP); // Internal pull-up resistor enabled
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Attach Servo and set initial closed position (0 degrees)
barrierServo.attach(servoPin);
barrierServo.write(0);
// Default state: Red LED ON (Gate Closed)
digitalWrite(redLedPin, HIGH);
digitalWrite(greenLedPin, LOW);
// Initialize LCD Display
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Smart Toll System");
lcd.setCursor(0, 1);
lcd.print("Testing All Parts");
// Startup beep
tone(buzzerPin, 1000, 300);
delay(2000);
lcd.clear();
}
void loop() {
// Read sensor and switch states
int irState = digitalRead(irSensorPin); // Usually LOW when an object is detected
int switchState = digitalRead(switchPin); // LOW when button is pressed
// Print live diagnostics to Serial Monitor (Tools -> Serial Monitor)
Serial.print("IR Sensor: ");
Serial.print(irState);
Serial.print(" | Switch: ");
Serial.println(switchState);
// Trigger condition: IR detects car (LOW) OR Manual switch is pressed (LOW)
if (irState == LOW || switchState == LOW) {
// 1. Audio and Visual Alert
tone(buzzerPin, 1200, 200);
digitalWrite(redLedPin, LOW);
digitalWrite(greenLedPin, HIGH);
// 2. LCD Feedback
lcd.setCursor(0, 0);
lcd.print("Car Detected! ");
lcd.setCursor(0, 1);
lcd.print("Opening Gate... ");
// 3. Open Servo Gate (90 degrees)
barrierServo.write(90);
delay(4000); // Keep gate open for 4 seconds
// 4. Closing Warning Sequence
tone(buzzerPin, 800, 300);
lcd.setCursor(0, 0);
lcd.print("Gate Closing... ");
lcd.setCursor(0, 1);
lcd.print("Please Wait ");
// Close Servo Gate (0 degrees)
barrierServo.write(0);
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, HIGH);
delay(1000);
lcd.clear();
}
else {
// Idle / Ready State
digitalWrite(redLedPin, HIGH);
digitalWrite(greenLedPin, LOW);
lcd.setCursor(0, 0);
lcd.print("Slot Available ");
lcd.setCursor(0, 1);
lcd.print("Wai
ting for Car ");
}
delay(100); // Small debounce delay
}
No comments:
Post a Comment