|
最近在使用ESP8266,用arduino语言编程。为了方便,很多时候使用字符串变量,如下:
const char *phone = "";
const char *NameDevice = "";
String T_phone = "";
String DeviceName = "";
void callback(char *topic, byte *payload, unsigned int length)
{
String msg = "";
for (int i = 0; i < length; i++)
{
msg += (char)payload[i];
}
T_phone = msg.substring(msg.indexOf("data_phone\":") + 12, msg.indexOf(",\"userName"));
DeviceName = msg.substring(msg.indexOf("userName\":") + 10, msg.indexOf("}"));
phone= T_phone.c_str();
NameDevice = DeviceName.c_str();
}
void send_sms( )
{
Serial.println("send sms.........");
char param[256] = {0};
sprintf(param, "{\"phone\": \"%s\",\"store\": \"%s\",\"temp\":%.2f,\"hum\":%.2f}\0", phone, NameDevice, T_Device_temp, T_Device_hump);
client.publish(Mqtt_sms_topic, param);
}
发现ESP8266收到的phone和NameDevice数据到晚上就丢了。
后来看了些资料,必须将数据存储到变量里面去,于是改成下面的程序:
const char *phone= "";
const char *NameDevice = "";
String T_phone = "";
String DeviceName = "";
char arr_phone[50]={0};
char arr_NameDevice[50]={0};
void callback(char *topic, byte *payload, unsigned int length)
{
String msg = "";
for (int i = 0; i < length; i++)
{
msg += (char)payload[i];
}
T_phone = msg.substring(msg.indexOf("data_phone\":") + 12, msg.indexOf(",\"userName"));
DeviceName = msg.substring(msg.indexOf("userName\":") + 10, msg.indexOf("}"));
phone= T_phone.c_str();
strncpy(arr_phone,phone,strlen(phone));// phone存入数组
NameDevice = DeviceName.c_str();
strncpy(arr_NameDevice,NameDevice,strlen(NameDevice));//NameDevice 存入数组
}
void send_sms( )
{
char param[256] = {0};
phone=arr_phone;//从数组取出数据 phone
NameDevice=arr_NameDevice;//从数组取出数据NameDevice
sprintf(param, "{\"phone\": \"%s\",\"store\": \"%s\",\"temp\":%.2f,\"hum\":%.2f}\0", phone, NameDevice, T_Device_temp, T_Device_hump);
client.publish(Mqtt_sms_topic, param);
}
现在运行很好,再也没有丢失数据 phone和数据NameDevice |
阿莫论坛20周年了!感谢大家的支持与爱护!!
曾经有一段真挚的爱情摆在我的面前,我没有珍惜,现在想起来,还好我没有珍惜……
|