Using JSON open weather data to control RGB led color

From a relative newbie here, I’m trying to use temperature data from Open Weather to determine color of an RGB led with a NodeMCU ESP32); unfortunately, when trying to convert temperature data to an integer value to use in subsequent code to define RGB color, I keep getting this compiling error: 'tempDegC' was not declared in this scope

I'm very much a newbie, so perhaps I'm forgetting something obvious here. I did declare the tempDegC int variable in the setup. I append below my code (mostly from ESP32 HTTP GET with Arduino IDE (OpenWeatherMap.org and ThingSpeak) | Random Nerd Tutorials), and apologize for its messiness/the way I might have butchered the original excellent code. . .and the likely very basic nature of my question. Thank you in advance!

Code:

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>

#define PIN_RED    23 // GIOP23
#define PIN_GREEN  22 // GIOP22
#define PIN_BLUE   21 // GIOP21

const char* ssid = "hidden";
const char* password = "hidden";

// Your Domain name with URL path or IP address with path
String openWeatherMapApiKey = "hidden";
// Example:
//String openWeatherMapApiKey = " ";

// Replace with your country code and city
String city = "Phoenix";
String countryCode = "US";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;

String jsonBuffer;

void setup() {
  int tempDegC;
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  
 
  Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");

  pinMode(PIN_RED,   OUTPUT);
  pinMode(PIN_GREEN, OUTPUT);
  pinMode(PIN_BLUE,  OUTPUT);
}

void loop() {
   analogWrite(PIN_RED,   120);
   analogWrite(PIN_GREEN, 60);
   analogWrite(PIN_BLUE,  60);
  // Send an HTTP GET request
  if ((millis() - lastTime) > timerDelay) {
    // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;
      
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      JSONVar myObject = JSON.parse(jsonBuffer);
  
      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
    
      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      Serial.println(myObject["main"]["temp"]);
      Serial.print("Pressure: ");
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);      
      tempDegC = int(myObject["main"]["temp"]);  
      
                }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }

  
  if (tempeDegC) > 273   {
   analogWrite(PIN_RED,   20);
   analogWrite(PIN_GREEN, 250);
   analogWrite(PIN_BLUE,  0);
  }

  
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "{}"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

and here are the compiler error messages:

C:\Users\Desktop\Arduino \open_weather_api_test_if_then_sketch\open_weather_api_test_if_then_sketch.ino: In function 'void loop()':
open_weather_api_test_if_then_sketch:95:7: error: 'tempDegC' was not declared in this scope
       tempDegC = int(myObject["main"]["temp"]);
       ^~~~~~~~
C:\Users\Desktop\Arduino\open_weather_api_test_if_then_sketch\open_weather_api_test_if_then_sketch.ino:95:7: note: suggested alternative: 'tempnam'
       tempDegC = int(myObject["main"]["temp"]);
       ^~~~~~~~
       tempnam

Multiple libraries were found for "WiFi.h"
 Used: C:\Users\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.4\libraries\WiFi
 Not used: C:\Program Files (x86)\Arduino\libraries\WiFi
exit status 1
'tempDegC' was not declared in this scope

The scope of a variable in C extends only to the end of the block where the variable is declared. In general, a block is a piece of code delimited by curly braces.
You declared it in the setup(), but you are trying to use it in the loop() - this is wrong.
Move your variable declaration to the beginning of loop() or to the global scope

That did the trick -- no more compiler errors! Thanks so much!

Now, though, the code compiles and uploads, downloads the data (JSON data visible in the serial monitor), but the color of the RGB LED does not change (stays at the greenish color that I set towards the start of the loop). My intention is to have the LED start greenish, then go to red if tempDegC is above 273 or go to blue if below 273.

I'm wondering if it is because the JSON data returns a temperature in decimal form (two decimal places), but I've declared tempDegC as an int variable? Do I need to declare tempDegC as a float variable instead? If so, how do I do so? Simply changing the int to float in the code causes compiling errors.

I append the updated code here:

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>

#define PIN_RED    23 // GIOP23
#define PIN_GREEN  22 // GIOP22
#define PIN_BLUE   21 // GIOP21

const char* ssid = "hidden";
const char* password = "hidden";

// Your Domain name with URL path or IP address with path
String openWeatherMapApiKey = "hidden";
// Example:
//String openWeatherMapApiKey = "hidden";

// Replace with your country code and city
String city = "Phoenix";
String countryCode = "US";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;

String jsonBuffer;

void setup() {
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  
 
  Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");

  pinMode(PIN_RED,   OUTPUT);
  pinMode(PIN_GREEN, OUTPUT);
  pinMode(PIN_BLUE,  OUTPUT);
}

void loop() {
   int tempDegC;
   analogWrite(PIN_RED,   0);
   analogWrite(PIN_GREEN, 255);
   analogWrite(PIN_BLUE,  30);
  // Send an HTTP GET request
  if ((millis() - lastTime) > timerDelay) {
    // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;
      
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      JSONVar myObject = JSON.parse(jsonBuffer);
  
      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
    
      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      Serial.println(myObject["main"]["temp"]);
      Serial.print("Pressure: ");
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);      
      tempDegC = int(myObject["main"]["temp"]); 
             
                }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }

   if (tempDegC > 273)   {
   analogWrite(PIN_RED,   255);
   analogWrite(PIN_GREEN, 0);
   analogWrite(PIN_BLUE,  0); 

  }

  else {
    analogWrite(PIN_RED,   0);
    analogWrite(PIN_GREEN, 0);
    analogWrite(PIN_BLUE,  255); 
  }

  
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "{}"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

Did you try printing out 'tempDegC' to see the value?

I think you want:
tempDegC = myObject["main"]["temp"].asInt();

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.