JSON parsing failing in Arduino and ESP8266 - json

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.

Related

How can I fix my serial communication from Arduio Uno to ESP8266?

I'm testing the Serial Communication with my Arduino and NodeMCU, and how I can send one data to another. Here is the Code.
For the Arduino Uno
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); //RX, TX
float i = 10;
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
}
void loop() {
Serial.print("Number ");
Serial.print(i);
Serial.println("");
mySerial.write(i);
delay(1000);
}
And here is for my ESP8266 NodeMCU
#include <SoftwareSerial.h>
SoftwareSerial myNode(D1, D2); //RX, TX
float git;
void setup() {
Serial.begin(115200);
myNode.begin(9600);
}
void loop() {
git = Serial.read();
Serial.print("The Number is ");
Serial.print(git);
Serial.println("");
delay(1000);
}
The result should be that in the Serial Monitor it should say "The Number is 10". But instead it says -1.00 enter image description here
Am I doing something wrong?
Ah, I finally figured it out. Apparently I need to initialize the NodeMCU Pin's as so:
#include <SoftwareSerial.h>
static const uint8_t D1 = 5;
static const uint8_t D2 = 4;
SoftwareSerial myNode(D1, D2); //RX, TX
float git;
void setup() {
Serial.begin(115200);
myNode.begin(9600);
}
void loop() {
git = Serial.read();
Serial.print("The Number is ");
Serial.print(git);
Serial.println("");
delay(1000);
}
Try
git = myNode.read();
instead of
git = Serial.read();
And check myNode.available() before reading

ESP8266 restart after the second request to the server (Exception 9)

I am new to this community, and I look forward to your help with this issue.
I have communication between two ESP8266 modules. One of these as a Server/Access-Point and the other as a Client. The configuration and connection between these two modules are satisfactory, and part of the communication as well. However, after the Client makes the first request (Begin and GET), and the server responds, for the second Client/Server request, the Client restarts with the next message or exception.
Exception (9):
epc1=0x40207204 epc2=0x00000000 epc3=0x00000000 excvaddr=0x0036006a depc=0x00000000
That is, the first request to the server's root is answered, but the second to /data causes the mentioned restart on the Client.
After reviewing the stack exception decoder, I find that the code (9) means 9: LoadStoreAlignmentCause Load or store to an unaligned address.
Then, I've tried different solutions for this issue
erase all flash content
http.end()
change the macro delay() for delayMicroseconds()
and a few more
But nothing works yet.
Please, help me with this issue. The codes of the server and Client are:
The client:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define LED_PIN 2
const char* ssid = "Mi_Servidor";
const char* password = "";
const char* host = "http://192.168.4.1";
int counter=1, httpCode=0;
HTTPClient http;
void peticion (int httpCode){
String mensaje;
if(httpCode == 200) {
mensaje = http.getString();
Serial.println(mensaje);
}
else {
Serial.print("[HTTP] GET... failed, no connection or no HTTP server\n");
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
delay(10);
Serial.print("Conectando a ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi conectada");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
counter++;
int modulo=counter%2;
if(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
else{
Serial.print("[HTTP] begin...\n");
if(modulo==0) http.begin("192.168.4.1", 80); //HTTp
else http.begin("192.168.4.1", 80, "/data"); //HTTp
httpCode = http.GET();
Serial.print("httpCode: "); //JJ
Serial.println(httpCode); //JJ
peticion(httpCode);
delay(20);
}
Serial.println("End Loop!");
}
And the server:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#define LED_PIN 2
void handle_datos();
const char WiFiClave[] = ""; //Sin clave
const char AP_Nombre[] = "Mi_Servidor";
int val;
String MiMessage = "Message to transmit:\n\r";
ESP8266WebServer server(80);
void handle_data() {
server.send(200, "text/plain", MiMessage);
delay(1000);
}
void handle_root() {
server.send(200, "text/plain", "Mi_root");
delay(1000);
}
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_Nombre, WiFiClave);
server.on("/data", handle_data);
server.on("/", handle_root);
server.begin();
// for (int i = 0; i <= 3999; i++) {
// MiMessage.concat(String(i));
// MiMessage.concat(";");
// }
Serial.println();
Serial.println(MiMessage);
Serial.println("\nServidor ready... ");
}
void loop() {
server.handleClient();
delay(100);
}
Thanks in advance

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() {
}

How to send and parse JSON data through NRF24L01 sensor?

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

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.