基于stm32和esp8266采用mqtt方式连接华为云代码
时间: 2024-04-30 15:22:33 浏览: 170
STM32F1系列单片机+ESP8266接入阿里云和华为云C语言实现MQTT协议
5星 · 资源好评率100%
下面是基于STM32和ESP8266采用MQTT方式连接华为云的代码:
```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define WIFI_SSID "your_wifi_ssid"
#define WIFI_PASSWORD "your_wifi_password"
#define MQTT_SERVER "your_mqtt_server"
#define MQTT_PORT 1883
#define MQTT_USERNAME "your_mqtt_username"
#define MQTT_PASSWORD "your_mqtt_password"
#define MQTT_TOPIC "your_mqtt_topic"
SoftwareSerial espSerial(2, 3); // RX, TX
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
espSerial.begin(115200);
lcd.begin();
lcd.backlight();
lcd.print("Connecting to WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
lcd.setCursor(0, 1);
lcd.print(".");
}
lcd.clear();
lcd.print("WiFi Connected");
mqttClient.setServer(MQTT_SERVER, MQTT_PORT);
mqttClient.setCallback(mqttCallback);
}
void loop() {
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
String temp = readTemperature();
mqttClient.publish(MQTT_TOPIC, temp.c_str());
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temp);
delay(1000);
}
void mqttReconnect() {
while (!mqttClient.connected()) {
Serial.println("Connecting to MQTT broker...");
if (mqttClient.connect("ESP8266", MQTT_USERNAME, MQTT_PASSWORD)) {
Serial.println("MQTT connected");
mqttClient.subscribe(MQTT_TOPIC);
} else {
Serial.print("MQTT connection failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Received message [");
Serial.print(topic);
Serial.print("]: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
String readTemperature() {
String temp;
espSerial.println("AT+CIPSTART=\"TCP\",\"api.openweathermap.org\",80");
if (espSerial.find("OK")) {
Serial.println("TCP connection established");
String request = "GET /data/2.5/weather?q=London,uk&APPID=your_api_key HTTP/1.1\r\nHost: api.openweathermap.org\r\nConnection: close\r\n\r\n";
espSerial.print("AT+CIPSEND=");
espSerial.println(request.length());
if (espSerial.find(">")) {
Serial.println("Sending request");
espSerial.print(request);
if (espSerial.find("CLOSED")) {
Serial.println("TCP connection closed");
} else {
Serial.println("Error closing TCP connection");
}
} else {
Serial.println("Error sending request");
}
} else {
Serial.println("Error establishing TCP connection");
}
return temp;
}
```
这段代码连接到Wi-Fi并建立MQTT连接,然后每秒钟读取温度并将其发布到MQTT主题“your_mqtt_topic”中。当接收到来自MQTT主题的消息时,它将在串行监视器中打印出来。请注意,您需要将代码中的"WIFI_SSID","WIFI_PASSWORD","MQTT_SERVER","MQTT_USERNAME","MQTT_PASSWORD"和"MQTT_TOPIC"替换为您自己的值。也需要更改“readTemperature”函数中的API密钥和查询参数,以获取您所需的实际温度值。
阅读全文