DHT22 sensor required to work globally

Hello and thank you in advance for reading.

I have a conceptual and structural issue with coding up a DHT sensor.

I have coded up an example that hopefully explains what I am doing and should highlight what Is going on.

#include <Wire.h> 
#include <LiquidCrystal_PCF8574.h>
LiquidCrystal_PCF8574 lcd(0x3F);

#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);


void setup() {
  
Serial.begin(115200);
dht.begin();
lcd.begin(16, 2);

}

void loop() {


lcd_function();

}


void lcd_function(){
  
  // Wait a few seconds between measurements.
  delay(2000);

  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Check if any reads failed and exit early (to try again).
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  // serial porting
  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F("%  Temperature: "));
  Serial.print(temperature);
  Serial.println("°C ");

  //LCD porting
  lcd.home();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(F("Hum: "));
  lcd.print(humidity);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print(F("Temp: "));
  lcd.print(temperature);
  lcd.print("C");
  
  }

Now the issue is the "float variables" only work within a void sub program.

I need the DHT sensor to work globally! So... say for instance I write code in "void loop" or any other void for the matter; I that need the sensor information to operate other functions correctly (relays switching on and off).

HOW?

I welcome examples and links to further learning.

I have no idea what "work globally" means.

.

You also lost me with "globally"? If the code runs here it will run there. I also have no idea why you created a void lcd_function() to only be called from the void loop() function. Here is an example of similar code for a DHT 22 or DHT 12 sensor. If I wanted to turn pins On/Off based on any of the variables I would have just included it in the void loop function.

//===================START======================
//References
#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_Sensor.h>
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

// set the LCD address to 0x27 for a 20 chars and 4 line display
LiquidCrystal_I2C lcd(0x27,20,4); 

// Uncomment whatever DHT type you're using!
//#define DHTTYPE DHT11   // DHT 11 
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

//Define Arduino input pin
#define DHTPIN 2

// Initialize DHT sensor for normal 16mhz Arduino 
DHT dht(DHTPIN, DHTTYPE); 

//====================SETUP=====================
void setup(){

  Serial.begin(9600); 
   // Initialize the DHT Sensor
  dht.begin();
  pinMode(2,INPUT);
  // Initialize LCD Screen
  lcd.init();                      
  lcd.init();
  lcd.backlight();
  
}
//====================Void Loop====================
void loop(){
  //Wait a few seconds
  delay(2000);

  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
// Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);
  
// Serial print the serial monitor data
  Serial.print("Humidity: "); 
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
  Serial.print("DATA,TIME,"); Serial.print(t); Serial.print(","); Serial.println(h);

 // LCD Data
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Humidity = ");
  lcd.print( h);
  lcd.print("%");
  lcd.setCursor(0,1);
  lcd.print("Temperature = ");
  lcd.print(t);
  lcd.print("C");
  lcd.setCursor(0,2);
  lcd.print("Temperature = ");
  lcd.print(f);
  lcd.print("F");
  lcd.setCursor(0,3);
  lcd.print("Heat Index = ");
  lcd.print (hi);
}

Ron

I was hoping to meet knowledge / experience here....

Please re read what I posted. I explained very simply and clearly.

The code that I provided works and my example stands correct.

However I do not want to have to double up on using the FLOAT variables in every single sub program (which is why I showed a separate sub program)

The program I am building is quite large and the variables would be required for several sub programs.

"Global variables are ones declared before main or loop and can universally be called upon"

Can some one please help. If you do not understand please refrain from posting.

You should just declare those variables globally (on top) instead of locally (in the function). It's called variable scope. Very important concept in C++.

Hi SLant_Eng

Ron Blain pointed at a very peculiar way of programming (about that later). Floats first!

The DHT22 reads the temperature and humidity as floats, but you must reserve space in memory to store these floats for later use. if you don't do this the vaklues are displayed but as they are not stored they will not be available elsewhere.

The simple solution therefore is to add to the section where you declare parameters the following
(see comment by wvmarle)

