Skip to main content
Arduino

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Global or local

I'm new to Arduino and embedded, but understand that it is often better to use global instead of local variables (such as here or here).

I have this simple code (from here):

//Libraries
#include <DHT.h>;
//Constants
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
//Variables
float hum; //Stores humidity value
float temp; //Stores temperature value
void setup()
{
 Serial.begin(9600);
 dht.begin();
}
void loop()
{
 //Read data and store it to variables hum and temp
 hum = dht.readHumidity();
 temp= dht.readTemperature();
 //Print temp and humidity values to serial monitor
 Serial.print("Humidity: ");
 Serial.print(hum);
 Serial.print(" %, Temp: ");
 Serial.print(temp);
 Serial.println(" Celsius");
 delay(2000); //Delay 2 sec.
}

My ancient C programmer training (Unix servers) says I must move variables hum and temp to loop(), or is it better on Arduino to leave them as globals?

Answer*

Draft saved
Draft discarded
Cancel
4
  • Thanks for all your answers, I've changed the code, and it's good to know I don't need to change my practices too much :) (Global variables were banned in all the development environments I worked in in the 1990s) So am I right to conclude that I only NEED to use a global if I refer to it in setup() and loop()? Everything else can be local and passed around? Commented Dec 20, 2018 at 10:21
  • 1
    @minisaurus: Yes, that's right. However, now that he ban is lifted, I suggest you try to avoid thinking of globals as evil. If you find yourself passing a variable around through many functions, consider making it global: does that hurt the program's readability? If the answer is "no", then a global is probably a good choice. Commented Dec 20, 2018 at 10:32
  • I'm out of touch, but is the ban really lifted in professional environments with several developers, APIs, libraries and who knows how many files of source code? But I can see how globals maybe aren't a big problem in these single file small Arduino projects. Commented Dec 20, 2018 at 13:50
  • 1
    @minisaurus: I don't know on these environments. My answer is specifically for the kind of programs you write on smallish embedded devices. Commented Dec 20, 2018 at 15:36

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /