Coding example of reading data from humidity sensor with Arduino

Categories: Uncategorized

Reading data from a humidity sensor with Arduino is a common task, especially when you want to monitor environmental conditions. One of the most popular humidity sensors is the DHT22 (or DHT11), which provides both temperature and humidity readings. Here’s a simple example of reading data from a DHT22 humidity sensor using an Arduino and the Adafruit DHT sensor library:

Step 1: Install the Adafruit DHT Sensor Library

Before you can use the DHT22 sensor, you’ll need to install the Adafruit DHT sensor library if you haven’t already. Here’s how to do it:

  1. Open the Arduino IDE.
  2. Go to “Sketch” -> “Include Library” -> “Manage Libraries…”
  3. In the Library Manager, type “DHT” into the search bar.
  4. Find “DHT sensor library by Adafruit” and click the “Install” button.

Step 2: Wiring

Connect the DHT22 sensor to your Arduino as follows:

  • Connect the sensor’s VCC pin to 5V on the Arduino.
  • Connect the sensor’s GND pin to GND on the Arduino.
  • Connect the sensor’s data pin (out) to a digital pin on the Arduino (e.g., D2).

Step 3: Arduino Code

Here’s an example Arduino code to read humidity and temperature data from the DHT22 sensor and display it on the Serial Monitor:

#include “DHT.h”

#define DHTPIN 2 // Digital pin connected to the DHT sensor

// Uncomment the type of sensor in use:
#define DHTTYPE DHT22 // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println(“DHT sensor example”);
dht.begin();
}

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

// Read humidity and temperature data.
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();

// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println(“Failed to read from DHT sensor!”);
return;
}

// Print the values to the Serial Monitor.
Serial.print(“Humidity: “);
Serial.print(humidity);
Serial.print(” %\t”);
Serial.print(“Temperature: “);
Serial.print(temperature);
Serial.println(” Β°C”);
}

Step 4: Monitor the Data

  1. Upload the code to your Arduino.
  2. Open the Serial Monitor by clicking “Tools” -> “Serial Monitor” in the Arduino IDE.
  3. Set the baud rate to 9600 (or the rate specified in your code).
  4. You should see humidity and temperature readings displayed in the Serial Monitor.

This example provides a basic introduction to reading data from a humidity sensor using Arduino. You can expand upon it by incorporating additional sensors, displaying data on an LCD screen, or sending it to a web server for remote monitoring.

Leave a Reply

Your email address will not be published. Required fields are marked *