发送多变量与nodemcu ubidots esp8266吗?



我有一个关于健康监测的项目,我使用NodeMCU esp8266设备和ad8232用于ecg, max30102用于spo2和bpmI想要使用wifi在ubidot上显示这三个变量,但平台说没有信息"没有发现信息",如果你只有一个变量,例如ecg,平台响应并显示图表。但是如果我想处理这三个变量,它就没有响应了。请帮助如果错误是在代码。下面是声明变量的代码:

#define DEVICE_LABEL "monitoring" // Put the device label
#define VARIABLE_LABEL_1 "ecgmoy" // Put the variable label
#define VARIABLE_LABEL_2 "spo2" // Put the variable label
#define VARIABLE_LABEL_3 "heartRate" // Put the variable label

和用于发送和显示:

dtostrf(ecgmoy, 4, 2, str_val_1);
dtostrf(spo2, 4, 2, str_val_2);
dtostrf(heartRate, 4, 2, str_val_3);
sprintf(topic, "%s", ""); // Cleans the topic content
sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL); 
sprintf(payload, "%s", ""); // Cleans the payload content
sprintf(payload, "{"%s":", VARIABLE_LABEL_1); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_1); // Adds the value
sprintf(payload, "{"%s":", VARIABLE_LABEL_2); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_2); // Adds the value
sprintf(payload, "%s, "%s":", payload, VARIABLE_LABEL_3); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_3); // Adds the value
sprintf(payload, "%s}", payload); // Closes the dictionary brackets
Serial.println("Publishing data to Ubidots Cloud");
client.publish(topic, payload);
client.loop();  
delay(10);   
}

请帮忙!

#include <ESP8266WiFi.h>
#include <Wire.h>
#include <PubSubClient.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"
#define WIFISSID "W055" // Put your Wifi SSID here
#define PASSWORD "123456789" // Put your WIFI password here
#define TOKEN "BBFF-9y3LaMBjvWcslJB1qRCLWwUku8YxED" // Put your Ubidots' TOKEN
#define DEVICE_LABEL "monitoring" // Put the device label
#define VARIABLE_LABEL_1 "ecgmoy" // Put the variable label
#define VARIABLE_LABEL_2 "spo2" // Put the variable label
#define VARIABLE_LABEL_3 "heartRate" // Put the variable label

#define MQTT_CLIENT_NAME "myecgsensor" // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string; 
//it should be a random and unique ascii string and different from all other devices

/****************************************
* Define Constants
****************************************/
#define output A0 // Set the A0 as output
const int N=10;      // Définition du nombre d'échantillons
int ecg[N];          // un tableau pour stocker les échantillons lus
int n= 0;       // l'indice de l'échantillon courant
float ecgmoy =0 ;    // la moyenne des échantillons mémorisés
float somme =0;   // la somme des échantillons mémorisés
//........SpO2........//
MAX30105 particleSensor;
uint32_t irBuffer[100]; //infrared LED sensor data
uint32_t redBuffer[100];  //red LED sensor data
int32_t bufferLength; //data length
int32_t spo2; //SPO2 value
int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
int32_t heartRate; //heart rate value
int8_t validHeartRate; //indicator to show if the heart rate calculation is valid

char mqttBroker[] = "industrial.api.ubidots.com";
char payload[100];
char topic[150];
// Space to store values to send
char str_val_1[10];
char str_val_2[10];
char str_val_3[10];

/****************************************
* Auxiliar Functions
****************************************/
WiFiClient ubidots;
PubSubClient client(ubidots);
void callback(char* topic, byte* payload, unsigned int length) {
char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
Serial.write(payload, length);
Serial.println(topic);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");    
// Attemp to connect
if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
Serial.println("Connected");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 2 seconds");
// Wait 2 seconds before retrying
delay(2000);
}
}
}

