Good day.
Fisrt, i know that there are other thread very similar. i based my projec in that. here is the link
In that thread someone posted code example working.
The code consist about send random values generated with the photon, then send them to localhost phpmyadmin using node.js. Basically it give the way to communicate photon to localhost.
The problem that i have is that i want to send data from a sensor, the data has decimals so im using double.
But i cant make it work. i try editing many parts of the code. Sometimes i get valor cant be null, other times node.js detect the first value but it cant store in the database or i get problems with types of data.
i know that can be a simple detail, but i cant find it.
i would appreciate a lot any help and advice
the codes that im using are (if you dont want to download anything):
Note, there are the codes that im using. they have been modified to the originals, the originals can be found in the code example’s link.
photon:
#include "Particle.h"
SYSTEM_THREAD(ENABLED);
const char *EVENT_NAME = "mysqlSample1";
const unsigned long EVENT_PERIOD_MS = 10000;
unsigned long lastPublish = 0;
int temp = A2;
int reading = 0;
double mvolts = 0.0;
double tempc = 0.0;
void setup() {
Serial.begin(9600);
Particle.variable("analog", &reading, INT);
Particle.variable("mvolts", &mvolts, DOUBLE);
Particle.variable("tempc", &tempc, DOUBLE);
}
void loop() {
if (millis() - lastPublish >= EVENT_PERIOD_MS) {
lastPublish = millis();
if (Particle.connected()) {
char data[256];
// Just a random value for testing. You might use a sensor value here instead
// int a = tempc;
reading = analogRead(A2);
mvolts = (reading * 3300.0)/4095.0;
tempc = mvolts/10.0;
double a = tempc;
// Prepare a buffer with JSON data
sprintf(data, "%f", a);
//snprintf(data, sizeof(data), "{\"a\":%d}", a);
// Send to the cloud
Particle.publish(EVENT_NAME, data);
Serial.println(data);
}
}
}
node.js
var config = require('./config.js');
// Particle cloud API
var Particle = require('particle-api-js');
var particle = new Particle();
// https://github.com/mysqljs/mysql
var mysql = require('mysql');
// Make database connection
console.log("starting database connection");
var connection = mysql.createConnection(config.mysql);
connection.connect();
// Make cloud connection
console.log("starting event stream listener");
particle.getEventStream({ deviceId: 'mine', auth: config.authToken }).then(
function(stream) {
stream.on('event', cloudEventHandler);
},
function(err) {
console.log("error starting event listener", err);
process.exit(1);
});
cloudEventHandler = function(data) {
// console.log("Event", data);
if (data.name == 'mysqlSample1') {
storeData(JSON.parse(data.data));
}
}
function storeData(data) {
console.log("storeData", data);
connection.query('INSERT INTO test2 SET ?', {'valor': data.a}, function(err, result) {
if (err) throw err;
console.log("id=" + result.insertId);
});
}