float temperature; // storage variable temperature from DHT22
float humidity; // storage variables relative humidity DHT22

Now your floats will be as you call it 'global' variables, that is to be recalled and used everywhere in your sketch

Serial begin:
You have set the Serial Monitor port speed way too high. Serial Monitor will print only gibberisch, or just nothing.

Serial begin (9600);

and then: programming:

It is good use to place in in the loop section calls to subroutines that each do a specific job. here the three jobs are: 1. read the sensor, 2. send the new values to the LCD display, 3. send the new values to Serial Monitor

Here is a sketch that works with a DHT11 and my own old parallel LCD display.
Put in your own I2C LCD display, change DHT11 into DHT22 and there you go.

// Slang_Eng_DHT22_LCD
// rebuilt around variables and subroutines 
// Photoncatcher 
// April 5, 20120
// public domain


  #include <Wire.h>
  #include <LiquidCrystal.h>

  LiquidCrystal lcd (12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

  #include "DHT.h"
  #define DHTPIN 10
  #define DHTTYPE DHT11
  DHT dht(DHTPIN, DHTTYPE);

  float temperature;   //  storage variable temperature from DHT22
  float humidity;      //  storage variables relative humidity DHT22


void setup() {
 
  Serial.begin(9600);
  dht.begin();
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Hum:         %");
  lcd.setCursor(0, 1);
  lcd.print("Temp:        C");

}

void loop() {

  get_temperature_and_humidity ();     // call subroutinme that reads the sensor and stores the temp-humidity values

  do_LCD_porting ();                   // call subroutine that displays on LCD

  do_Serial_porting ();                // call subtroutine that prints Serial Monitor
  
  delay(2000);


}

// =============================== subroutines ===================================================


void get_temperature_and_humidity (){                        // read the DHT sensor and store the values

   temperature = dht.readTemperature();
   humidity = dht.readHumidity();         
   if (isnan(humidity) || isnan(temperature)) {              // Check if any reads failed and exit early (to try again).
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
   }  
}

void do_LCD_porting (){                                      // send values to the LCD display

  lcd.setCursor(7,0);
  lcd.print(humidity,1);                                     // one decimal is enough
  lcd.setCursor(7, 1);
  lcd.print(temperature,1);                                  // one decimal is enough
  
}


void do_Serial_porting (){                                   // send values to Serial Monitor
  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F("%  Temperature: "));
  Serial.print(temperature);
  Serial.println("°C ");

}

A small refinement will introduce the 'degree' symbol on your LCD display:

void setup() {

Serial.begin(9600);
dht.begin();
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Hum: %");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.write(char(223));
lcd.write("C");

}

Success!

Slant_Eng:
I welcome examples and links to further learning.

Find a C or C++ tutorial or two and read them end-to-end at least twice with a fresh brain.
Its far more productive than trying to learn by coding first and getting stuck and frustrated.
Check out a few tutorials to find one's you like best. At this stage skip the more complex parts
of the language such as classes/inheritance. You want to get an overview of the language as
soon as possible.

You can then start to code while the information is in your head, and try to use most of the
language features in order to help reinforce the memory. You'll have many uncertainties about
details that you'll have to chase up by searching online, or a bit of trial and error

Hi Mark, most of us tinkering with Arduinos is amateur, self-taught men with interest in electronics, and so am I. Nevertheless, by looking over the shoulders of professionals and with a lot of learning and little bit of self-confidence even an amateur can come a certain distance along a long way. And it gives such an enormous satisfaction when a project works successfully. And..... if all else fails, read the manual!

@ photoncatcher. Thank you for your very clear explanation and showing an elegant solution to my problem.

You have taught a man to fish.

I knew about putting the variables after the #includes and declarations to make them global.

I did not know however; How to get variables to operate in runtime loop (to update constantly) and remain functionally global.

I came here because I was doing what MarkT was was suggesting. But I could find nothing "like" or anything that directly related to the issue I was having. I knew it was an issue that had to be with my understanding.

Issue has now been solved.