Hi All,
I have been working on a script on my WEMOS D1 mini that gets data via JSON and then performs a calculation on it. For purposes of this example, I have supplied some code which works fine until I try and do a calculation when the String returned from JSON fails as its a string and not a float(It does not have to be a float its just what I thought it was supposed to be).
I have done a search and tried to find some good example scripts to see how it's done but I've not been very successful.
The addition of lines 6, 79-81 causes the script to fail.
79: error: no match for 'operator-' (operand types are 'String' and 'int')
value = result - 100;
^
exit status 1
no match for 'operator-' (operand types are 'String' and 'int')
I also tried changing the lines from String to float or unsigned long without much success.
//Libraries
#include <ESP8266WiFi.h> //Provides WiFI
#include <ArduinoJson.h> //Handles the returned JSON data
//Setup Calc Var
String value;
//WiFi settings
const char* ssid = "VMxxxx";
const char* password = "xxxxx";
//URL Domain
const char* host = "coinmarketcap.northpole.ro"; //Test JSON data
//We now create the full URL for the request
String url = String("/api/btc.json");
void setup() {
Serial.begin(115200); // Serial Setup
WiFi.begin(ssid, password); // Do wifi stuff
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println(WiFi.localIP()); //Show WiFi connection
delay(100);
//Display URL on serial
Serial.print("URL: ");
Serial.print(host);
Serial.println(url);
}
void jsonfunc(){
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
//Serial.println("Got Data...");
delay(1000);//Delay added as without data request fails.
// Read all the lines of the reply from server.
String answer;
while(client.available()){
String line = client.readStringUntil('\r');
answer += line;
}
client.stop();
// Convert to JSON
String jsonAnswer;
int jsonIndex;
for (int i = 0; i < answer.length(); i++) {
if (answer[i] == '{') {
jsonIndex = i;
break;
}
}
// Get JSON data
jsonAnswer = answer.substring(jsonIndex);
jsonAnswer.trim();
//Get current currency price data
int rateIndex = jsonAnswer.indexOf("price");
String result = jsonAnswer.substring(rateIndex + 8, rateIndex + 18);
//Print Results to the serial
Serial.print("Returns = ");
Serial.println(result);
//Calulations on Result
value = result - 100;
Serial.print("Calc Returns = ");
Serial.println(value);
}
void loop() {
jsonfunc(); //Call the jsonfunc Function :)
delay(10000);//Wait to limit number or web requests
}
If anyone can show me how to get around this or point me at an example that does something similar it would be a great help.
Many thanks