#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for SSD1306 display connected using I2C
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C // I2C address for the SSD1306 display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define DHTPIN A0 // Pin where the DHT11 is connected
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize the I2C communication
Wire.begin();
// Initialize the OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.display();
// Initialize the DHT sensor
dht.begin();
// Set up the serial monitor
Serial.begin(9600);
}
void loop() {
// Read temperature as Celsius
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again)
if (isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Print the temperature to the Serial Monitor
Serial.print(F("Temperature: "));
Serial.print(temperature);
Serial.println(F("°C"));
// Clear the display
display.clearDisplay();
// Display temperature on the OLED
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print(F("Temp: "));
display.print(temperature);
display.print(F(" C"));
// Update the display with the new data
display.display();
// Wait a few seconds between measurements
delay(2000);
}
Sunil Singh
ReplyDelete