How to send and parse JSON data through NRF24L01 sensor? - json

TRANSMITTER.ino (COM8 port)
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include<ArduinoJson.h>
RF24 radio(7, 8); // CE, CSN
const byte addresses[6] = {"00001"};
void setup() {
radio.begin();
radio.openWritingPipe(addresses);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
}
void loop() {
DynamicJsonBuffer jBuffer;
JsonObject& root = jBuffer.createObject();
root["North"] = "true";
root["South"] = "false";
root["East"] = "true";
root["West"] = "true";
radio.write(&root, sizeof(root));
delay(1000);
}
RECEIVER.ino (COM9 port)
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include<ArduinoJson.h>
RF24 radio(7, 8); // CE, CSN
const byte addresses[6] = {"00001"};
void setup() {
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(0, addresses);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
}
void loop() {
if ( radio.available()) {
unsigned char data[1024];
radio.read(&data, sizeof(data));
StaticJsonBuffer<1024> jsonBuffer;
JsonObject& toor = jsonBuffer.parseObject(data);
String n = toor["North"];
String s = toor["South"];
String e = toor["East"];
String w = toor["West"];
Serial.println(n);
Serial.println(s);
Serial.println(e);
Serial.println(w);
delay(1000);
}
}
I am trying to transmit a JSON data over NRF24L01, and printing it to the serial monitor, but i dont see any output in my serial monitor(COM9 serial monitor). what is the mistake am i doing here?
I am using arduino JSON 5.13.5 version

Related

Blynk Button is not getting actuated

I, a complete beginner, was doing a project with ESP8266 where I interfaced with a relay and two sensors. The sensors are working fine but the relay is not getting actuated by the Blynk button when I press it. Below is the code where I got proper output for the sensors but not the relay.
I get all the values of sensors in the Blynk app but not the relay actuation where I connected it to a motor and in the D2 pin. Thanks in advance.:)
#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "my_template"
#define BLYNK_DEVICE_NAME "my_device name"
#define BLYNK_AUTH_TOKEN "Auth token"
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>
#define BLYNK_PRINT Serial
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS D2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
char auth[] = "Authtoken";
char ssid[] = "my_ssid";
char pass[] = "my_pass";
#define sensorPin D3
int sensorState = 0;
int lastState = 0;
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;
void sendSensor()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
Blynk.virtualWrite(V5, h); //hum
Blynk.virtualWrite(V6, t); //temp
}
void setup()
{
pinMode(D2,OUTPUT); //these two lines are the one which use for actuating the relay
digitalWrite(D2, HIGH);//
Blynk.begin(auth, ssid, pass);
pinMode(sensorPin, INPUT);
dht.begin();
timer.setInterval(1000L, sendSensor);
Blynk.begin(auth, ssid, pass);
sensors.begin();
}
int sensor = 0;
void sendTemps()
{
sensor = analogRead(A0);
sensors.requestTemperatures();
float temp = sensors.getTempCByIndex(0);
Blynk.virtualWrite(V1, temp);
Blynk.virtualWrite(V2, sensor);
delay(1000);
}
void loop()
{
Blynk.run();
timer.run();
sendTemps();
sensorState = digitalRead(sensorPin);
if (sensorState == 1 && lastState == 0) {
lastState = 1;
delay(1000);
}
else if (sensorState == 1 && lastState == 1) {
delay(1000);
}
else {
lastState = 0;
delay(1000);
}
delay(100);
}

Arduino UART ESP01 , json parse 4with 433 MHZ receiver and transmitter

