#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <Wire.h>
#include <RTClib.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Pin definitions
#define TFT_CS 15
#define TFT_RST 4
#define TFT_DC 2
#define TFT_MOSI 23
#define TFT_CLK 18
#define BUTTON_PIN_1 5
#define BUTTON_PIN_2 32
#define ONE_WIRE_BUS 19
// Initialize display
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST, TFT_MOSI, TFT_CLK);
// Initialize DS1307 RTC
RTC_DS1307 rtc;
// Initialize DS18B20 temperature sensor
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// Variables
bool page1Active = true; // Flag to indicate which page is active
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
Serial.begin(115200);
Wire.begin();
rtc.begin();
if (!rtc.isrunning()) {
Serial.println("RTC is NOT running!");
}
tft.begin();
tft.setRotation(3); // Adjust rotation if needed
//pinMode(TFT_BL, OUTPUT);
//digitalWrite(TFT_BL, HIGH); // Turn on the backlight
// Set up buttons
pinMode(BUTTON_PIN_1, INPUT);
pinMode(BUTTON_PIN_2, INPUT);
sensors.begin();
}
void loop() {
// Check button presses
int buttonState1 = digitalRead(BUTTON_PIN_1);
int buttonState2 = digitalRead(BUTTON_PIN_2);
if (buttonState1 == HIGH && buttonState2 == LOW) {
page1Active = true;
} else if (buttonState1 == LOW && buttonState2 == HIGH) {
page1Active = false;
}
// Update the display based on the active page
if (page1Active) {
displayTime();
} else {
displayTemperature();
}
}
void displayTime() {
DateTime now = rtc.now();
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(50, 100);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print(now.hour());
tft.print(':');
if (now.minute() < 10) {
tft.print('0');
}
tft.print(now.minute());
}
void displayTemperature() {
sensors.requestTemperatures();
float tempC = sensors.getTempCByIndex(0);
if (tempC == -127.00) {
tft.setCursor(50, 100);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Error");
} else {
float tempF = sensors.toFahrenheit(tempC);
// Draw temperature bar graph
int barHeight = map(tempC, 0, 40, 0, 160);
tft.fillRect(60, 180 - barHeight, 20, barHeight, ILI9341_RED);
}
}