Sir*_*d G 0 c arduino software-serial esp8266
我正在创建一个系统,该系统通过SoftwareSerial从Arduino Uno读取传感器值,并通过MQTT发布它。但是,我认为所面临的问题更为笼统,我必须承认我是c语言的新手。
我正在读取数据,并将其拆分为程序顶部定义的两个const *变量。
当我读回从串行连接中解析的已保存的“数据”和“主题”变量时,我只会得到垃圾输出,通常会崩溃,从而重启设备。
它可以在read-from-serial函数中成功打印它们,但以后无法正确读取。它与数据的保存方式有关吗?我可以为变量显式分配一些内存吗?
我正在使用ESP8266(ESP07)芯片,其波特率降低且电源电压合适。它似乎运行良好且稳定。
#include <StringSplitter.h>
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <time.h>
//const char* ssid = "xxxx";
//const char* password = "xxxx";
const char* ssid = "xxxx";
const char* password = "xxxx";
const char* mqttServer = "xxxx;
const int mqttPort = xxxx;
const char* mqttUser = "xxxx";
const char* mqttPassword = "xxxx";
int timezone = 1;
int dst = 0;
Run Code Online (Sandbox Code Playgroud)
数据存储在这里:
char* data;
char* topic;
boolean newData = false;
boolean unpublishedData = false;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(19200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
// wait and determine if we have a valid time from the network.
time_t now = time(nullptr);
Serial.print("Waiting for network time.");
while (now <= 1500000000) {
Serial.print(".");
delay(300); // allow a few seconds to connect to network time.
now = time(nullptr);
}
}
Serial.println("");
time_t now = time(nullptr);
Serial.println(ctime(&now));
String datatext = "val: ";
String timetext = ", time: ";
String dataToBeSent = "test";
String timeToBeSent = ctime(&now);
String publishString = datatext + dataToBeSent + timetext + timeToBeSent;
Serial.println("Attempting to publish: " + publishString);
client.publish("trykk/sensor0", (char*) publishString.c_str());
client.subscribe("trykk/sensor0");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
recvWithStartEndMarkers();
showNewData();
publishReceived();
}
void publishReceived() {
if (unpublishedData) {
Serial.println("Hello from inside the publisher loop!");
time_t now = time(nullptr);
char* timeNow = ctime(&now);
Run Code Online (Sandbox Code Playgroud)
它在这里失败,读取数据:
char publishText[30]; //TODO: make it JSON
strcpy( publishText, data );
strcat( publishText, " " );
strcat( publishText, timeNow );
Serial.print("publishText: ");
Serial.println(publishText);
Serial.print("topic: ");
Serial.println(topic);
client.publish(topic, publishText);
client.subscribe(topic);
unpublishedData = false;
} else if (!data) {
Serial.println("No data saved to array.");
} else if (!topic) {
Serial.println("No topic saved to array.");
}
}
void recvWithStartEndMarkers() {
int numChars = 32;
char receivedChars[numChars];
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
if (Serial.available() > 0) {
Serial.println("Hello from inside the receive loop!");
delay(100);
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
Serial.println("Reading from data line.");
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
Serial.println("Found the end marker.");
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
unpublishedData = true;
Run Code Online (Sandbox Code Playgroud)
这部分将值正确地打印给我:
//Split the string
Serial.print("ESP debug: read: ");
Serial.println(receivedChars);
const char s[2] = ":";
*data = strtok(receivedChars, s);
Serial.print(data);
Serial.print(" ");
*topic = strtok(NULL, s);
Serial.println(topic);
}
}
else if (rc == startMarker) {
recvInProgress = true;
Serial.println("Found start marker");
}
}
}
}
//This is gutted as it gave me problems reading the variables
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.print("Topic: ");
Serial.print("stuff");
Serial.print(", data: ");
Serial.println("more stuff");
newData = false;
}
}
Run Code Online (Sandbox Code Playgroud)
从您的代码:
Run Code Online (Sandbox Code Playgroud)char* data; ... *data = strtok(receivedChars, s);
strtok返回a,char*但是您*data = strtok(...)在数据本身是a(未初始化)char *时执行此操作,这是不一致的,并且您有第一个“机会”发生崩溃,因为您是在随机地址上写的。
如果您没有崩溃,并且程序可以继续运行,则数据本身不会被修改并且不会被初始化。
在
Run Code Online (Sandbox Code Playgroud)strcpy( publishText, data ); ... Serial.print(data);
当您使用的数据为char*做Serial.print(data);而strcpy( publishText, data );你从一个随机(当然无效)地址读取,产生你的崩溃。
要纠正,只需替换*data = strtok(receivedChars, s);为data = strtok(receivedChars, s);