心血来潮,想把家里的太阳能热水器和水塔写个程序用8266去控制,然后用点灯平台,让智能音箱读取温度和水位,还要能控制自动上水等。
因为很多传感器还没有到,所以用手头上仅有的模块做了初步一个模型。
这是根据电阻水位传感器控制上水的0.001版本,代码冗余比较严重,以后会优化,业余写的代码,大家多多指教
#include <Ticker.h>
#define AD0 A0
#define AD1 1
#define AD5 5
int delayTime = 10000; //定时需要延时的时长,毫秒ms 一般是45分钟
double waterHeight = 0;//水位数值
int acctionSign = 0; //抽水标志
int acctionWaterSign = 0; //重复抽水标志,如果是1 则延时后再试
Ticker acctionTime;
void acctionWater(){
pinMode(AD5,INPUT); //停止抽水
acctionWaterSign = acctionWaterSign+1;
Serial.print("the ");
Serial.print(acctionWaterSign);
Serial.println(" times acction,after 20s ,but no water up,time out and stop !");
}
//acctionWater 执行后 ,水位依然是小于25%,那么程序 中止 10S后再执行
void acctionDelay(){
pinMode(AD5,INPUT); //停止抽水
Serial.println("Delay 10S !");
delay(delayTime);
}
void setup() //程序初始化
{
pinMode(AD0,OUTPUT);//设置输出模式
pinMode(AD1,INPUT);//设置输入模式
//pinMode(AD5,OUTPUT);//设置输入模式
Serial.begin(9600);//设置波特率9600
acctionTime.attach(20,acctionWater); //每隔20S 执行一次关水
}
void loop()//程序主体循环
{
waterHeight = analogRead(AD0); //读取模拟口AD0的值,存入waterHeight变量 read 0-1023 write 0-254
Serial.print("water height = "); //串口输出"waterHeight = "
Serial.print(waterHeight/1024*100); //串口输出waterHeight变量的值,并换行
Serial.println("%");
if(waterHeight/1024*100<=25){
pinMode(AD5,OUTPUT); //水位小于25%开始抽水
delay(delayTime); //抽水时间
acctionSign = 1;
}
if(waterHeight/1024*100>90){
pinMode(AD5,INPUT); //水位大于95%停止抽水
acctionSign = 0;
acctionWaterSign = 0;
}
if(digitalRead(AD5)==1){
Serial.print("switch is :");
Serial.println("Now water acction stop ...");
}else{
Serial.print("switch is :");
Serial.println("Now water acction start ...");
}
//如果抽了一次水,但是水位还是小于25% 那么就执行延时
if(acctionWaterSign >= 1 && waterHeight/1024*100<=25){
acctionDelay();
}
delay(1000); //延时500ms
}