Digital Weather Station using Raspberry Pi Pico and DHT22


Build your own digital weather station using Raspberry Pi Pico and DHT22 sensor. Monitor real-time temperature and humidity levels with continuous display updates on a 16x2 LCD screen. Perfect for learning environmental monitoring without buying physical components - test everything in Wokwi simulator first!

 Digital Weather Station using Raspberry Pi Pico and DHT22

Build your own Digital Weather Monitoring System using the Raspberry Pi Pico and DHT22 sensor. This beginner-friendly IoT project measures real-time temperature and humidity and displays the readings on a 16x2 I2C LCD screen — all fully testable in the Wokwi simulator before using physical hardware.

Perfect for students, makers, and IoT beginners who want hands-on experience with environmental monitoring using MicroPython.


 Project Overview

This weather station:

  • Continuously reads temperature (°C & °F)

  • Displays humidity percentage (0–100%)

  • Updates LCD every 2 seconds

  • Handles sensor read errors gracefully

  • Uses I2C communication for LCD control

  • Runs on MicroPython firmware

The DHT22 sensor communicates with the Pico via a digital single-wire protocol, while the LCD uses I2C (SDA & SCL pins).


Components Required

  • Raspberry Pi Pico (simulated in Wokwi)

  • DHT22

  • 16x2 LCD Display (I2C)

  • 10kΩ Pull-up Resistor

  • Jumper wires

  • MicroPython firmware

  • Wokwi


Circuit Connections

DHT22 Sensor:

  • VCC → 3.3V

  • GND → GND

  • DATA → GPIO15

  • 10kΩ Resistor between DATA and VCC

LCD Display (I2C Mode):

  • SDA → GPIO0

  • SCL → GPIO1

  • VCC → 3.3V

  • GND → GND

 Key Features

✔ Real-time temperature monitoring (°C & °F)
✔ Humidity percentage display
✔ LCD updates every 2 seconds
✔ Sensor error handling
✔ Customizable display layout
✔ Fully simulated in Wokwi
✔ Beginner-friendly MicroPython project


 Sample LCD Output

Line 1: Temp: 24.5°C
Line 2: Humid: 65.2%

Console Output:

Temperature: 24.5°C (76.1°F)
Humidity: 65.2%

What You’ll Learn

This Raspberry Pi Pico weather station project teaches:

  • Reading DHT22 sensor data using MicroPython

  • I2C communication protocol

  • LCD display interfacing

  • Temperature conversion (Celsius to Fahrenheit)

  • Error handling in embedded systems

  • Data formatting for display

  • Sensor timing and delays

  • Digital sensor communication


Real-World Applications

  • Home climate monitoring system

  • Greenhouse automation

  • Smart HVAC control

  • Mold prevention monitoring

  • IoT weather station

  • Environmental data logging system

  • Smart home automation projects


Why Use Wokwi Simulator?

Using Wokwi allows you to:

  • Test the complete project for free

  • Avoid wiring mistakes

  • View serial output instantly

  • Adjust virtual temperature & humidity values

  • Share project links easily

  • Debug before hardware implementation

Code:

main.py:
"""
Temperature and Humidity Monitor using Raspberry Pi Pico
Hardware: DHT22 Sensor + 16x2 I2C LCD Display
Platform: Wokwi Simulator
Author: MakeMindz
"""

from machine import Pin, I2C
from time import sleep
import dht
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd

# LCD Configuration
I2C_ADDR = 0x27      # I2C address of LCD (default for most I2C LCDs)
I2C_NUM_ROWS = 2     # Number of rows on LCD
I2C_NUM_COLS = 16    # Number of columns on LCD

# Pin Configuration
DHT_PIN = 15         # DHT22 sensor data pin (GPIO 15)
I2C_SDA_PIN = 0      # I2C SDA pin (GPIO 0)
I2C_SCL_PIN = 1      # I2C SCL pin (GPIO 1)

# Initialize I2C for LCD
i2c = I2C(0, sda=Pin(I2C_SDA_PIN), scl=Pin(I2C_SCL_PIN), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)

