ESP8266 上线
1.首先配置esp8266 WIFI模块
使用USB转 TTL 连接 esp8266 WIFI模块,波特率115200
//查询固件版本
AT+GMR
//设置WiFi应用模式为Station
AT+CWMODE=3
//连接到WiFi路由器,请将SSID替换为路由器名称,Password替换为路由器WiFi密码
AT+CWJAP="SSID","Password"
//连接单连模式
AT+CIPMUX=0
//设置为透传模式
AT+CIPMODE=1
//进入透传模式
AT+SAVETRANSLINK=1,"121.42.180.30",8181,"TCP"
每输入一条指令,均会有反馈,如果没有,重新连接串口,继续发送指令
2. ESP8266 WIFI模块 连接 arduino
#include <aJSON.h> //============= 此处必须修改============ String DEVICEID="xxxx"; // 你的设备编号 ID == String APIKEY="xxxxxxxx"; // 设备密码== APIKEY //======================================= 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(); //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); 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"){ sayToClient(F_C_ID,"LED on!"); } if(C=="stop"){ 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; } } }
上传代码到 Arduino uno R3时,要将连接到Arduino上的 TX,RX 拔出,要不会上传出错(Arduino nano板因为带不动Esp8266所以不能使用)
3.
作者:Dozeoo
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。