#include <Servo.h>
#include <LiquidCrystal_I2C.h>
const int servoPin = 9;
const int speakerPin = 8;
const int ledRedPin = 6;
const int ledGreenPin = 5;
const int sensorPin = 3;
Servo myservo; // Create servo object
// Define LCD connections (modify based on your I2C backpack)
const int lcd_address = 0x27; // Replace with your LCD I2C address
LiquidCrystal_I2C lcd(lcd_address, 16, 2);
int sensorValue = 0; // Variable to store sensor reading
char happyFace1[] = { 0x00, 0x0E, 0x11, 0x0E, 0x00, 0x00, 0x00, 0x00 }; // Happy face bitmap (eyes open)
char happyFace2[] = { 0x00, 0x0E, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00 }; // Happy face bitmap (eyes closed)
char sadFace[] = { 0x00, 0x04, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00 }; // Sad face bitmap
void setup() {
pinMode(ledRedPin, OUTPUT);
pinMode(ledGreenPin, OUTPUT);
pinMode(sensorPin, INPUT);
myservo.attach(servoPin); // Attach servo to pin
// Initialize LCD
lcd.init();
lcd.backlight(); // Turn on backlight
lcd.clear(); // Clear LCD display
}
void loop() {
sensorValue = analogRead(sensorPin); // Read sensor value
// Map sensor value to proximity range (adjust based on your sensor's range)
int distance = map(sensorValue, 0, 1023, 0, 100); // Example for 0-100cm range
// Control servo movement for tail wagging
wagTail(distance);
// Play sound effects and adjust LED brightness based on proximity
playSounds(distance);
adjustLEDs(distance);
// Display emotions on LCD based on proximity (animated)
displayEmotionsAnimation(distance);
delay(100); // Adjust delay for desired animation speed
}
void wagTail(int distance) {
int angle = map(distance, 0, 100, 0, 180); // Map proximity to servo position (adjust range)
myservo.write(angle);
delay(20); // Adjust delay for wagging speed
myservo.write(90); // Return to center position
delay(20);
}
void playSounds(int distance) {
if (distance < 30) { // Close (happy pet)
tone(speakerPin, 1000); // Play happy sound (modify frequency for desired sound)
} else if (distance > 70) { // Far (sad pet)
tone(speakerPin, 500); // Play sad sound (modify frequency for desired sound)
} else { // Medium distance (content)
noTone(speakerPin); // Stop sound
}
}
void adjustLEDs(int distance) {
int brightness = map(distance, 0, 100, 0, 255); // Map proximity to LED brightness
analogWrite(ledGreenPin, brightness); // Green LED for happy (adjust for PWM pin)
analogWrite(ledRedPin, 255 - brightness); // Red LED for sad (adjust for PWM pin)
}
void displayEmotionsAnimation(int distance) {
if (distance < 30) { // Happy pet (animate eyes)
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(happyFace1);
delay(200);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(happyFace2);
delay(200);
} else if (distance > 70) { // Sad pet (blink slowly)
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(sadFace);
delay(500);
lcd.clear();
delay(200);
} else { // Medium distance (content)
lcd.clear();
lcd.setCursor(0, 0);
// You can display a neutral character here (e.g., underline)
lcd.print("--");
}
}