#include <WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Define the pins for the sensors
#define TRIG_PIN 12 // Pin connected to the TRIG pin of the HC-SR04
#define ECHO_PIN 13 // Pin connected to the ECHO pin of the HC-SR04
#define ONE_WIRE_BUS 14 // Pin connected to the data pin of the DS18B20
// Setup the OneWire bus
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
long duration;
int distance;
void setup() {
// Start the serial communication
Serial.begin(115200);
// Initialize the ultrasonic sensor
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize the DS18B20 sensor
sensors.begin();
Serial.println("Ultrasonic and DS18B20 Sensor Test");
}
void loop() {
// Measure distance with the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2; // Calculate distance in cm
// Request temperature from the DS18B20 sensor
sensors.requestTemperatures(); // Request temperature reading
float temperature = sensors.getTempCByIndex(0); // Get the temperature in Celsius
// Check if the temperature reading is valid
if (temperature == -127.00) {
Serial.println("Failed to read from DS18B20 sensor!");
} else {
// Print the sensor values to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
// Wait for 2 seconds before taking the next reading
delay(2000);
}