# Initialize DHT22 sensor
sensor = dht.DHT22(Pin(DHT_PIN))

# Startup message
lcd.clear()
lcd.putstr("MakeMindz")
lcd.move_to(0, 1)
lcd.putstr("Temp & Humidity")
sleep(2)

print("Temperature and Humidity Monitor Started!")
print("=" * 40)

def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit"""
    return (celsius * 9/5) + 32

def read_sensor():
    """Read temperature and humidity from DHT22 sensor"""
    try:
        sensor.measure()
        temp_c = sensor.temperature()
        humidity = sensor.humidity()
        return temp_c, humidity
    except OSError as e:
        print(f"Failed to read sensor: {e}")
        return None, None

def display_readings(temp_c, humidity):
    """Display temperature and humidity on LCD"""
    if temp_c is not None and humidity is not None:
        # Convert to Fahrenheit
        temp_f = celsius_to_fahrenheit(temp_c)
       
        # Clear LCD
        lcd.clear()
       
        # Line 1: Temperature
        lcd.putstr(f"Temp:{temp_c:.1f}C")
        lcd.move_to(0, 1)
       
        # Line 2: Humidity
        lcd.putstr(f"Humid:{humidity:.1f}%")
       
        # Print to console
        print(f"Temperature: {temp_c:.1f}°C ({temp_f:.1f}°F)")
        print(f"Humidity: {humidity:.1f}%")
        print("-" * 40)
    else:
        # Display error message
        lcd.clear()
        lcd.putstr("Sensor Error!")
        lcd.move_to(0, 1)
        lcd.putstr("Check Wiring")
        print("Error: Could not read sensor data")

# Main loop
while True:
    try:
        # Read sensor data
        temperature, humidity = read_sensor()
       
        # Display on LCD and console
        display_readings(temperature, humidity)
       
        # Wait 2 seconds before next reading
        sleep(2)
       
    except KeyboardInterrupt:
        print("\nProgram stopped by user")
        lcd.clear()
        lcd.putstr("Program Stopped")
        break
    except Exception as e:
        print(f"Error in main loop: {e}")
        lcd.clear()
        lcd.putstr("System Error!")
        sleep(2)


Components Required

  • Raspberry Pi Pico (simulated in Wokwi)
  • DHT22 Temperature & Humidity Sensor
  • 16x2 LCD Display (I2C or parallel connection)
  • 10kΩ Pull-up Resistor (for DHT22 data line)
  • Breadboard and jumper wires
  • MicroPython firmware on Pico
lcd_api.py:
"""
LCD API Library for MicroPython
Provides a simple API for controlling character LCDs
"""

import time

class LcdApi:
    """Implements the API for talking with HD44780 compatible character LCDs."""

    # Commands
    LCD_CLR = 0x01              # DB0: clear display
    LCD_HOME = 0x02             # DB1: return to home position
    LCD_ENTRY_MODE = 0x04       # DB2: set entry mode
    LCD_ENTRY_INC = 0x02        # --DB1: increment
    LCD_ENTRY_SHIFT = 0x01      # --DB0: shift
    LCD_ON_CTRL = 0x08          # DB3: turn lcd/cursor on
    LCD_ON_DISPLAY = 0x04       # --DB2: turn display on
    LCD_ON_CURSOR = 0x02        # --DB1: turn cursor on
    LCD_ON_BLINK = 0x01         # --DB0: blinking cursor
    LCD_MOVE = 0x10             # DB4: move cursor/display
    LCD_MOVE_DISP = 0x08        # --DB3: move display (0-> move cursor)
    LCD_MOVE_RIGHT = 0x04       # --DB2: move right (0-> left)
    LCD_FUNCTION = 0x20         # DB5: function set
    LCD_FUNCTION_8BIT = 0x10    # --DB4: set 8BIT mode (0->4BIT mode)
    LCD_FUNCTION_2LINES = 0x08  # --DB3: two lines (0->one line)
    LCD_FUNCTION_10DOTS = 0x04  # --DB2: 5x10 font (0->5x7 font)
    LCD_CGRAM = 0x40            # DB6: set CG RAM address
    LCD_DDRAM = 0x80            # DB7: set DD RAM address
    LCD_RS_CMD = 0
    LCD_RS_DATA = 1
    LCD_RW_WRITE = 0
    LCD_RW_READ = 1

    def __init__(self, num_lines, num_columns):
        self.num_lines = num_lines
        if self.num_lines > 4:
            self.num_lines = 4
        self.num_columns = num_columns
        if self.num_columns > 40:
            self.num_columns = 40
        self.cursor_x = 0
        self.cursor_y = 0
        self.backlight = True
        self.display_off()
        self.backlight_on()
        self.clear()
        self.hal_write_command(self.LCD_ENTRY_MODE | self.LCD_ENTRY_INC)
        self.hide_cursor()
        self.display_on()

    def clear(self):
        """Clears the LCD display and moves the cursor to the top left corner."""
        self.hal_write_command(self.LCD_CLR)
        self.hal_write_command(self.LCD_HOME)
        self.cursor_x = 0
        self.cursor_y = 0

    def show_cursor(self):
        """Causes the cursor to be made visible."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY |
                               self.LCD_ON_CURSOR)

    def hide_cursor(self):
        """Causes the cursor to be hidden."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)

    def blink_cursor_on(self):
        """Turns on the cursor, and makes it blink."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY |
                               self.LCD_ON_CURSOR | self.LCD_ON_BLINK)

    def blink_cursor_off(self):
        """Turns on the cursor, and makes it not blink."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY |
                               self.LCD_ON_CURSOR)

    def display_on(self):
        """Turns on (i.e. unblanks) the LCD."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)

    def display_off(self):
        """Turns off (i.e. blanks) the LCD."""
        self.hal_write_command(self.LCD_ON_CTRL)

    def backlight_on(self):
        """Turns the backlight on."""
        self.backlight = True
        self.hal_backlight_on()

    def backlight_off(self):
        """Turns the backlight off."""
        self.backlight = False
        self.hal_backlight_off()

    def move_to(self, cursor_x, cursor_y):
        """Moves the cursor position to the indicated position."""
        self.cursor_x = cursor_x
        self.cursor_y = cursor_y
        addr = cursor_x & 0x3f
        if cursor_y & 1:
            addr += 0x40    # Lines 1 & 3 add 0x40
        if cursor_y & 2:    # Lines 2 & 3 add number of columns
            addr += self.num_columns
        self.hal_write_command(self.LCD_DDRAM | addr)

    def putchar(self, char):
        """Writes the indicated character to the LCD at the current cursor position."""
        if char == '\n':
            if self.cursor_y < self.num_lines - 1:
                self.cursor_y += 1
            self.cursor_x = 0
            self.move_to(self.cursor_x, self.cursor_y)
        else:
            self.hal_write_data(ord(char))
            self.cursor_x += 1
            if self.cursor_x >= self.num_columns:
                self.cursor_x = 0
                if self.cursor_y < self.num_lines - 1:
                    self.cursor_y += 1
                self.move_to(self.cursor_x, self.cursor_y)

    def putstr(self, string):
        """Write the indicated string to the LCD at the current cursor position."""
        for char in string:
            self.putchar(char)

    def custom_char(self, location, charmap):
        """Write a character to one of the 8 CGRAM locations, available as chr(0) through chr(7)."""
        location &= 0x7
        self.hal_write_command(self.LCD_CGRAM | (location << 3))
        time.sleep_us(40)
        for i in range(8):
            self.hal_write_data(charmap[i])
            time.sleep_us(40)
        self.move_to(self.cursor_x, self.cursor_y)

    def hal_backlight_on(self):
        """Allows derived classes to override hal_backlight_on."""
        pass

    def hal_backlight_off(self):
        """Allows derived classes to override hal_backlight_off."""
        pass

    def hal_write_command(self, cmd):
        """Writes a command to the LCD. Derived classes must implement this."""
        raise NotImplementedError

    def hal_write_data(self, data):
        """Write data to the LCD. Derived classes must implement this."""
        raise NotImplementedError