/****************************************
* Main Functions
****************************************/
void setup() {
Serial.begin(115200);
WiFi.begin(WIFISSID, PASSWORD);
Serial.println();
Serial.print("Waiting for WiFi..."); 
while (WiFi.status()  != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi Connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqttBroker, 1883);
client.setCallback(callback); 
// Assign the pin as INPUT 
pinMode(output, INPUT); 
/************************/

/*************************/

pinMode  (LED_BUILTIN, OUTPUT);
Serial.print("Initializing pulse oximeter..");
if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
{
Serial.println(F("MAX30102 was not found. Please check wiring/power."));
while (1);
}
Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
while (Serial.available() == 0) ; //wait until user presses a key
Serial.read();
byte ledBrightness = 60; //Options: 0=Off to 255=50mA
byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
int pulseWidth = 411; //Options: 69, 118, 215, 411
int adcRange = 4096; //Options: 2048, 4096, 8192, 16384
particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
for (int i=0 ; i<N ; i++)
{ 
ecg [i] = 0; 
}
}
void loop() {
if (!client.connected()) 
{  reconnect(); }
Serial.begin (115200);
/******spo2********/
bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps
//read the first 100 samples, and determine the signal range
for (byte i = 0 ; i < bufferLength ; i++)
{  
while (particleSensor.available() == false) //do we have new data?
particleSensor.check(); //Check the sensor for new data
redBuffer[i] = particleSensor.getRed();
irBuffer[i] = particleSensor.getIR();
particleSensor.nextSample(); //We're finished with this sample so move to next sample  
}
//calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
//Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
while (1)  {
//dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
for (byte i = 25; i < 100; i++)   {   redBuffer[i - 25] = redBuffer[i];
irBuffer[i - 25] = irBuffer[i];   }
//take 25 sets of samples before calculating the heart rate.
for (byte i = 75; i < 100; i++)
{     
while (particleSensor.available() == false) //do we have new data?
particleSensor.check(); //Check the sensor for new data
redBuffer[i] = particleSensor.getRed();
irBuffer[i] = particleSensor.getIR();
particleSensor.nextSample(); //We're finished with this sample so move to next sample
//send samples and calculation result to terminal program through UART
Serial.print(F("red="));
Serial.print(redBuffer[i], DEC);
Serial.print(F(", ir="));
Serial.print(irBuffer[i], DEC);
Serial.print(F(", HR="));
Serial.print(heartRate, DEC);
Serial.print(F(", HRvalid="));
Serial.print(validHeartRate, DEC);
Serial.print(F(", SPO2="));
Serial.print(spo2, DEC);
Serial.print(F(", SPO2Valid="));
Serial.println(validSPO2, DEC);
}
//After gathering 25 new samples recalculate HR and SP02
maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
}
/*******ecg*******/
somme = somme - ecg [n];
// Lecture du capteur
ecg[n] = analogRead(output);
Serial.print(ecg [n]);
// Ajout du dernier echantillon
somme = somme + ecg [n];
// Incrémentation de n
n++;
if (n>= N){
// ...retour au début
n =0; }
ecgmoy = somme / N;
//delay(20);

dtostrf(ecgmoy, 4, 2, str_val_1);
dtostrf(spo2, 4, 2, str_val_2);
dtostrf(heartRate, 4, 2, str_val_3);
sprintf(topic, "%s", ""); // Cleans the topic content
sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL); 
sprintf(payload, "%s", ""); // Cleans the payload content
sprintf(payload, "{"%s":", VARIABLE_LABEL_1); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_1); // Adds the value
sprintf(payload, "{"%s":", VARIABLE_LABEL_2); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_2); // Adds the value
sprintf(payload, "%s, "%s":", payload, VARIABLE_LABEL_3); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_3); // Adds the value
sprintf(payload, "%s}", payload); // Closes the dictionary brackets
Serial.println("Publishing data to Ubidots Cloud");
client.publish(topic, payload);
client.loop();  
delay(10);   
}

的这部分代码:

sprintf(payload, "%s", ""); // Cleans the payload content
sprintf(payload, "{"%s":", VARIABLE_LABEL_1); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_1); // Adds the value
sprintf(payload, "{"%s":", VARIABLE_LABEL_2); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_2); // Adds the value
sprintf(payload, "%s, "%s":", payload, VARIABLE_LABEL_3); // Adds the variable label
sprintf(payload, "%s {"value": %s}", payload, str_val_3); // Adds the value
sprintf(payload, "%s}", payload); // Closes the dictionary brackets

如果您打印出payload,您将注意到ecgmoy缺失并显示为

{"spo2": {"value": xx.xx}, "heartRate": {"value": yy.yy}}

这是由sprintf覆盖payload之前的值引起的,你的代码过度声明了不必要的变量/宏,使其难以跟踪和调试。许多变量没有必要声明为全局变量,最好在使用它的地方声明。

你的代码可以简化为两行代码

char payload[100]={''}; // declare and initialised with ''
sprintf(payload, 
"{"ecgmoy": {"value": %s}, {"spo2": {"value": %s}, "heartRate": {"value": %s}}", 
str_val_1, 
str_val_2, 
str_val_3
);

最新更新