Cerca codice

Lezione 36: Utilizzare il sensore di temperatura HTU21D con un LCD Corso Arduino passo dopo passo

Lezione 36: Utilizzare il sensore di temperatura HTU21D con un LCD Corso Arduino passo dopo passo

Il sensore di temperatura e umidità HTU21D è una scelta popolare per molti progetti Arduino grazie alla sua facilità d'uso e precisione. In questa lezione, costruiremo un progetto semplice che legge i dati di temperatura e umidità dal sensore e li visualizza su uno schermo LCD. Entro la fine di questo tutorial, avrai un setup funzionante che visualizza continuamente la temperatura in Celsius, Fahrenheit e Kelvin, oltre alla percentuale di umidità relativa. Per ulteriori chiarimenti, puoi fare riferimento al video (nel video al mm:ss).

Hardware Spiegato

Il componente principale di questo progetto è il sensore di temperatura e umidità HTU21D, che comunica tramite I2C. Questo sensore opera all'interno di un intervallo di tensione da 1,5 a 3,6 volt, rendendolo adatto sia per sistemi da 3,3V che da 5V. Consuma molto poca energia, tipicamente solo 0,02 microampere in inattività e 450 microampere durante la misurazione. Oltre all'HTU21D, utilizzeremo anche un display LCD, in particolare l'LDC1602 con I2C. Questo display consente un facile output di dati testuali e richiede solo due pin per la comunicazione: SDA (linea dati) e SCL (linea di clock). La combinazione di questi componenti ci permetterà di creare un display informativo per monitorare i livelli di temperatura e umidità.

Dettagli della scheda dati

ProduttoreTE Connectivity
Numero di parteHTU21D-F
Tensione logica/IO1,5 - 3,6 V
Tensione di alimentazione3,3 V (tip.)
Corrente di uscita (tipica)0,02 µA (inattivo), 450 µA (misurazione)
Intervallo di temperatura-40 a +125 °C
Gamma di umidità0 a 100 %HR
Risoluzione (Temperatura)0,01 °C
Risoluzione (Umidità)0,04 %UR
PacchettoDFN-6

  • Utilizzare una resistenza di pull-up per le linee SDA e SCL se non sono integrate.
  • Garantire una corretta tensione di alimentazione per evitare di danneggiare il sensore.
  • Mantenere un cablaggio adeguato per prevenire errori di comunicazione.
  • Controlla l'indirizzo I2C se il sensore non risponde.
  • Usa un ritardo tra le letture per prevenire il sovraccarico del sensore.
  • Assicurati che il LCD sia compatibile con la comunicazione I2C.

Istruzioni per il cablaggio

Per collegare il sensore HTU21D e il display LCD, inizia con le connessioni di alimentazione. Collega il pin sinistro dell'HTU21D alla sorgente di alimentazione a 3,3V e il secondo pin (spesso rosso) a terra. Successivamente, collega il pin SDA dell'HTU21D al pin analogico A4 dell'Arduino e il pin SCL al pin analogico A5. Per il display LCD1602, collega il pin VCC alla stessa sorgente di alimentazione a 3,3V e collega il pin GND a terra. Il pin SDA del LCD dovrebbe collegarsi anch'esso ad A4 e il pin SCL dovrebbe collegarsi ad A5, permettendo a entrambi i componenti di condividere il bus I2C. Assicurati che tutte le connessioni siano sicure per facilitare una corretta comunicazione tra l'Arduino, il sensore e il display.

Esempi di codice e guida passo-passo

Il seguente codice inizializza il sensore HTU21D e il display LCD. Nella funzione di impostazione, il LCD viene preparato per l'uso e il sensore viene controllato per la connettività.

void setup() {
  lcd.begin();
  lcd.backlight();
  if (!htu.begin()) {
      lcd.print("Robojax HTUD1DF");
      lcd.setCursor(0,1);
      lcd.print("sensor missing"); 
      while (1);
  } else {
      lcd.print("Robojax HTUD1DF");
      lcd.setCursor(0,1);
      lcd.print("Demo"); 
  }
  delay(2000);   
}

