/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
*********/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
#define DHTPIN 2 // Define the digital pin where the DHT22 is connected
#define BUZZER_PIN 4
#define DHTTYPE DHT22
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
pinMode(BUZZER_PIN, OUTPUT);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.clearDisplay();
printMsg("Welcome to",30,15);
printMsg("Smart irrigation",15,35);
display.display();
delay(3000);
}
void loop() {
// Read temperature and humidity from the DHT sensor.
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
display.clearDisplay();
// High temprature warning
if(temperature > 50){
printMsg("Warning!!!",30,15);
printMsg("High Temprature",15,35);
display.display();
warningTone();
delay(1000);
return;
}
String humidityData = "Humidity:" + String(humidity) + " %";
String temp = "Temp:" + String(temperature) + " C";
printMsg("Smart irrigation",18,0);
printMsg(humidityData,0,15);
printMsg(temp,0,27);
printMsg("Soil moisture: 20%",0,40);
printMsg("Irrigate: Yes",0,55);
display.display();
}
void printMsg(String msg, int xAxis,int yAxis){
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(xAxis, yAxis);
// Display static text
display.println(msg);
}
void warningTone(){
for (int i = 0; i < 2; i++) {
// High-pitched tone
tone(BUZZER_PIN, 2500); // 2500 Hz frequency
delay(100); // Play for 0.1 second
noTone(BUZZER_PIN); // Turn off the buzzer
delay(100); // Pause for 0.1 second
// Medium-pitched tone
tone(BUZZER_PIN, 1800); // 1800 Hz frequency
delay(150); // Play for 0.15 second
noTone(BUZZER_PIN); // Turn off the buzzer
delay(100); // Pause for 0.1 second
// Low-pitched tone
tone(BUZZER_PIN, 1200); // 1200 Hz frequency
delay(200); // Play for 0.2 second
noTone(BUZZER_PIN); // Turn off the buzzer
delay(100); // Pause for 0.1 second
}
}