i'm doing with JSON string, i want to storage my sensor data to JSON string then i will send it to Node red or firebase (which i heard is it need JSON format, not sure about that). My actually project is receive lots of sensors value like
["ID": 01, "temp": value_temp_1, "humid": value_humid_1] , ["ID": 02, "temp": value_temp_2, "humid": value_humid_2],...
#include <DHT.h>
#include <DHT_U.h>
#include <ArduinoJson.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
int humidity, temperature;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Begin");
dht.begin();
}
void loop()
{
delay(2000);
humidity = dht.readHumidity();
temperature = dht.readTemperature();
StaticJsonDocument<50> doc;
JsonObject object = doc.to<JsonObject>();
object["ID"] = "Node01";
object["humidity"] = humidity;
object["temperature"] = temperature;
serializeJson(doc, Serial);
Serial.println("");
}
my question is do i have to use those code in loop()? everytime it will create a Json<50> so it will be full later or it only create 1 time? i have little confuse about that or could anyone give me some advices to optimize my code.
thank you
You don't need to create your object each time. Just define it as a global variable and change its values on your loop. Something like this:
#include <DHT.h>
#include <DHT_U.h>
#include <ArduinoJson.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
int humidity, temperature;
StaticJsonDocument<50> doc;
JsonObject object;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Begin");
dht.begin();
object = doc.to<JsonObject>();
}
void loop()
{
humidity = dht.readHumidity();
temperature = dht.readTemperature();
object["ID"] = "Node01";
object["humidity"] = humidity;
object["temperature"] = temperature;
serializeJson(doc, Serial);
Serial.println("");
delay(2000);
}
Related
I'm working on a script that will play multiple.wav encoded files in the ESP8266 using the ESP8266Audio library. I need to play multiple audio streams with different time stamps; that's why I am asking for it. Please do note that the hardware is ESP32-8266 and TIP 120 transistor.
#include <Arduino.h>
#include "AudioFileSourcePROGMEM.h"
#include "AudioGeneratorWAV.h"
#include "AudioOutputI2SNoDAC.h"
#include <ESP8266WiFi.h>
#include <SPI.h>
#include <SD.h>
// VIOLA sample taken from https://ccrma.stanford.edu/~jos/pasp/Sound_Examples.html
#include "viola.h"
#include "viola02.h"
AudioGeneratorWAV *wav;
AudioFileSourcePROGMEM *file;
AudioOutputI2SNoDAC *out;
void setup()
{
Serial.begin(115200);
delay(1000);
Serial.printf("WAV start\n");
audioLogger = &Serial;
out = new AudioOutputI2SNoDAC();
// out02 = new AudioOutputI2SNoDAC();
// out -> SetGain(0.08);
}
void Play(const void *data, uint32_t len) {
file = new AudioFileSourcePROGMEM( data, len );
wav = new AudioGeneratorWAV();
wav->begin(file, out);
delay(3000);
while (true) {
if (wav->isRunning()) {
if (!wav->loop()) wav->stop();
} else {
Serial.printf("WAV done\n");
delay(1000);
break;
}
}
}
void loop()
{
Play(viola,sizeof(viola));
Play(viola02,sizeof(viola02));
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/yIKml.png
I have this program that prins to an LCD with watchdog interrupt. But the problem is that i need to have 2 decimals after seconds.
the code is as follows:
#include <Arduino.h>
#include "DFRobot_RGBLCD.h"
#include <stm32l4xx_hal_iwdg.h>
#include <Wire.h>
#define I2C2_SCL PB10
#define I2C2_SDA PB11
DFRobot_RGBLCD lcd(16,2);
TwoWire dev_i2c (I2C2_SDA, I2C2_SCL);
IWDG_HandleTypeDef watchdog;
void Start();
void Pause();
int paused = 0;
int milli = 0;
volatile byte state = HIGH;
void setup() {
pinMode(A2, INPUT_PULLUP);
pinMode(A3, INPUT_PULLUP);
lcd.init();
Serial.begin(9600);
dev_i2c.begin();
attachInterrupt(A2, Start, FALLING);
attachInterrupt(A3, Pause,RISING);
watchdog.Instance = IWDG;
watchdog.Init.Prescaler = IWDG_PRESCALER_256;
watchdog.Init.Reload = 1220;
watchdog.Init.Window = 0x0FFF;
HAL_IWDG_Init(&watchdog);
delay(1);
}
void loop() {
if(state){
delay(250);
lcd.setCursor(0, 0);
lcd.print("Sekunder: ");
lcd.print(millis()/1000-pause);
delay(100);
}
else{
delay(1000);
paused++;
HAL_IWDG_Refresh(&watchdog);
}
}
void Start(){
state = HIGH;
HAL_IWDG_Refresh(&watchdog);
delay(10);
}
void Pause(){
state = !state;
delay(10);
}
I have tried to put the -pause outside the lcd.print, but that didnt work. i've also tried this codeline: ```
lcd.print(millis()/1000.0, 2-paused);
But it seems like it takes -paused from the number 2. Do anyone have suggestion to how i can make it work so i get the 2 decimals?
String seconds = String(millis() / 1000.0, 2);
lcd.print(seconds);
i read a few example and the value is string or number like this
json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
For example i have 2 values:
pack0.humidity = dht.readHumidity();
pack0.temperature = dht.readTemperature();
Can i read those temp and humid and add it to json in loop()
like this
json[] =
"{\"Temperature\": /*temp here*/,
\"Humidity\":/*humid here*/}";
Could anyone give me example for my project. thanks a lot.
My current code for rf24
struct package0
{
float temperature = 0;
float humidity = 0;
int soil = 0;
};
typedef struct package0 Package0;
Package0 pack0;
void loop()
{
delay(2000);
pack0.humidity = dht.readHumidity();
pack0.temperature = dht.readTemperature();
pack0.soil = map(analogRead(SOILPIN), 0, 4096, 100, 0);//convert to percentage
if (isnan(pack0.humidity) || isnan(pack0.temperature))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
RF24NetworkHeader header(master00);
bool ok = network.write(header, &pack0, sizeof(pack0));
Consider using ArduinoJson, which will do the JSON encoding for you. The advantage of this library is that it makes it easy to modify your data schema at a later time.
Or you can do it yourself by simply using snprintf:
const int BUFFER_SIZE = 48; // Choose a suitable number here
char json[BUFFER_SIZE];
snprintf(json, BUFFER_SIZE, "{\"Temperature\":%f,\"Humidity\":%f}", pack0.humidity, pack0.temperature);
json will then contain your JSON data. Using snprintf ensures that the write will not overflow.
code:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
byte flags = 0b00011110;
byte bpm;
byte rr;
byte heart[8] = { 0b00011110, 60, 60, 60, 60 , 60, 60, 60};
byte hrmPos[1] = {2};
bool _BLEClientConnected = false;
#define heartRateService BLEUUID((uint16_t)0x180D)
BLECharacteristic heartRateMeasurementCharacteristics(BLEUUID((uint16_t)0x2A37), BLECharacteristic::PROPERTY_NOTIFY);
BLECharacteristic sensorPositionCharacteristic(BLEUUID((uint16_t)0x2A38), BLECharacteristic::PROPERTY_READ);
BLEDescriptor heartRateDescriptor(BLEUUID((uint16_t)0x2901));
BLEDescriptor sensorPositionDescriptor(BLEUUID((uint16_t)0x2901));
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
_BLEClientConnected = true;
};
void onDisconnect(BLEServer* pServer) {
_BLEClientConnected = false;
}
};
void InitBLE() {
BLEDevice::init("Sensor X");
// Create the BLE Server
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pHeart = pServer->createService(heartRateService);
pHeart->addCharacteristic(&heartRateMeasurementCharacteristics);
heartRateMeasurementCharacteristics.addDescriptor(&heartRateDescriptor);
heartRateMeasurementCharacteristics.addDescriptor(new BLE2902());
pHeart->addCharacteristic(&sensorPositionCharacteristic);
sensorPositionCharacteristic.addDescriptor(&sensorPositionDescriptor);
pServer->getAdvertising()->addServiceUUID(heartRateService);
pHeart->start();
// Start advertising
pServer->getAdvertising()->start();
}
void setup() {
Serial.begin(115200);
Serial.println("Start");
InitBLE();
bpm = 1;
rr = 800;
}
void loop() {
// put your main code here, to run repeatedly:
heart[1] = (byte)bpm;
int energyUsed = 3000;
heart[3] = energyUsed / 256;
heart[6] = (byte)bpm;
heart[2] = energyUsed - (heart[2] * 256);
Serial.println(bpm);
Serial.println(rr);
heartRateMeasurementCharacteristics.setValue(heart, 8);
heartRateMeasurementCharacteristics.notify();
sensorPositionCharacteristic.setValue(hrmPos, 1);
rr++;
bpm++;
delay(2000);
}
I have the above code - and I have been looking at this here but I can't figure out how do I pass the RR data over BLE. I set the flags according to the BLE spec shown here. But whenever I use an app to see the data "HRV Logger", it says that I am not transmitted RR data. I thought all I had to do was pass heart[6] data and that would show up as RR. I have dummy information being passed since I'm not connected to any sensors. Help would be helpful, determining how to pass the RR data across, thanks! (for future reference I am using the Sparkfun ESP32, but this shouldn't affect solving the issue since it has to do with protocols)
I've collected some string information in processing and I am trying to send it to Arduino. I am getting processing to send the information, however, my output in arduino is weird. I get numbers like "77789...". I am not sure What I am doing wrong. All I need to do is, basically get a string from processing and send it to arduino to display it on a LCD screen.
Any help on this would be appreciated.
Here is my processing code:
import processing.serial.*;
Serial myPort;
XML MSFTxml; // loading Query
XML MSFT; // results of the query
XML row; // first row in the query
XML symbol; // Name of the stock
String symbolTxt;
String val;
void setup() {
size(200,200);
myPort = new Serial(this,"COM3", 9600);
}
void draw() {
updateXMLCall();
delay(10000);
}
void updateXMLCall () {
MSFTxml = loadXML("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%27http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3DMSFT%26f%3Dsl1d1t1c1ohgv%26e%3D.csv%27%20and%20columns%3D%27symbol%2Cprice%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2%27&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
MSFT = MSFTxml.getChild("results"); //Getting the first tag "results" in the query MSFT
row= MSFT.getChild("row"); //first child tag "row"
symbol = row.getChild("symbol"); //name of the stock
symbolTxt = symbol.getContent().toString(); //converting the name of the stock into a string
myPort.write(symbolTxt);
println(symbolTxt);
}
Here is my arduino Code:
#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
const int colorR = 50;
const int colorG = 0;
const int colorB = 0;
void setup()
{
Serial.begin(9600);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.setRGB(colorR, colorG, colorB);
// Print a message to the LCD.
lcd.setCursor(0, 1);
}
void loop()
{
String content = "";
if (Serial.available()) {
while (Serial.available()) {
content += Serial.read();
lcd.print(content);
Serial.print(content);
lcd.setCursor(0, 1);
}
}
delay(100);
}
The problem is the use of += in C += doesn't concat strings.
You need to concatenate the char get from Serial.read() like here for example:
Convert serial.read() into a useable string using Arduino?