arduino uno通过esp8266将数据传到阿里云物联网平台代码
时间: 2023-04-01 18:04:34 浏览: 248
esp8266_on_arduino_uno:Arduino UNO 上 wifi ESP8266 模块的示例脚本
5星 · 资源好评率100%
您好,以下是将Arduino Uno通过ESP8266将数据传到阿里云物联网平台的代码示例:
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.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);
void setup() {
Serial.begin(960);
espSerial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
mqttClient.setServer(MQTT_SERVER, MQTT_PORT);
mqttClient.setCallback(mqttCallback);
while (!mqttClient.connected()) {
Serial.println("Connecting to MQTT server...");
if (mqttClient.connect("arduino", MQTT_USERNAME, MQTT_PASSWORD)) {
Serial.println("Connected to MQTT server");
mqttClient.subscribe(MQTT_TOPIC);
} else {
Serial.println("Failed to connect to MQTT server");
delay(100);
}
}
}
void loop() {
if (espSerial.available()) {
String data = espSerial.readStringUntil('\n');
Serial.println("Received data: " + data);
mqttClient.publish(MQTT_TOPIC, data.c_str());
}
mqttClient.loop();
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Received message [");
Serial.print(topic);
Serial.print("]: ");
for (int i = ; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
阅读全文