赞
踩
输入下列代码上传到开发板(作者用的是ESP8266)
- void setup() {
- pinMode(LED_BUILTIN, OUTPUT);
- }
-
- void loop() {
- digitalWrite(LED_BUILTIN, LOW);
-
- delay(1000);
- digitalWrite(LED_BUILTIN, HIGH);
- delay(2000);
- }
看到ESP8266上蓝色的呼吸灯一闪一闪就成功啦!!!
- const char *ssid = "Jason"; // 输入你的WiFi名称
- const char *password = "88888888"; // 输入你的WiFi密码
- const char *mqtt_broker = "10.12.3.89"; //输入你的无线局域网适配器IPv4地址
- const int mqtt_port = 1883; //默认为1883
Win+R打开运行框-->输入cmd-->输入ipconfig-->查找IPv4地址
ESP8266接入服务器
创建WebSocket客户端
下发指令
查看ESP8266接收指令情况
- #include <ESP8266WiFi.h> //esp8266
- #include <PubSubClient.h>
- //#include <WiFi.h> // esp32
-
- const char *ssid = "Jason"; // 输入你的WiFi名称
- const char *password = "88888888"; // 输入你的WiFi密码
- const char *mqtt_broker = "10.12.3.89"; //输入你的无线局域网适配器IPv4地址
- const int mqtt_port = 1883; //默认为1883
-
- WiFiClient espClient;
- PubSubClient client(espClient);
-
- void setup() {
- pinMode(LED_BUILTIN, OUTPUT);
- Serial.begin(115200); // 频段
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.println("Connecting to WiFi..");
- }
- Serial.println("Connected to the WiFi network");
- client.setServer(mqtt_broker, mqtt_port);
- client.setCallback(callback);
- while (!client.connected()) {
- Serial.println("Connecting to public emqx mqtt broker.....");
- if (client.connect("esp8266-client")) {
- Serial.println("Public emqx mqtt broker connected");
- } else {
- Serial.print("failed with state ");
- Serial.print(client.state());
- delay(2000);
- }
- }
- // publish and subscribe
- client.publish("esp8266/test", "hello emqx");
- client.subscribe("Android");
- }
-
- void callback(char *topic, byte *payload, unsigned int length) {
-
- Serial.print("Message arrived in topic: ");
- Serial.println(topic);
- Serial.print("Message:");
- String message;
- for (int i = 0; i < length; i++) {
- message = message + (char) payload[i]; // convert *byte to string
- }
- Serial.print(message);
- if (message == "lon") {
- digitalWrite(LED_BUILTIN, LOW);// LED on
- Serial.print(" on ready");
- }
-
- if (message == "loff"){
- digitalWrite(LED_BUILTIN, HIGH);// LED off
- Serial.print(" on ready");
- }
-
- Serial.println();
- Serial.println("-----------------------");
- }
-
- void loop() {
- // digitalWrite(LED_BUILTIN, LOW);
-
- // delay(1000);
- // digitalWrite(LED_BUILTIN, HIGH);
- // delay(2000);
- client.loop();
- }
本文为作者独立编写
本BLOG上所有的原创文章未经本人许可,不得用于商业用途及传统媒体。网络媒体转载请注明出处,否则属于侵权行为。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。