#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP32Servo.h> // Use ESP32Servo instead of Servo.h
// Pin Definitions
#define TRIG_PIN 27
#define ECHO_PIN 14
#define BUZZER_PIN 13
#define SERVO_PIN 26
#define DS18B20_PIN 12
// Objects
Servo myServo; // ESP32 Servo object
OneWire oneWire(DS18B20_PIN);
DallasTemperature sensors(&oneWire);
// Function to measure distance using HC-SR04
float getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // 30ms timeout
if (duration == 0) {
Serial.println("No echo received or out of range");
return -1; // Return -1 for out-of-range or error
}
float distance = duration * 0.0343 / 2; // Convert to cm
return distance;
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
myServo.attach(SERVO_PIN); // Attach servo to ESP32
myServo.write(90); // Initial servo position
sensors.begin(); // Initialize temperature sensor
}
void loop() {
// Get distance from ultrasonic sensor
float distance = getDistance();
if (distance != -1) { // Only proceed if distance is valid
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Servo motor control based on distance
if (distance < 10) {
myServo.write(180);
digitalWrite(BUZZER_PIN, HIGH); // Activate buzzer
} else {
myServo.write(90);
digitalWrite(BUZZER_PIN, LOW); // Deactivate buzzer
}
}
// Read temperature from DS18B20
sensors.requestTemperatures();
float temperatureC = sensors.getTempCByIndex(0);
if (temperatureC != DEVICE_DISCONNECTED_C) {
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
} else {
Serial.println("Temperature sensor not detected");
}
delay(1000); // Wait before next loop
}
Loading
ds18b20
ds18b20