کد:
#include <EEPROM.h>
#include <Bounce2.h>
#include <DHT.h>
#include <LiquidCrystal.h>
#define setBUTTON 13
#define upBUTTON 12
#define downBUTTON 11
#define DHTPIN 2
#define DHTTYPE DHT21
Bounce set;
Bounce up;
Bounce down;
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal lcd(8, 7, 6, 5, 4, 3);
const byte temprelay = 10, humidityrelay = 9;
byte humiditySetpoint = 85;
byte tempSetpoint = 20;
unsigned long prevMillis = 0;
unsigned long currentmillis = millis();
static byte prevdownButton;
static byte prevupButton;
static byte prevsetButton;
static byte prevSetMode;
byte setMode;
void setup() {
lcd.begin(16, 2);
lcd.clear();
dht.begin();
set.attach (setBUTTON);
set.interval(30);
up.attach (upBUTTON);
up.interval(30);
down.attach (downBUTTON);
down.interval(30);
pinMode (setBUTTON, INPUT_PULLUP);
pinMode (upBUTTON, INPUT_PULLUP);
pinMode (downBUTTON, INPUT_PULLUP);
humiditySetpoint = EEPROM.read(0);
tempSetpoint = EEPROM.read(1);
}
void loop() {
set.update();
up.update();
down.update();
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
lcd.clear();
lcd.setCursor(1,0);
lcd.print("Failed to read ");
lcd.setCursor(0,1);
lcd.print("from DHT sensor!");
delay(2000);
lcd.clear();
return;
}
if ((t) >= tempSetpoint){
digitalWrite (temprelay, HIGH);
}
else if ((t) <= tempSetpoint-5)
{
digitalWrite (temprelay, LOW);
}
if ((h) >= humiditySetpoint){
digitalWrite (humidityrelay, LOW);
}
else if ((h) <=humiditySetpoint-10)
{
digitalWrite (humidityrelay, HIGH);
}
if ( setMode != 0) {
if (currentmillis - prevMillis >= 10000UL) {
setMode = 0;
prevMillis = currentmillis;
}
}
if (set.fell()) {
setMode++;
}
prevsetButton = setBUTTON;
if (setMode >= 3) {
setMode = 0;
}
if (setMode != prevSetMode) {
lcd.clear();
prevSetMode = setMode;
}
switch (setMode) {
case 0://normal
lcd.print("Humidity:");
lcd.setCursor(10,0);
lcd.print(h);
lcd.setCursor(15,0);
lcd.print("%");
lcd.setCursor(1,1);
lcd.print("Temp:");
lcd.setCursor(7,1);
lcd.print(t);
lcd.setCursor(12,1);
lcd.print(" *C ");
prevMillis = currentmillis;
break;
case 1://edit temp
if ('upButton' != prevupButton) {
if (up.fell()) {
tempSetpoint = tempSetpoint + 1;
}
prevupButton = 'upButton';
}
if ('downButton' != prevdownButton) {
if (down.fell()) {
tempSetpoint = tempSetpoint - 1;
}
prevdownButton = 'downButton';
}
lcd.setCursor(0, 0);
lcd.print("Set temp:");
lcd.setCursor(7, 1);
lcd.print(tempSetpoint);
lcd.setCursor(9,1);
lcd.print("*C");
EEPROM.write(1, tempSetpoint);
break;
case 2://edit humidity
if ('upButton' != prevupButton) {
if (up.fell()) {
humiditySetpoint = humiditySetpoint + 1;
}
prevupButton = 'upButton';
}
if ('downButton' != prevdownButton) {
if (down.fell()) {
humiditySetpoint = humiditySetpoint - 1;
}
prevdownButton = 'downButton';
}
lcd.setCursor(0, 0);
lcd.print("Set Humidity:");
lcd.setCursor(7, 1);
lcd.print(humiditySetpoint);
lcd.setCursor(9,1);
lcd.print("%");
EEPROM.write(0, humiditySetpoint);
break;
}}