Questo estratto verifica se il sensore è collegato correttamente. In caso contrario, visualizza un messaggio di errore sul LCD e interrompe il programma. Se il sensore funziona, mostra un messaggio di demo per due secondi. La funzione loop è dove avviene la lettura e la visualizzazione principale. Qui, chiamiamo la funzione `lcdDisplay` per mostrare la temperatura in diverse unità:

void loop() {
   lcd.clear(); // clear previous values from screen
   lcdDisplay(0, 0, "Celsius: ", 10, 0, getHTU('C'), 'd');  
   lcdDisplay(0, 1, "Fahrenheit: ", 10, 1, getHTU('F'), 'd');     
   delay(5000);
}

In questo ciclo, il LCD viene cancellato e vengono visualizzate le letture di temperatura in Celsius e Fahrenheit. La funzione `getHTU` viene chiamata con il carattere 'C' per Celsius e 'F' per Fahrenheit, rispettivamente. Infine, la funzione `getHTU` è definita per leggere la temperatura o l'umidità in base al carattere di input:

float getHTU(char type) {
   float temp = htu.readTemperature();
   float rel_hum = htu.readHumidity();
   if(type =='F') {
       return temp * 9/5 + 32; // convert to Fahrenheit 
   } else if(type =='K') {
       return temp + 273.15; // convert to Kelvin
   } else if(type =='H') {
       return rel_hum; // return relative humidity
   } else {
       return temp; // return Celsius
   }
}

Questa funzione legge la temperatura e l'umidità dal sensore e converte la temperatura nell'unità richiesta. Assicurati di controllare il codice completo caricato sotto l'articolo per ulteriori dettagli.

Dimostrazione / Cosa Aspettarsi

Al termine del cablaggio e del caricamento del codice, dovresti vedere i valori di temperatura e umidità visualizzati sul display LCD. Le letture si aggiorneranno ogni pochi secondi, riflettendo le condizioni attuali. Se applichi calore al sensore, dovresti notare un aumento della temperatura, mentre l'umidità dovrebbe diminuire leggermente. Fai attenzione al limite massimo di temperatura del sensore; superarlo può comportare letture imprecise o guasti del sensore (nel video a mm:ss).

Timestamp video

  • 00:00- Introduzione al progetto
  • 01:15- Istruzioni per il cablaggio
  • 03:30- Passeggiata nel codice
  • 10:00- Dimostrazione dell'impostazione
511-Lesson 36: Using the HTU21D Temperature Sensor with an LCD and Arduino: A Step-by-Step Course
Lingua: C++
/*
 * Robojax Arduino Step-by-Step Course
 * Part 4: Temperature Sensors
 * Lesson 36: HTU21D Temperature Sensor with LCD1602 and LCD2004 Display
 


 * Display Temperature from HTU21DF on LCD1602-I2C or LCD2004
 * Updated by Ahmad Shamshiri on July 13, 2019



  Please watch video instructions here https://youtu.be/SrFJKbmiaPM
 This code is available at http://robojax.com/course1/?vid=lecture36
 
with over 100 lectures free on YouTube. Watch it here http://robojax.com/L/?id=338
Get the code for the course: http://robojax.com/L/?id=339  

If you found this tutorial helpful, please support me so I can continue creating 
and make a donation using PayPal http://robojax.com/L/?id=64



*
  This is an example for the HTU21D-F Humidity & Temp Sensor

  Designed specifically to work with the HTU21D-F sensor from Adafruit
  ----> https://www.adafruit.com/products/1899

  These displays use I2C to communicate; 2 pins are required to
  interface

 Watch Introduction to a 360 Servo video with code: https://youtu.be/b_xvu6wWafA
You can get the wiring diagram from my Arduino Course at Udemy.com
Learn Arduino step by step with all libraries, codes, and wiring diagrams all in one place.
Visit my course now http://robojax.com/L/?id=62

If you found this tutorial helpful, please support me so I can continue creating 
content like this. 
or make a donation using PayPal http://robojax.com/L/?id=64

 * Code is available at http://robojax.com/learn/arduino

 * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.
 * This code has been downloaded from Robojax.com
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>. 

*/

#include <Wire.h>
#include "Adafruit_HTU21DF.h"

