作者:木子李 | 更新时间:2016-05-30 | 浏览量:2421
#include <SoftwareSerial.h> #include <ESP8266WiFi.h> WiFiClient client; const int thresholdvalue=200; //MQ2目标值,一般空气环境是100左右。 int A0pin=A0; int A1pin=2;//gpio2 const char *ssid = "*****";//这里是我的wifi,你使用时修改为你要连接的wifi ssid const char *password = "*******";//你要连接的wifi密码 const char *host = "121.42.180.30"; const int httpPort =8181; void setup() { pinMode(A1pin, OUTPUT); delay(1000); delay(10000); delay(5000); Serial.begin(9600); Serial.println(); Serial.println(); Serial.print("Connecting to "); //Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); //smartConfig(); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); while (!client.connect(host, httpPort)) { Serial.println("connection failed"); //return; delay(1000); } Serial.print("connecting to "); Serial.println(host); client.write("{\"M\":\"checkin\",\"ID\":\"***\",\"K\":\"*****\"}\r\n");//登陆设备,修改成自己的ID和KEY delay(100); } void loop() { int sensorValue = analogRead(A0pin); //使用AO读取MQ2的值 if((sensorValue-thresholdvalue)>0) { digitalWrite(A1pin,HIGH);//使用A1显示LED状态,HIGH是点亮 delay(5000); } else { Serial.println(analogRead(A0pin)); digitalWrite(A1pin,LOW);//MQ2的值没有超过200,LED灭 } client.write("{\"M\":\"say\",\"ID\":\"***\",\"C\":\"****\"}\r\n");//向设备发送信息,防止掉线 delay(2000); String str1="{\"M\":\"update\",\"ID\":\"****\",\"V\":{\"**** \":\"";//修改成你自己的ID和数据接口ID1存温度 str1+=sensorValue; str1+="\"}}\n"; client.print(str1); Serial.println(sensorValue); while(client.available()){ String line = client.readStringUntil('\r'); Serial.print(line);} delay(3000); }