Circuit Connections

  • DHT22 Sensor: VCC → 3.3V, GND → GND, Data → GPIO15 (with 10kΩ pull-up to 3.3V)
  • LCD Display (I2C): SDA → GPIO0, SCL → GPIO1, VCC → 3.3V, GND → GND
  • LCD Display (Parallel): RS → GPIO2, E → GPIO3, D4-D7 → GPIO4-7
diagram.json:
{
  "version": 1,
  "author": "MakeMindz",
  "editor": "wokwi",
  "parts": [
    {
      "type": "wokwi-pi-pico",
      "id": "pico",
      "top": 0,
      "left": 0,
      "attrs": {}
    },
    {
      "type": "wokwi-dht22",
      "id": "dht22",
      "top": -38.4,
      "left": 220.8,
      "attrs": {
        "temperature": "24",
        "humidity": "65"
      }
    },
    {
      "type": "wokwi-lcd1602",
      "id": "lcd",
      "top": -144,
      "left": -192,
      "attrs": {
        "pins": "i2c"
      }
    },
    {
      "type": "wokwi-resistor",
      "id": "r1",
      "top": -19.2,
      "left": 268.8,
      "attrs": {
        "value": "10000"
      }
    }
  ],
  "connections": [
    [
      "pico:GP0",
      "lcd:SDA",
      "green",
      [
        "h0"
      ]
    ],
    [
      "pico:GP1",
      "lcd:SCL",
      "blue",
      [
        "h0"
      ]
    ],
    [
      "pico:3V3",
      "lcd:VCC",
      "red",
      [
        "h0"
      ]
    ],
    [
      "pico:GND.8",
      "lcd:GND",
      "black",
      [
        "h0"
      ]
    ],
    [
      "dht22:VCC",
      "pico:3V3",
      "red",
      [
        "v0"
      ]
    ],
    [
      "dht22:GND",
      "pico:GND.3",
      "black",
      [
        "v0"
      ]
    ],
    [
      "dht22:SDA",
      "pico:GP15",
      "yellow",
      [
        "v0"
      ]
    ],
    [
      "r1:1",
      "dht22:SDA",
      "",
      [
        "v0"
      ]
    ],
    [
      "r1:2",
      "dht22:VCC",
      "",
      [
        "v0"
      ]
    ]
  ],
  "dependencies": {}
}

