#include <DHT.h>
#include<ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "Adafruit_SGP30.h"
#include <ArduinoJson.h>
const char* ssid = "Redmi"; // 连接 WiFi名 ,修改为自己的WiFi名
const char* password = "12345678"; // 连接 WiFi密码,修改为自己的WiFi密码
/******************产品/设备配置(每个人需要根据自己的产品设备信息去动态更换)**********************/
#define PRODUCT_KEY "********" //产品key 从产品详情获取
#define DEVICE_NAME "phone" //设备deviceName 从设备详情获取
// 服务端相关
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt.cn-shanghai.aliyuncs.com" //阿里云MQTT服务地址
#define MQTT_PORT 1883 //MQTT服务端口
// 校验三元组
#define MQTT_CLIENT_ID DEVICE_NAME "|securemode=3,signmethod=hmacsha1|" //mqtt clientid
#define MQTT_USERNAME DEVICE_NAME "&" PRODUCT_KEY //mqtt username
#define MQTT_PASSWORD "BC22B700B31E6452BE3BF495D35B531921CAAAC9" //mqtt password 通过生成工具获得
// 相关主题 自定义一个主题
#define SUB_TOPIC "/" PRODUCT_KEY "/" DEVICE_NAME "/user/get" //订阅主题
#define PUB_TOPIC0 "/" PRODUCT_KEY "/" DEVICE_NAME "/user/update" //发布主题
#define PUB_TOPIC "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post" //发布主题
/*************************************************************************************************/
/******************配置ESP8266的引脚**********************/
//温度传感器的引脚和类型配置
#define DHTPIN D5
#define DHTTYPE DHT11
const int humanSensor = D0; //人体红外传感器引脚
const int fireSensor = D4; //火焰传感器引脚
const int ultravioletSensor = A0; //紫外线引脚
/*******************************************************/
/******************传感器的存储变量**********************/
int humanState; //检测人体的状态,有人为1,无人为0
int fireState; //检测火焰的状态,有火为1,无火为0
float hum; //湿度值
float temp; //温度值
uint16_t tvoc; //总挥发性有机物
uint16_t co2; //CO2浓度
uint16_t illumination; //光照强度
uint16_t ultraviolet; //紫外线数值
/*****************************************************/
int BH1750address = 0x23; //光照强度传感器地址端接地
byte buff[2]; //光照强度缓存
DHT dht(DHTPIN,DHTTYPE);
Adafruit_SGP30 sgp;
WiFiClient espClient; //创建wifi客户端
PubSubClient client(espClient); //创建MQTT客户端
void setup() {
Serial.begin(115200);
pinMode(humanSensor,INPUT); //设置人体红外传感器引脚为输入模式
pinMode(fireSensor,INPUT); //设置火焰传感器引脚为输入模式
dht.begin(); //开启温湿度传感器DHT11
sgp.begin(); //开启CO2浓度检测
Wire.begin();
BH1750_Init(BH1750address);
setup_wifi();
client.setServer(MQTT_SERVER,MQTT_PORT); //设置阿里云MQTT服务器地址和端口
client.setCallback(callback);
}
void loop() {
getHumanState(); //获取人体传感器的状态
getFireState(); //获取火焰的状态
getUltraviolet();
getTempHum(); //获取温度和湿度值
getVOTC(); //获取总挥发性有机物和二氧化碳的浓度
getIllumination(); //获取光照强度的数值
if (!client.connected()){
reconnect();
}
client.loop();
jsonAndPublish();//把获取的数据转变为json格式,并且上传阿里云
delay(5000);
}
void jsonAndPublish(){
StaticJsonDocument<256> doc;
doc["id"] = "1";
doc["version"] = "1.0";
JsonObject params = doc.createNestedObject("params");
params["humanState"] = humanState;
params["fireState"] = fireState;
params["hum"] = hum;
params["temp"] = temp;
params["tvoc"] = tvoc;
params["co2"] = co2;
params["illumination"] = illumination;
params["ultraviolet"] = ultraviolet;
doc["method"] = "thing.event.property.post";
char output[256];
serializeJson(doc, output);
client.publish(PUB_TOPIC, output);
Serial.println();
Serial.println(output);
Serial.println();
}
void getIllumination(){
if (2 == BH1750_Read(BH1750address))
{
illumination = ((buff[0] << 8) | buff[1]) / 1.2;
Serial.print("光照强度:");
Serial.print(illumination, DEC);
Serial.println("[lx]");
}
}
void getVOTC(){
if (! sgp.IAQmeasure()) {
Serial.println("sgp measurement failed");
return;
}
tvoc = sgp.TVOC;
co2 = sgp.eCO2;
Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.println(" ppb\t");
Serial.print("eCO2 "); Serial.print(sgp.eCO2); Serial.println(" ppm");
}
void getUltraviolet(){
ultraviolet = analogRead(ultravioletSensor);
Serial.print("紫外线: ");
Serial.print(ultraviolet);
Serial.println();
}
void getTempHum(){
hum=dht.readHumidity();
temp=dht.readTemperature();
Serial.print("hum: ");
Serial.print(hum);
Serial.println("%");
Serial.print("temp: ");
Serial.print(temp);
Serial.println("C");
}
void getFireState(){
fireState = digitalRead(fireSensor);
Serial.print("火焰状态: ");
if(fireState==1){
Serial.println("有火");
}else{
Serial.println("无火");
}
}
void getHumanState(){
humanState= digitalRead(humanSensor);
Serial.print("人体状态: ");
if(humanState==1){
Serial.println("有人");
}else{
Serial.println("无人");
}
}
int BH1750_Read(int address) //
{
int i = 0;
Wire.beginTransmission(address);
Wire.requestFrom(address, 2);
while (Wire.available()) //
{
buff[i] = Wire.read(); // receive one byte
i++;
}
Wire.endTransmission();
return i;
}
void BH1750_Init(int address)
{
Wire.beginTransmission(address);
Wire.write(0x10);//1lx reolution 120ms
Wire.endTransmission();
}
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//收到订阅Topic信息的回调处理
void callback(char *topic, byte *payload, unsigned int length){
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++){
Serial.print((char)payload[i]);
}
Serial.println();
// 平台发来命令“1”时开灯
if ((char)payload[0] == '1'){
digitalWrite(BUILTIN_LED, HIGH);
}
else{
digitalWrite(BUILTIN_LED, LOW);
}
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected()){
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)){
Serial.println("MQTT server connected");
// 订阅主题
client.subscribe(SUB_TOPIC);
}
else{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
|