#include <Arduino.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <TM1637Display.h>
// 设置传感器、风扇、LED、TM1637数码管引脚
#define DHTsensor 2 //温湿度传感器
#define LED_G 5 //绿色LED
const int CLK = 6; //TM1637的CLK引脚连接到6号引脚
const int DIO = 7; //TM1637的DIO引脚连接到7号引脚
#define LED_R 4 //红色LED
#define FAN 3 //风扇
// 初始化传感器和数码管
DHT dht(DHTsensor, DHT22);
TM1637Display tm1637(CLK, DIO);
//初始化传感器读取到的数值
int temperature = 0;
int humidity = 0;
int data = temperature*100 + humidity;
//设置温湿度阈值
int temperature_limit_low = 15; //温度下限
int temperature_limit_high = 25; //温度上限
int humidity_limit_low = 40; //湿度下限
int humidity_limit_high = 70; //湿度上限
//声明在setup中将要调用的函数
void Monitor_setup();
void Heat_setup();
void Fan_setup();
//设置加热系统中电热丝和风扇的功率
int heat = 128;
int rotate = 128;
void setup() {
//设置串口波特率
Serial.begin(115200);
//调用函数
Monitor_setup();
Heat_setup();
Fan_setup();
}
void loop() {
//读取传感器数据
int temperature = dht.readTemperature();
int humidity = dht.readHumidity();
//数码管显示的数字
int display = temperature*100 + humidity;
//更新TM1637数码管显示的数字
tm1637.showNumberDec(display);
//当温度和湿度在设定范围内时,触发绿色LED
if ((temperature > temperature_limit_low)
&& (temperature < temperature_limit_high)
&& (humidity > humidity_limit_low)
&& (humidity < humidity_limit_high)) {
digitalWrite(LED_G, HIGH); //开启绿色LED
} else {
digitalWrite(LED_G, LOW); //关闭绿色LED
}
if (display > 0) { //如果从客户端获取到了数据 display <=> Serial.available()
String currentLine = Serial.readStringUntil("\n");
String Part1 = currentLine.substring(0, 2); //提取前两个字符
String Part2 = currentLine.substring(2); //提取第三个字符后面的所有字符
// int temperature_set = Part1.toInt(); //将提取的第一部分转换为整数
// int time_set = Part2.toInt(); //将提取的第二部分转换为整数
int temperature_set = 10; //假设设定的温度为10
int time_set = 120000; //假设设定的时间为120秒
//记录程序开始执行的时间并设为静态常量
static unsigned long startTime = millis();
//记录此刻的时间
unsigned long currentTime = millis();
//工作时间未满前不断调整温度
if (currentTime - startTime < time_set) {
if (temperature < temperature_set) {
analogWrite(LED_R, heat++);
digitalWrite(FAN, LOW);
Serial.print("风扇已关闭!电热丝功率为");
Serial.println(heat);
} else {
digitalWrite(LED_R, LOW);
digitalWrite(FAN, rotate++);
Serial.print("电热丝已关闭!风扇功率为");
Serial.println(rotate);
}
} else {
digitalWrite(LED_R, LOW);
digitalWrite(FAN, LOW);
}
currentLine = ""; //将字符串初始化,防止误读
}
}
//创建监控系统setup函数
void Monitor_setup(){
dht.begin(); //开启DHT传感器
tm1637.setBrightness(7); //初始化TM1637数码管,设置亮度(0-7)
pinMode(DHTsensor, INPUT);
pinMode(LED_G, OUTPUT);
digitalWrite(LED_G, LOW);
}
//创建加热系统setup函数
void Heat_setup(){
pinMode(LED_R, OUTPUT);
digitalWrite(LED_R, LOW);
}
//创建风扇系统setup函数
void Fan_setup(){
pinMode(FAN, OUTPUT);
digitalWrite(FAN, HIGH); //风扇以最大功率开始工作
}