Applications

picoi2c_lcd.py:

"""
I2C LCD Library for Raspberry Pi Pico
Implements I2C communication with HD44780 compatible LCDs
"""

import time
from lcd_api import LcdApi

# PCF8574 pin definitions
MASK_RS = 0x01       # P0
MASK_RW = 0x02       # P1
MASK_E = 0x04        # P2
MASK_BACKLIGHT = 0x08 # P3

SHIFT_DATA = 4       # P4-P7 are data bits

class I2cLcd(LcdApi):
    """Implements a HD44780 character LCD connected via PCF8574 on I2C."""

    def __init__(self, i2c, i2c_addr, num_lines, num_columns):
        self.i2c = i2c
        self.i2c_addr = i2c_addr
        self.i2c.writeto(self.i2c_addr, bytes([0]))
        time.sleep_ms(20)   # Allow LCD time to powerup
        # Send reset 3 times
        self.hal_write_init_nibble(self.LCD_FUNCTION | self.LCD_FUNCTION_8BIT)
        time.sleep_ms(5)    # Need to delay at least 4.1 msec
        self.hal_write_init_nibble(self.LCD_FUNCTION | self.LCD_FUNCTION_8BIT)
        time.sleep_ms(1)
        self.hal_write_init_nibble(self.LCD_FUNCTION | self.LCD_FUNCTION_8BIT)
        time.sleep_ms(1)
        # Put LCD into 4-bit mode
        self.hal_write_init_nibble(self.LCD_FUNCTION)
        time.sleep_ms(1)
        LcdApi.__init__(self, num_lines, num_columns)
        cmd = self.LCD_FUNCTION
        if num_lines > 1:
            cmd |= self.LCD_FUNCTION_2LINES
        self.hal_write_command(cmd)

    def hal_write_init_nibble(self, nibble):
        """Writes an initialization nibble to the LCD."""
        byte = ((nibble >> 4) & 0x0f) << SHIFT_DATA
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        time.sleep_ms(1)
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        time.sleep_ms(1)

    def hal_backlight_on(self):
        """Allows the hal layer to turn the backlight on."""
        self.i2c.writeto(self.i2c_addr, bytes([1 << 3]))

    def hal_backlight_off(self):
        """Allows the hal layer to turn the backlight off."""
        self.i2c.writeto(self.i2c_addr, bytes([0]))

    def hal_write_command(self, cmd):
        """Writes a command to the LCD."""
        byte = ((self.backlight << 3) |
                (((cmd >> 4) & 0x0f) << SHIFT_DATA))
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        time.sleep_ms(1)
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        byte = ((self.backlight << 3) |
                ((cmd & 0x0f) << SHIFT_DATA))
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        time.sleep_ms(1)
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        if cmd <= 3:
            time.sleep_ms(5)

    def hal_write_data(self, data):
        """Write data to the LCD."""
        byte = (MASK_RS |
                (self.backlight << 3) |
                (((data >> 4) & 0x0f) << SHIFT_DATA))
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        time.sleep_ms(1)
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        byte = (MASK_RS |
                (self.backlight << 3) |
                ((data & 0x0f) << SHIFT_DATA))
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        time.sleep_ms(1)
        self.i2c.writeto(self.i2c_addr, bytes([byte]))


  • Home Climate Monitoring: Track room temperature and humidity for comfort optimization
  • Greenhouse Automation: Monitor plant growing conditions
  • Weather Station: Build complete environmental monitoring systems
  • HVAC Control: Trigger fans or heaters based on readings
  • Mold Prevention: Alert when humidity levels are too high in bathrooms/basements
  • Data Logging: Record temperature trends over time for analysis

