#include <Wire.h>//alows communications with I2C devices
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>//library for Monochrome OLEDs based on SSD1306 drivers
#define SCREEN_WIDTH 128 // OLED width, in pixels
#define SCREEN_HEIGHT 64 // OLED height, in pixels
//----------- Temperature -----------------
#include <DHT.h>
// Define the sensor type (DHT22)
#define DHT_TYPE DHT22
// Pin where your DHT11 is connected to
#define DHT_PIN 2
// Initialize the DHT sensor
DHT dht(DHT_PIN, DHT_TYPE);
// create an OLED display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
Serial.begin(9600);// Initialize serial communication
// Initialize the DHT sensor
dht.begin();
// initialize OLED display with I2C address 0x3C
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("failed to start SSD1306 OLED"));
while (1);
}
delay(2000); // wait two seconds for initializing
oled.clearDisplay(); // clear display
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
oled.setTextSize(1); // set text size
oled.setTextColor(WHITE); // set text color
oled.setCursor(21, 0); // set position to display (x,y)
oled.print("Weather Station");
oled.setCursor(0, 20); // set position to display (x,y)
oled.print("Temperature"); // set text
oled.setCursor(80, 20); // set position to display (x,y)
oled.print(temperature); // set text
oled.setCursor(120,20);
oled.print("C");
oled.setCursor(0,45);//set position to display (x,y)
oled.print("Humidity");// set text
oled.setCursor(80,45);
oled.print(humidity);// set text
oled.setCursor(120,45);
oled.print("%");
oled.drawLine(0, 15, 128, 15, 1);//horiziontal line 1 (x1,y1,x2,y2,colour)
oled.drawLine(0, 35, 128, 35, 1);//horiziontal line 2
oled.drawLine(70, 16, 70, 64, 1);//vertical line 1
oled.display(); // display on OLED
//------Temperature Code Starts Here-----------
// Read temperature and humidity data from the sensor
// float temperature = dht.readTemperature();
// float humidity = dht.readHumidity();
// Check if the data was successfully read from the sensor
if (!isnan(temperature) && !isnan(humidity)) {
// Print the temperature and humidity values to the serial monitor
Serial.print("Temperature (°C): ");
Serial.println(temperature);
Serial.print("Humidity (%): ");
Serial.println(humidity);
} else {
// If there was an error reading data from the sensor, print an error message
Serial.println("Error reading from DHT sensor");
}
// Delay for a few seconds before taking the next reading
delay(2000);
}