#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define OLED_WIDTH 128 // OLED display width, in pixels
#define OLED_HEIGHT 64 // OLED display height, in pixels
#define SENSOR_PIN 5 // The Arduino Nano pin connected to DS18B20 sensor's DQ pin
Adafruit_SSD1306 oled(OLED_WIDTH, OLED_HEIGHT, &Wire, -1); // create SSD1306 display object connected to I2C
OneWire oneWire(SENSOR_PIN); // setup a oneWire instance
DallasTemperature DS18B20(&oneWire); // pass oneWire to DallasTemperature library
String temperature1_str, temperature2_str, temperature3_str, temperature4_str;
void setup() {
Serial.begin(9600);
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(2000); // wait for initializing
oled.clearDisplay(); // clear display
oled.setTextSize(2); // text size
oled.setTextColor(WHITE); // text color
oled.setCursor(0, 10); // position to display
DS18B20.begin(); // initialize the sensor
temperature1_str.reserve(10); // to avoid fragmenting memory when using String
temperature2_str.reserve(10);
temperature3_str.reserve(10);
temperature4_str.reserve(10);
}
void loop() {
DS18B20.requestTemperatures(); // send the command to get temperatures
float temperature1_C = DS18B20.getTempCByIndex(0); // read temperature in Celsius
float temperature2_C = DS18B20.getTempCByIndex(1);
float temperature3_C = DS18B20.getTempCByIndex(2);
float temperature4_C = DS18B20.getTempCByIndex(3);
temperature1_str = String(temperature1_C, 2); // two decimal places
temperature2_str = String(temperature2_C, 2);
temperature3_str = String(temperature3_C, 2);
temperature4_str = String(temperature4_C, 2);
Serial.println(temperature1_str);
Serial.println(temperature2_str);
Serial.println(temperature3_str);
Serial.println(temperature4_str); // print the temperature in Celsius to Serial Monitor
oled.clearDisplay(); // clear the display once
oled_display_center("T1:"+ temperature1_str, 0);
oled_display_center("T2:"+ temperature2_str, 16);
oled_display_center("T3:"+ temperature3_str, 32);
oled_display_center("T4:"+ temperature4_str, 48);
oled.display(); // display all at once
}
void oled_display_center(String text, int yOffset) {
int16_t x1, y1;
uint16_t width, height;
oled.getTextBounds(text, 0, 0, &x1, &y1, &width, &height);
oled.setCursor((OLED_WIDTH - width) / 2, yOffset); // position text horizontally centered and vertically at yOffset
oled.println(text);
}