1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include <BluetoothSerial.h> #include <ArduinoJson.h> #include <WiFi.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it #endif static String data_app; BluetoothSerial SerialBT;
bool init_wifi(){ int count = 0; WiFi.begin(); while(WiFi.status()!=WL_CONNECTED){ Serial.print("."); delay(500); count++; if (count==20){ return false;}} return true; }
void setup() { Serial.begin(115200); WiFi.hostname("myESP32"); SerialBT.begin("myESP32"); Serial.println("现在可进行蓝牙配对!"); if(init_wifi()){ Serial.println(); Serial.println("wifi连接成功"); }else{ Serial.println(); Serial.println("wifi连接失败请使用蓝牙配网"); } }
void loop() { bluetooth(); }
void bluetooth() { if (Serial.available()) { SerialBT.write(Serial.read()); } if (SerialBT.available()){ data_app = ""; data_app = SerialBT.readString(); Serial.print("接收数据为:"); Serial.println(data_app); if (data_app=="ip_mac"){ String ip_mac = ipmac(); SerialBT.println(ip_mac); Serial.println(ip_mac); } else if(data_app.indexOf("ssid")!=-1){ StaticJsonDocument<200> doc; DeserializationError error = deserializeJson(doc, data_app); if (error) { Serial.println("数据格式错误"); SerialBT.print("Incorrect format of incoming data"); } else { String sid = doc["ssid"]; String pwd = doc["password"]; if (sid!="null"){ Serial.printf("SSID:%s\r\n",sid); if (pwd=="null"){ pwd = ""; } Serial.printf("PAWD:%s\r\n",pwd); if(wifiPW(sid,pwd)){ SerialBT.println("True"); }else{ SerialBT.println("False"); } } else { Serial.println("未识别到wifi数据"); SerialBT.print("Incorrect format of incoming data"); } } } else{ Serial.println("未接收到指令"); SerialBT.print("Incorrect format of incoming data"); } } } bool wifiPW(String sid,String pwd){ WiFi.begin(sid.c_str(), pwd.c_str()); int count = 0; delay(1000); while (WiFi.status()!=WL_CONNECTED){ Serial.print("."); delay(500); count++; if (count>20){ Serial.println(); Serial.println("配网失败"); return false;} } Serial.println(); Serial.println("配网成功"); return true; } String ipmac(){ if(WiFi.isConnected()){ String ip = WiFi.localIP().toString(); String mac = WiFi.macAddress(); return "{'ip':'"+ip+"','mac':'"+mac+"'}"; }else{ return "Not connected to wifi"; } }
|