My Arduino project is an electrical monitoring system using: Arduino One (plus Ethernet Shield), A Voltage and Ampere sensors (0-5V), and an external server in DigitalOcean. My sketch collect and posts the information to a Real Time database (InfluxDB) and representing the collected data using Grafana. These projects are really a good combination, easy to use and very produce a very nce result.
Mi first test has been collecting the voltage inside my house, and it is working like a charm. So it is time to expand the adquisition of a new variable (Amp), and including the computation of the instant power, and finally posting all the information to my server. At the end I have included the full Arduino sketch.
However with three variables, I am having big issues trying to build the JSON object that has to be HTTP Posted to the real time database server. Unfotunately I am not an expert in Processing/C++, I find Pyhon much more string friendly, and I am lost.
In my code I am trying to build a JSON object according InfluxDB specifications, so I tried the following code with two variables (Vac and Iac):
String data;
data = "[{"
"\"name\":\"VoltAmpPot\","
"\"columns\":[\"VacRMS\""
",\"IacRMS\""
// ",\"Pac\""
"],"
"\"points\":[[" + String(valueVolt) + ","
//+ String(valueAmp) + ","
//+ String(valuekW) + ","
"]]"
"}]";
Serial.println(data);
This is working, I can deal with up to two realtime variables. In the example above valueVolt, valueAmp and valuekW are float elements. The result in the serial console is more or less the following:
[{"name":"VoltAmpPot","columns":["VacRMS","IacRMS"],"points":[[168.91,]]}]
[{"name":"VoltAmpPot","columns":["VacRMS","IacRMS"],"points":[[145.60,]]}]
[{"name":"VoltAmpPot","columns":["VacRMS","IacRMS"],"points":[[139.88,]]}]
[{"name":"VoltAmpPot","columns":["VacRMS","IacRMS"],"points":[[135.92,]]}]
etc
However adding the three variables (Voltage, Intensity and Power), It is not working, when I print the object, the String data is empty, It has not been built.
String data;
data = "[{"
"\"name\":\"VoltAmpPot\","
"\"columns\":[\"VacRMS\""
",\"IacRMS\""
",\"Pac\""
"],"
"\"points\":[[" + String(valueVolt) + ","
+ String(valueAmp) + ","
+ String(sensorAmp) + ","
"]]"
"}]";
Serial.println(data);
No results in the serial console. Why can I expand the JSON object to include the three varaibles?, any hint?. I know there are another ways to concatenate strings, as seen in the different examples in the IDE, however in my way I find everything more direct and clear to make later changes.
Thank you in advanced!
full code, mainly based mainly in a Thingspeak.com sketch :
// Librerias Ethernet + HTTP
#include <Ethernet.h>
#include <SPI.h>
// Definicion Variables Globales
unsigned long Tiempo_UpdatePOST = 1*1000; // 1 Sg para HTTP POST
unsigned long Tiempo_UpdateLED = 500; // 0.5 Sg para LED
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
int VoltPin = A0;
int sensorVolt = 0; // Voltaje Integer (0-1023)
float valueVolt = 0.0; // Voltaje VacRMS (0-450V)
int AmpPin = A1;
int sensorAmp = 0 ; // Amperaje Integer (0-1023)
float valueAmp = 0.0; // Amperios (0-25A)
float valuekW = 0.0; // kW = Volt (450V) x Amp (25A) = 11.250 kW
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0xFE, 0xED };
EthernetClient client;
String Server[] = "XXXXXX";
long int lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
void setup() {
// 1. Inicializacin de PINs Digitales
//pinMode(ledPin, OUTPUT);
// 2. Inicializacin puerto Serie
Serial.begin(9600);
Serial.println("--------------------- SETUP -------------------");
Serial.println("");
Serial.println("--- 1. SETUP: Inicializacion Serial completada ---");
Serial.println("");
// 3. Iniciacion Ethernet Stack
startEthernet();
Serial.println("------------------ FIN SETUP ------------------");
Serial.println("");
}
void loop () {
// 1. Lectura RED ETHERNET
if (client.available())
{
char c=client.read();
Serial.print(c);
}
if (!client.connected() && lastConnected) {
Serial.println("...Desconectado de Red Ethernet");
client.stop();
}
// 2. Calculo de Variables / datos a POSTear
sensorVolt = analogRead(VoltPin);
valueVolt = (float(sensorVolt) / 1023.0 ) * 450.0 ; // Rango Sensor 0-450V
sensorAmp = analogRead(AmpPin);
valueAmp = (float(sensorAmp) / 1023.0 ) * 25.0 ; // Rango Sensor 0-50A
valuekW = valueAmp * valueVolt;
String data;
data = "[{"
"\"name\":\"VoltAmpPot\","
"\"columns\":[\"VacRMS\""
",\"IacRMS\""
// ",\"Pac\""
"],"
"\"points\":[[" + String(valueVolt) + ","
//+ String(valueAmp) + ","
//+ String(sensorAmp) + ","
"]]"
"}]";
Serial.println(data);
// 3. HTTP POST :
if (!client.connected() && ((millis() - lastConnectionTime) > Tiempo_UpdatePOST))
{
updateHTTPPOST(data); // Funcion POSTEA datos a servidor
}
// Resetear la conexion a Internet si ha habido 3 fallos de conexion
if (failedCounter > 3) {
failedCounter = 0;
startEthernet();
}
lastConnected = client.connected();
}
/////////////////////////////
// FUNCION:startEthernet() //
/////////////////////////////
void startEthernet()
{
client.stop();
Serial.println("--- 2. SETUP: startethernet(): Conectando red Ethernet ...");
delay(1000);
if (Ethernet.begin(mac) == 0) {
Serial.println("--- 2. SETUP: startethernet(): Fallo Configuracion Ethernet ---");
Serial.println("");
}
else{
Serial.print("--- 2. SETUP: startethernet(): Conexion DHCP, IP: ");
Serial.print(Ethernet.localIP());
Serial.println(" ---");
Serial.println();
}
}
/////////////////////////////
// FUNCION: HTTPpost() //
/////////////////////////////
void updateHTTPPOST(String POSTdata)
{
if (client.connect("XXXXXXX", 8086)) // Conexion a Servidor
{
Serial.println("--------------START POST-------------------------");
// Cabeceras (HTTP POST Headers)
client.print("POST /db/test_voltios/series?u=root&p=root HTTP/1.1\n");
Serial.print("POST /db/test_VAkW/series?u=root&p=root HTTP/1.1\n");
client.println("Host: XXXXXX");
Serial.println("Host: XXXXX");
client.print("User-Agent: Arduino/1.0\n");
Serial.print("User-Agent: Arduino/1.0\n");
client.print("Connection: Close\n");
Serial.print("Connection: Close\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
Serial.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
Serial.print("Content-Length: ");
client.print(POSTdata.length());
Serial.print(POSTdata.length());
client.print("\n\n"); // Se necesitan dos Line breaker para cerrar header
Serial.print("\n\n");
// Cuerpo del Mensaje (HTTP POST Body)
client.print(POSTdata);
Serial.print(POSTdata);
lastConnectionTime = millis();
// Chequeo sigo conectado -> POST con exito
if (client.connected())
{
Serial.println();
Serial.println("----------------FIN POST-------------------------");
Serial.println();
Serial.println();
failedCounter=0;
} else {
failedCounter++;
Serial.println("Conexion con Servidor perdida");
Serial.print("Conexion perdida Nº ");
Serial.println(String(failedCounter));
Serial.println();
}
}
else // No he sido capaz de conectar con el Servidor
{
failedCounter++;
Serial.println("No puedo Conectarme a Servidor");
Serial.print("Conexion perdida Num. ");
Serial.println(String(failedCounter));
Serial.println();
lastConnectionTime = millis();
}
}