#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Pin definitions
const int inductiveSensorPin = 8;
const int ldrPin = A0;
const int redLedPin = 3;
const int whiteLedPin = 5;
const int speakerPin = 6;
const int servo1Pin = 9;
const int servo2Pin = 11;
// LDR threshold value (adjust as needed)
const int ldrThreshold = 500;
// Servo objects
Servo servo1;
Servo servo2;
// I2C LCD address (typically 0x27 or 0x3F)
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Initialize pin modes
pinMode(inductiveSensorPin, INPUT);
pinMode(redLedPin, OUTPUT);
pinMode(whiteLedPin, OUTPUT);
pinMode(speakerPin, OUTPUT);
// Attach servos to pins
servo1.attach(servo1Pin);
servo2.attach(servo2Pin);
// Initialize servos to 90 degrees (straight position)
servo1.write(90);
servo2.write(90);
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.print("CLOSE");
Serial.begin(9600);
}
void loop() {
// Read the state of the inductive sensor
int inductiveSensorState = digitalRead(inductiveSensorPin);
// Check if the metal piece is detected
if (inductiveSensorState == HIGH) {
delay(10);
// Metal detected
digitalWrite(redLedPin, HIGH); // Turn on red LED
// Play a sound
noTone(speakerPin);
lcd.clear();
lcd.print("OPEN"); // Display "CLOSE"
servo1.write(180); // Rotate servos to 180 degrees
servo2.write(180);
} else {
// Metal not detected
digitalWrite(redLedPin, LOW);
delay(10);
// Turn off red LED
tone(speakerPin, 1000, 200);
// Stop sound
lcd.clear();
lcd.print("CLOSE"); // Display "OPEN"
servo1.write(90); // Rotate servos to 90 degrees
servo2.write(90);
}
// Read the LDR value
int ldrValue = analogRead(ldrPin);
Serial.print("LDR Value: ");
Serial.println(ldrValue);
// Adjust white LED brightness based on LDR value
int whiteLedBrightness = map(ldrValue, 0, 1023, 255, 0);
analogWrite(whiteLedPin, whiteLedBrightness);
Serial.print("White LED Brightness: ");
Serial.println(whiteLedBrightness);
// Delay for stability
delay(10);
}