I am using 2 Arduino, 1 Esp01,433 MHz 1 receiver and 1 433 MHz transmitter. The transmtiter sending uint_8 "85648217". When i write below the code.I can receive the messages and i can get response from api.
#include <ArduinoJson.h>
#include <RH_ASK.h>
#include <SPI.h>
#define RX 0
#define TX 1
using namespace std;
unsigned char rxBuf[512];
RH_ASK rf_driver;
void setup() {
rf_driver.init();
Serial.begin(9600);
}
void loop() {
{
uint8_t buf[8];
uint8_t buflen = sizeof(buf);
if (rf_driver.recv(buf, &buflen))
{
Serial.println("https://example.com/example/example/"+(String((char*)buf))+";headers\n");
//(String((char*)buf) is number from transmitter
String message = Serial.readString();
const size_t capacity = JSON_OBJECT_SIZE(1) + 20;
DynamicJsonDocument doc(capacity);
// DeserializationError error = deserializeJson(doc, message);
//if (error) {
// Serial.print(F("deserializeJson() failed: "));
//Serial.println(error.f_str());
// return;
// }
Serial.println(doc["attribute"].as<const char*>());
Serial.println(message);
}
}
}
When i write code like this.I can't receive message.I am receving "07413943⸮" or "07413943⸮ " .I don't know why is this happening.Does anyone know how can i fix this?
#include <ArduinoJson.h>
#include <RH_ASK.h>
#include <SPI.h>
#define RX 0
#define TX 1
using namespace std;
unsigned char rxBuf[512];
RH_ASK rf_driver;
void setup() {
rf_driver.init();
Serial.begin(9600);
}
void loop() {
{
uint8_t buf[8];
uint8_t buflen = sizeof(buf);
if (rf_driver.recv(buf, &buflen))
{
Serial.println("https://example.com/example/example/"+(String((char*)buf))+";headers\n");
//(String((char*)buf) is number from transmitter
String message = Serial.readString();
const size_t capacity = JSON_OBJECT_SIZE(1) + 20;
DynamicJsonDocument doc(capacity);
DeserializationError error = deserializeJson(doc, message);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
Serial.println(doc["attribute"].as<const char*>());
Serial.println(message);
}
}
}
I found the solution.It seems like i need to convert string this (String((char*)buf)) but not like this.Here is how i solved.
uint8_t buflen = sizeof(buf)
if (rf_driver.recv(buf, &buflen))
{
rf_driver.printBuffer("Got:",buf,buflen);
String rcv;
for (int i=0; i<buflen;i++){
rcv+=(char)buf[i];
}
Serial.print("example.com/example"+rcv+";header");
String input = Serial.readString();
StaticJsonDocument<32> doc;
DeserializationError error = deserializeJson(doc,input);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
float attribute= doc["attribute"]; // 428.5
Serial.println(float(attribute));
Serial.println(input);

Setting variables from json into a struct have weird results

I have something in my code output I don't understand.
My guess is the issue is due to [me of course] ... the usage of both "struct"+"arduinoJson" to store configuration values.
I have made this simple code that only connect to Wifi;
either using hardcoded settings
loadConfigHarcoded(); // Serial print of values: OK, and "WiFi Success!"
either using deserializeJson
loadConfigFromJson(); // Serial print of values: OK, but "WiFi Connect Failed!"
Is there anything I missed ?
The full code :
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
const char* ssid = "my_ssid";
const char* password = "my_password";
String confJson = "{\"ssid\": \""+String(ssid)+"\", \"password\": \""+String(password)+"\"}";
struct sConfig {
const char* ssid;
const char* password;
const char* host;
};
sConfig config;
void loadConfigHarcoded() {
config.ssid = ssid;
config.password = password;
}
void loadConfigFromJson() {
DynamicJsonDocument docConfig(1024);
DeserializationError err = deserializeJson(docConfig, confJson);
if (!err) {
config.ssid = docConfig["ssid"];
config.password = docConfig["password"];
}
}
void setup() {
Serial.begin(115200);
Serial.println();
loadConfigHarcoded(); // Serial print of values are OK ; and "WiFi Success!"
//loadConfigFromJson(); // Serial print of values are OK ; but "WiFi Connect Failed!"
Serial.print("SSID=");
Serial.println(config.ssid);
Serial.print("PSWD=");
Serial.println(config.password);
WiFi.mode(WIFI_STA);
WiFi.begin(config.ssid, config.password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Connect Failed!");
} else {
Serial.println("WiFi Success!");
}
}
void loop() {
}

Why does the serial monitor just show an endless loop of the "dot" and not the other serial prints?

The code should transfer an JSON object and the print "hello" in the void loop, but it just repeat the "dot" from the void setup. What did i miss?
I tried different serial prints in the main loop but none of them is actually transferred. Maybe there is an infinite loop in the void setup?
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <vector>
const char* apSsid = "ap-ssid";
const char* apPassword = "ap-password";
const char* clientSsid = "client-ssid";
const char* clientPassword = "client-password";
WiFiEventHandler probeRequestPrintHandler;
String macToString(const unsigned char* mac) {
char buf[20];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
std::vector<WiFiEventSoftAPModeProbeRequestReceived> myList;
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt) {
myList.push_back(evt);
}
void setup() {
Serial.begin(115200);
Serial.print("Hello!");
// Don't save WiFi configuration in flash - optional
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(apSsid, apPassword);
WiFi.begin(clientSsid, clientPassword);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.print("");
probeRequestPrintHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
}
void loop() {
delay(3000);
String json = "";
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& probes = root.createNestedArray("probes");
for(WiFiEventSoftAPModeProbeRequestReceived w : myList){
JsonObject& probe = probes.createNestedObject();
probe["address"] = macToString(w.mac);
probe["rssi"] = w.rssi;
}
myList.clear();
root.printTo(json);
Serial.print(json);
Serial.print("hallo");
}
It should transfer the dot, a json object and the word "hallo"
This is because the ESP8266 can't find a WiFi access point with SSID client-ssid and password client-password.
Unless it gets connected to the said access point it will print . on the screen.
You can change the access point parameters to one that visible in the range of ESP8266 alternatively you can change the access point SSID and password to one in the code.
You can use the WiFi manager to avoid hard-code SSID names and password.

JSON parsing failing in Arduino and ESP8266

I have to extract an Ajax response from [this REST API][1]. Please provide a code snippet for this so that I can proceed I am stuck here.
I need to read JSON data from http://tutor4study.com/forms/ajaxDeviceValue and then I have to parse it.
enter code here
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
const char* ssid = "ssid";
const char* password = "password";
const char* host = "tutor4study.com";
const int httpsPort = 80;
WiFiClient client;
WiFiClient readClient;
String sensorValue1 = "5555";
String sensorValue2 = "9999";
String readUrl = "";
char readLine;
String readResponse ="";
String readJsonResponse ="";
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("connecting to ");
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
// yield();
}
StaticJsonBuffer<200> jsonBuffer;
void readConnect(){
if(!readClient.connect(host,httpsPort)){
Serial.println("connection failed for readCLient");
ESP.reset();
return;
}
readUrl = "/forms/ajaxDeviceValue";
Serial.print("requesting URL: ");
Serial.println(readUrl);
readClient.print(String("GET ")+readUrl+" HTTP/1.1\r\n"+
"Host: "+host+"\r\n"+
"Connection: close\r\n\r\n");
while(readClient.connected()){
readLine = readClient.read();
Serial.print(readLine);
readResponse += readLine;
}
JsonObject& root = jsonBuffer.parseObject(readResponse);
if (!root.success()) {
Serial.println("parseObject() failed");
return;
}
}
void loop() {
readConnect();
}
Aboveis my code. Please have a look at the code and let me know how to read a JSON response for url /ajaxDeviceValue and parse it in a string.
I found the solution after a lot of hit and trial I was reading WiFiClient .It was giving me few garbage value with Json response.Because of garbage value ArduinoJson library was not able to parse it. I used HttpClient to read the response andit is returning clear Json which ArduinoJson is able to parse and now code is working fine.