#include <DHT.h>
#define DHTPIN 5 // Pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 11 or DHT22
#define trigPin 3 // Pin connected to the trigger pin of the ultrasonic sensor
#define echoPin 2 // Pin connected to the echo pin of the ultrasonic sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.println("write 1 for temperature and humidty measurement");
Serial.println("write 2 for distance measurement");
}
void loop() {
// Wait for input from the serial monitor
while (Serial.available() == 0 ) {
// Do nothing until input is received
}
int input = Serial.parseInt(); // Read the input integer from the serial monitorr
if(input==1){
float temperature = dht.readTemperature(); // Read temperature value
float humidity = dht.readHumidity(); // Read humidity value
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print temperature and humidity values to the serial monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.println("%");
delay(2000); // Wait 2 seconds between measurements
} else if(input==2){
// Send a pulse to the ultrasonic sensor
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
float distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short time before taking another measurement
delay(1000);
}
// Wait a short time before taking another input
delay(1000);
}