创作者:Tonyzhang1371 | 更新日期:2018-06-22 | 在线时长:15分
Tonyzhang1371的第一个设备,来自贝壳物联(play 亮 stop灭)
暂无。
esp8266 led
/*
*注意 :Arduino IDE版本请使用1.6.5-1.8.2
*/
#include
//============= 此处必须修该============
String DEVICEID="6456"; // 你的设备编号 ==
String APIKEY="36f0460f0"; // 设备密码==
//=======================================
const int LED = 4;// LED正极连接针脚4
unsigned long lastCheckInTime = 0; //记录上次报到时间
const unsigned long postingInterval = 40000; // 每隔40秒向服务器报到一次
String inputString = "";
boolean stringComplete = false;
boolean CONNECT = true;
char* parseJson(char *jsonString);
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(115200);
delay(5000);
}
void loop() {
if(millis() - lastCheckInTime > postingInterval || lastCheckInTime==0) {
checkIn();
}
serialEvent();
if (stringComplete) {
inputString.trim(); //去掉string首尾的空格
//Serial.println(inputString);
if(inputString=="CLOSED"){
Serial.println("connect closed!");
CONNECT=false;
}else{
int len = inputString.length()+1;
if(inputString.startsWith("{") && inputString.endsWith("}")){
char jsonString[len];
inputString.toCharArray(jsonString,len); //string转char[]
aJsonObject *msg = aJson.parse(jsonString);
processMessage(msg);
aJson.deleteItem(msg);
}
}
// clear the string:
inputString = "";
stringComplete = false;
}
}
void checkIn() {
if (!CONNECT) {
Serial.print("+++");
delay(500);
Serial.print("\r\n");
delay(1000);
Serial.print("AT+RST\r\n");
delay(6000);
CONNECT=true;
lastCheckInTime=0;
}
else{
Serial.print("{\"M\":\"checkin\",\"ID\":\"");
Serial.print(DEVICEID);
Serial.print("\",\"K\":\"");
Serial.print(APIKEY);
Serial.print("\"}\r\n");
lastCheckInTime = millis();
}
}
void processMessage(aJsonObject *msg){
aJsonObject* method = aJson.getObjectItem(msg, "M");
aJsonObject* content = aJson.getObjectItem(msg, "C");
aJsonObject* client_id = aJson.getObjectItem(msg, "ID");
//char* st = aJson.print(msg);
if (!method) {
return;
}
//Serial.println(st);
//free(st);
String M=method->valuestring;
String C=content->valuestring;
String F_C_ID=client_id->valuestring;
if(M=="say"){
if(C=="play"){
digitalWrite(LED, HIGH);
sayToClient(F_C_ID,"LED on!");
}
if(C=="stop"){
digitalWrite(LED, LOW);
sayToClient(F_C_ID,"LED off!");
}
}
}
void sayToClient(String client_id, String content){
Serial.print("{\"M\":\"say\",\"ID\":\"");
Serial.print(client_id);
Serial.print("\",\"C\":\"");
Serial.print(content);
Serial.print("\"}\r\n");
lastCheckInTime = millis();
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == '\n') {
stringComplete = true;
}
}
}