First post here. Just got a starter kit yesterday and a DHT22 and I'm now fiddling around with the tutorials and trying to make them my own.
I followed the wifi weather station tutorial but I'm sending the output to an LCD instead of to a server (I think I will tackle that whole webserver setup next). I got that working just fine, but I decided I would like to have a button which when pressed would switch the temperature printout from Celsius (default) to Farenheit.
I went back to the drawing board and got a push button to act as a switch, turning two LEDs on and off which works well, but, when I try to incorporate the same technique into the weather station it only seems to work while I hold the pushbutton down. Immediately reverting to Celsius on release.
I've been fighting the code for two hours now, just hoping a fresh set of eyes can pick up the issue. I'd really appreciate the help.
Here's the code:
Code: Select all
#include <LiquidCrystal.h>
#include "DHT.h"
LiquidCrystal lcd(12,11,5,4,3,2);
// DHT22 sensor pins
#define DHTPIN 7 // DHT
#define DHTTYPE DHT22
// Create DHT instance
DHT dht(DHTPIN, DHTTYPE);
int CSS = LOW; // Current Switch State
int PSS = LOW; // Previous Switch State
String tempUnit = "C"; // Temperature Unit
long time = 0;
long debounce = 200;
void setup(){
pinMode(6,INPUT);
// Initialize DHT sensor
dht.begin();
lcd.begin(16,2);
}
void loop() {
CSS = digitalRead(6);
// Measure the humidity & temperature
float h = dht.readHumidity();
float t = dht.readTemperature();
// Swap temperature units on button press
if(CSS != PSS && millis() - time > debounce ) {
if(tempUnit == "C") {
tempUnit = "F";
t = dht.readTemperature();
t = t * 9 / 5 + 32; // Adjust calculation for Farenheit
}
else {
tempUnit = "C";
t = dht.readTemperature();
}
time = millis();
}
// Transform to String
String temperature = String((int) t);
String humidity = String((int) h);
// Print data to lcd
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" ");
lcd.print(tempUnit);
lcd.setCursor(0,1);
lcd.print("Humid: ");
lcd.print(humidity);
lcd.print("%");
PSS = CSS;
}
Cheers,
Steven