// Connect Vin to 3-5VDC
// Connect GND to ground
// Connect SCL to I2C clock pin (A5 on UNO)
// Connect SDA to I2C data pin (A4 on UNO)

Adafruit_HTU21DF htu = Adafruit_HTU21DF();

// start of settings for LCD1602 with I2C
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x3F, 16, 2);
// end of settings for LCD1602 with I2C

void setup() {
	//Get the code for the course: http://robojax.com/L/?id=339  
  lcd.begin();  
  lcd.backlight();
  if (!htu.begin()) {
      lcd.print("Robojax HTUD1DF");
      lcd.setCursor(0,1);
      lcd.print("sensor missing"); 
    while (1);
  }else{
  // initialize the LCD

  lcd.print("Robojax HTUD1DF");
  lcd.setCursor(0,1);
  lcd.print("Demo"); 
  }
  delay(2000);   
}

void loop() {
//Get the code for the course: http://robojax.com/L/?id=339  	
   lcd.clear();// clear previous values from screen
lcdDisplay(
             // to print Celsius:
             0, // character 0 
             0, // line 0
             "Celsius: ", 

             // to print Celsius
             10, // character 10
             0, // line 0
             getHTU('C'),
             'd'
             );  

  lcdDisplay(
             // to print fahrenheit:
             0, // character 0 
             1, // line 1
             "Fahrenheit: ", 

             // to print Fahrenheit
             10, // character 9
             1, // line 0
             getHTU('F'),
             'd'
             );     
    delay(5000);
lcdDisplay(
             // to print Kelvin:
             0, // character 0 
             0, // line 0
             "Kelvin: ", 

             // to print Celsius
             9, // character 10
             0, // line 0
             getHTU('K'),
             'k'
             );      
  lcdDisplay(
             // to print humidity text
             0, // character 0 
             1, // line 1
             "Humidity: ", 

             // to print humidity
             10, // character 9
             1, // line 1
             getHTU('H'),
             '%' 
             );  
   
        delay(5000);
}

/*
 * @brief returns temperature or relative humidity
 * @param "type" is character
 *     C = Celsius
 *     K = Kelvin
 *     F = Fahrenheit
 *     H = Humidity
 * @return returns one of the values above
 * Usage: to get Fahrenheit type: getHTU('F')
 * to print it on serial monitor Serial.println(getHTU('F'));
 * Written by Ahmad Shamshiri on July 13, 2019
 * in Ajax, Ontario, Canada
 * www.Robojax.com 
 */
float getHTU(char type)
{
	//Get the code for the course: http://robojax.com/L/?id=339  
  float value;
    float temp = htu.readTemperature();
    float rel_hum = htu.readHumidity();
   if(type =='F')
   {
    value = temp *9/5 + 32;//convert to Fahrenheit 
   }else if(type =='K')
   {
    value = temp + 273.15;//convert to Kelvin
   }else if(type =='H')
   {
    value = rel_hum;//return relative humidity
   }else{
    value = temp;// return Celsius
   }
   return value;
}//


/*
 * lcdDisplay(int tc, int tr, String title, int vc, int vr, float value)
 * displays value and title on LCD1602
 * How to use:
 * If you want to display: "Voltage: 13.56mV" starting from the first character
 * on the second row.
 * use:
 * lcdDisplay(0, 1, "Voltage: ", 13.56,'d')
 *   
 *   'd' is degree symbol
 * tc  is character number  (0)
 * tr is row in the lcd (1)
 * title is the text (Voltage:)
 * vc value for character 
 * vr value for  row or line
 * value is the value (13.56)
 */
void lcdDisplay(int tc, int tr, String title, int vc, int vr, float value,char symbol)
{
   // Robojax.com LCD1602 for HTU21D Demo
   lcd.setCursor (tc,tr); //
   lcd.print(title);
   
   lcd.setCursor (vc,vr); //
   lcd.print(value);
   if(symbol == 'd')
   {
    lcd.print((char)223);
   }else if(symbol =='%')
   {
    lcd.print("%");
   }else if(symbol =='k')
   {
    lcd.print("K");
   }
 // Robojax.com LCD1602 for HTU21D Demo
}

Cose di cui potresti avere bisogno

File📁

Scheda tecnica (pdf)