#include <DHT.h>
// Define pin numbers
#define MOTOR_PIN 3 // PWM pin connected to motor driver
#define LED_PIN 5 // Pin connected to LED
#define BUTTON_PIN 7 // Pin connected to the button
#define TRIG_PIN 8 // Trig pin of the ultrasonic sensor
#define ECHO_PIN 9 // Echo pin of the ultrasonic sensor
#define DHT_PIN 10 // Pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT sensor type (DHT11 or DHT22)
#define RUN_TIME 5000 // Run time in milliseconds (5 seconds)
#define DISTANCE_THRESHOLD 10 // Distance threshold in cm
#define TEMP_THRESHOLD 30 // Temperature threshold in Celsius
DHT dht(DHT_PIN, DHTTYPE);
void setup() {
// Set pin modes
pinMode(MOTOR_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize the motor and LED to be off
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(LED_PIN, LOW);
// Initialize the DHT sensor
dht.begin();
// Initialize serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read button state
int buttonState = digitalRead(BUTTON_PIN);
// Read temperature
float temperature = dht.readTemperature();
// Read distance
long duration = getUltrasonicDistance();
int distance = duration * 0.034 / 2;
// Check button state and sensor thresholds
if (buttonState == HIGH || (distance < DISTANCE_THRESHOLD && temperature < TEMP_THRESHOLD)) {
// Turn on the motor and LED
digitalWrite(MOTOR_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
// Wait for the specified run time
delay(RUN_TIME);
// Turn off the motor and LED
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(LED_PIN, LOW);
// Wait for the specified run time before restarting the loop
delay(RUN_TIME);
} else {
// Ensure the motor and LED are off
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(LED_PIN, LOW);
}
// Print sensor values for debugging
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" C, Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
long getUltrasonicDistance() {
// Send a 10us pulse to trigger the sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echo time in microseconds
long duration = pulseIn(ECHO_PIN, HIGH);
return duration;
}