In this project, we will use the highly accurate DS18B20 digital temperature sensor to measure ambient temperature and display it on a 2.0-inch TFT screen. The system also features a safety guard: if the temperature exceeds 30°C, the text turns red and an alert message is displayed.
To ensure the display and sensor operate properly, connect the pins according to the following table:
| Component / Pin | Arduino Nano Pin | Description |
|---|---|---|
| DS18B20 (VCC) | 5V | Sensor Power Supply |
| DS18B20 (Data) | D2 | Data Line (with 4.7k pull-up to VCC) |
| TFT SCL (SCK) | D13 | SPI Clock |
| TFT SDA (MOSI) | D11 | SPI Data |
| TFT RES (RST) | D9 | Display Reset |
| TFT DC | D8 | Data/Command |
| TFT CS | D10 | Chip Select |
| TFT BLK | 3.3V / 5V | Display Backlight |
The code below reads the temperature, updates the display every two seconds, and verifies the active alarm boundaries.
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#define TFT_CS 10
#define TFT_RST 9
#define TFT_DC 8
#define ONE_WIRE_BUS 2
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float tempC = 0;
const float ALARM_TEMP = 30.0;
void setup() {
sensors.begin();
tft.init(240, 320);
tft.setRotation(1);
tft.fillScreen(ST77XX_BLACK);
tft.setCursor(20, 20);
tft.setTextColor(ST77XX_WHITE);
tft.setTextSize(2);
tft.println("Thermometer Station");
}
void loop() {
sensors.requestTemperatures();
tempC = sensors.getTempCByIndex(0);
tft.fillRect(60, 100, 200, 80, ST77XX_BLACK);
if (tempC > ALARM_TEMP) {
tft.setTextColor(ST77XX_RED);
tft.setCursor(20, 200);
tft.setTextSize(2);
tft.println("ALARM: TOO HOT!");
} else {
tft.fillRect(20, 200, 240, 30, ST77XX_BLACK);
tft.setTextColor(ST77XX_GREEN);
}
tft.setCursor(60, 100);
tft.setTextSize(5);
tft.print(tempC, 1);
tft.setTextSize(2);
tft.print(" C");
delay(2000);
}