#include <Servo.h>
#include <SoftwareSerial.h>
// Set up Bluetooth serial communication
SoftwareSerial bluetooth(2, 3); // RX, TX
// Set up solenoid lock
int lockPin = 9; // Use PWM pin 9 to control solenoid
boolean lockState = false;
// Set up servo motor and ultrasonic sensor
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
const int trigPin = 12; // define the pins for ultrasonic sensor
const int echoPin = 11;
void setup() {
// Set up serial communication for debugging
Serial.begin(9600);
while (!Serial) {
; // Wait for serial port to connect
}
// Set up solenoid lock
pinMode(lockPin, OUTPUT);
digitalWrite(lockPin, LOW);
// Set up servo motor and ultrasonic sensor
myservo.attach(6); // attaches the servo on pin 6 to the servo object
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set up Bluetooth serial communication
bluetooth.begin(9600);
Serial.println("Bluetooth module is ready");
}
void loop() {
// Check for incoming Bluetooth data
if (bluetooth.available()) {
char command = bluetooth.read();
Serial.print("Received command: ");
Serial.println(command);
// If command is 'L', lock the Bin
if (command == 'L') {
digitalWrite(lockPin, HIGH); // Apply power to solenoid
lockState = true; // Update lock state
Serial.println("Bin locked");
}
// If command is 'U', unlock the Bin
if (command == 'U') {
digitalWrite(lockPin, LOW); // Remove power from solenoid
lockState = false; // Update lock state
Serial.println("Bin unlocked");
}
}
// Check for changes in lock state
if (lockState) {
bluetooth.print("Locked");
} else {
bluetooth.print("Unlocked");
}
// Send a 10 microsecond pulse to the ultrasonic sensor to trigger a measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the duration of the pulse from the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters based on the speed of sound
int cm = (duration/2) / 29.1;
Serial.print(cm);
Serial.println(" cm");
// If the distance is less than a certain threshold, rotate the servo to open the lid of the garbage bin
if (cm < 20) {
for (pos = 0; pos <= 90; pos += 1) { // goes from 0 degrees to 90 degrees in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); }
}
}