/****************** Arduino SPI with DHT22 and UltraSonic ******************/
/****************** 240x320 2.8" LCD-TFT display with SPI interface *********/
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#define TFT_DC 9
#define TFT_CS 10
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// DHT lib
#include <Adafruit_Sensor.h>
#include <DHT.h>
// DHT22
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
//Variables
float hum; //Stores humidity value
float temp; //Stores temperature value
float dis;
float converted = 0.00;
// Sonic Sensor
#define ECHO_PIN 4
#define TRIG_PIN 3
void setup()
{
tft.begin();
// Initialize device.
dht.begin();
// Sonic
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
//Rotate the screen to right direction
tft.setRotation(1);
//Print the headers
printHeader();
}
void loop()
{
//Read data and store it to variables hum and temp
hum = dht.readHumidity();
temp= dht.readTemperature();
printSensorData();
}
//Print headers
unsigned long printHeader(void )
{
tft.fillRect(0, 0, 200, 64, ILI9341_GREEN);
tft.fillRect(0, 64, 200, 64, ILI9341_RED);
tft.fillRect(0,128, 200, 64, ILI9341_CYAN);
tft.fillRect(0,192, 200, 64, ILI9341_ORANGE);
unsigned long start = micros();
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(3);
tft.setCursor(50, 0+20);
tft.print("CELCIUS");
tft.setCursor(50, 64+20);
tft.print("KELVIN");
tft.setCursor(50, 128+20);
tft.print("HUMIDITY");
tft.setCursor(50, 192+20);
tft.print("DISTANCE");
return micros() - start;
}
unsigned long printSensorData()
{
tft.fillRect(201, 0, 240, 64,ILI9341_ORANGE);
tft.fillRect(201, 64, 240, 64,ILI9341_CYAN);
tft.fillRect(201,128, 240, 64,ILI9341_RED);
tft.fillRect(201,192, 240, 64,ILI9341_GREEN);
unsigned long start = micros();
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(2);
tft.setCursor(201,0+20);
tft.print(temp);
tft.print(" ");
tft.print((char)247);
tft.println("C");
//Kelvin
//T(K) = T(°C) + 273.15
converted = temp + 273.15;
tft.setCursor(201,64+20);
tft.print(converted);
tft.print(" ");
tft.println("K");
//Humidity
tft.setCursor(201,128+20);
tft.print(hum);
tft.print(" ");
tft.println("%");
// Distance
dis = readDistanceCM();
tft.setCursor(201,192+20);
tft.print(dis);
tft.print(" ");
tft.println("cm");
return micros() - start;
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}