What You'll Learn

  • Reading DHT22 sensor data using MicroPython libraries
  • I2C communication protocol for LCD displays
  • Data parsing and formatting (temperature/humidity values)
  • LCD programming and custom display layouts
  • Sensor error handling and data validation
  • Timing and delays for accurate sensor readings
  • Digital sensor communication (one-wire protocol)
  • Using Wokwi simulator for testing before hardware build

Code Structure

Your MicroPython code will include:

  • Import DHT and LCD libraries
  • Initialize sensor on GPIO15 and LCD on I2C pins
  • Read temperature and humidity in a loop
  • Format data for LCD display (Line 1: Temp, Line 2: Humidity)
  • Handle sensor read failures gracefully
  • Update display every 2-3 seconds

Wokwi Simulator Advantages

  • Zero Cost: Test the complete project for free before buying components
  • Instant Testing: No wiring mistakes - connections are virtual
  • Easy Debugging: Serial monitor shows all sensor readings
  • Adjustable Sensor: Manually change temperature/humidity values to test different scenarios
  • Share Projects: Get a link to share your simulation with others

Sample Display Output

Line 1: Temp: 24.5°C 76.1°F
Line 2: Humidity: 65.2%

Difficulty Level

Beginner - Perfect first sensor project. Requires basic understanding of GPIO pins and Python syntax. Wokwi simulation makes it easy to test without hardware knowledge. Step-by-step tutorial with complete code provided.

Skills You'll Gain

This project builds fundamental IoT skills including sensor interfacing, data display, and environmental monitoring. These concepts are essential for smart home automation, agricultural tech, weather stations, and industrial monitoring systems. You'll gain hands-on experience with digital sensors and LCD displays - components used in thousands of real-world products.

View Complete Tutorial with Wokwi Simulation

Rapberry pi pico based projects:

Comments