Advertisement
MrAyushBajpai

Arduino Code v1

Oct 13th, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "DHT.h"
  2.  
  3. #define DHTPIN 2       // Pin connected to the DHT sensor
  4. #define DHTTYPE DHT11  // DHT 22 (AM2302)
  5. #define MOTORPIN 8     // Pin connected to the motor
  6.  
  7. // Initialize DHT sensor
  8. DHT dht(DHTPIN, DHTTYPE);
  9.  
  10. void setup() {
  11.   Serial.begin(9600);
  12.   Serial.println();
  13.   Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");
  14.  
  15.   // Initialize the DHT sensor
  16.   dht.begin();
  17.  
  18.   // Set motor pin as OUTPUT
  19.   pinMode(MOTORPIN, OUTPUT);
  20.   digitalWrite(MOTORPIN, LOW); // Ensure motor is off initially
  21. }
  22.  
  23. void loop() {
  24.   // Read humidity and temperature
  25.   float hum = dht.readHumidity();
  26.   float temp = dht.readTemperature();
  27.  
  28.   // Check if any reads failed
  29.   if (isnan(hum) || isnan(temp)) {
  30.     Serial.println("Failed to read from DHT sensor!");
  31.     return;
  32.   }
  33.  
  34.   // Print the values to the serial monitor
  35.   Serial.print("Humidity: ");
  36.   Serial.print(hum);
  37.   Serial.print(" %, Temp: ");
  38.   Serial.print(temp);
  39.   Serial.println(" Celsius");
  40.  
  41.   // Control the motor based on temperature
  42.   if (temp > 30) {
  43.     digitalWrite(MOTORPIN, HIGH); // Turn the motor ON
  44.     Serial.println("Motor: ON");
  45.   } else {
  46.     digitalWrite(MOTORPIN, LOW);  // Turn the motor OFF
  47.     Serial.println("Motor: OFF");
  48.   }
  49.  
  50.   delay(2000);  // Wait a few seconds between readings
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement