I get the fundamentals of global variables, functions, and strings, however I’m still missing something in my code.
I’ve declared the global string (wthr_int, which is NULL) and the variable is set in the getForecast() function. Currently that variable only works in the function, as it doesn’t get passed as a global variable. I also need to pass that variable into displayForecast() to be used to light up an LED.
And that’s where I’m stuck. I need the variable in one function to be made into a global variable to be used in another function. Your assistance would be greatly appreciated.
#include "HttpClient.h"
#include "application.h"
unsigned int nextTime = 0; // Next time to contact the server
HttpClient http;
// Headers currently need to be set at init, useful for API keys etc.
http_header_t headers[] = {
// { "Content-Type", "text/plain" },
{ "Accept" , "application/json" },
{ "Accept" , "*/*"},
{ NULL, NULL } // NOTE: Always terminate headers will NULL
};
int bluePin = D0;
int redPin = D1;
int greenPin = D2;
String wthr_int;
http_request_t request;
http_response_t response;
void setup() {
Serial.begin(9600);
pinMode(bluePin, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
// Initialize functions:
getForecast();
displayForecast();
}
void loop() {
getForecast();
displayForecast();
}
void getForecast() {
if (nextTime > millis()) {
return;
}
// Contact server
Serial.println();
request.hostname = "wthr.im";
request.port = 80;
request.path = "/berkeley.php";
// Get request
http.get(request, response, headers);
Serial.println(response.body);
// Token response into variable
String str = String(response.body);
char strBuffer[125] = "";
str.toCharArray(strBuffer, 125);
char wthr_int = atoi(strtok(strBuffer, "\"~"));
nextTime = millis() + 3600000; // 1hr = 3600000 / 6hrs = 21600000 / 24hrs = 86400000
}
void displayForecast() {
if (wthr_int == "1") { // colder temperature - blue LED
digitalWrite(bluePin, HIGH);
}
if (wthr_int == "2") { // warmer temperature - red LED
digitalWrite(redPin, HIGH);
}
if (wthr_int == "3") { // same temperature - white LED
analogWrite(redPin, 254);
analogWrite(bluePin, 150);
analogWrite(greenPin, 120);
}
if (wthr_int == "") { // NULL value - purple LED
analogWrite(redPin, 254);
analogWrite(bluePin, 150);
analogWrite(greenPin, 0);
}
}