通过过串口给esp8266发送数据,但是后面总是跟着一段乱码,大佬们帮看下这是什么原因导致的,有啥靠谱的解决方法
代码贴在这里
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define WIFI_SSID "lyq"
#define WIFI_PASSWD "01234567890"
#define MQTT_SERVER "file:///C:\Users\ASUS\AppData\Roaming\Tencent\QQTempSys\%W@GJ$ACOF(TYDYECOKVDYB.png121.89.187.31"
#define MQTT_PORT 1883
#define MQTT_USRNAME "18b20"
#define CLIENT_ID "18b20_001"
#define MQTT_PASSWD "123456"
#define ALINK_BODY_FORMAT "%s"
#define ALINK_TOPIC_PROP_POST "/18b20"
#define temperature_topic "temp"
unsigned long i = 0, lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void data_recieve_post()
{
char a[30]; //定义字符数组,接受来自上位机的数据
char c[30];
int i = 0;
while (!Serial.available()); //等待数据传送过来,若没有数据,一直等待,即执行到本行不向下执行
while (Serial.available()) //当发现缓存中有数据时,将数据送至字符数组a中
{
a = Serial.read();
i++;
delay(10);
}
sprintf(c, ALINK_BODY_FORMAT, a);
client.publish(temperature_topic, c);
Serial.println(c);
}
void setup()
{
pinMode(4,INPUT_PULLUP);
Serial.begin(115200);
wifiInit();
}
void loop()
{
if (millis() - lastMs >= 500)
{
lastMs = millis();
mqttCheckConnect();
data_recieve_post();
}
client.loop();
}
图错误的界面
|