We use OLED screens to show sensor data so we can see real-time information easily without a computer screen.
Displaying sensor readings on OLED in Raspberry Pi
import board import busio from adafruit_ssd1306 import SSD1306_I2C import adafruit_dht i2c = busio.I2C(board.SCL, board.SDA) oled = SSD1306_I2C(128, 32, i2c) dhtDevice = adafruit_dht.DHT22(board.D4) try: temperature = dhtDevice.temperature humidity = dhtDevice.humidity oled.fill(0) oled.text(f"Temp: {temperature:.1f} C", 0, 0, 1) oled.text(f"Humidity: {humidity:.1f}%", 0, 16, 1) oled.show() except RuntimeError as error: print(error.args[0])
This example uses the Adafruit DHT22 sensor and SSD1306 OLED display libraries.
Make sure your sensor and OLED are connected to the correct Raspberry Pi pins.
oled.text("Hello, OLED!", 0, 0, 1) oled.show()
temperature = dhtDevice.temperature humidity = dhtDevice.humidity print(f"Temp: {temperature} C, Humidity: {humidity} %")
oled.fill(0) oled.text(f"Temp: {temperature:.1f} C", 0, 0, 1) oled.text(f"Humidity: {humidity:.1f}%", 0, 16, 1) oled.show()
This program reads temperature and humidity from a DHT22 sensor every 2 seconds and shows the values on a 128x32 OLED screen. If the sensor has an error, it prints the error message to the console.
import board import busio from adafruit_ssd1306 import SSD1306_I2C import adafruit_dht import time i2c = busio.I2C(board.SCL, board.SDA) oled = SSD1306_I2C(128, 32, i2c) dhtDevice = adafruit_dht.DHT22(board.D4) while True: try: temperature = dhtDevice.temperature humidity = dhtDevice.humidity oled.fill(0) # Clear the screen oled.text(f"Temp: {temperature:.1f} C", 0, 0, 1) oled.text(f"Humidity: {humidity:.1f}%", 0, 16, 1) oled.show() except RuntimeError as error: print(f"Sensor error: {error.args[0]}") time.sleep(2)
Use the correct pins for your sensor and OLED connections on the Raspberry Pi.
OLED screens usually need to be cleared before drawing new text to avoid overlapping.
Sensor readings can sometimes fail; handle errors to avoid crashes.
OLED screens let you see sensor data directly on your Raspberry Pi project.
Use libraries to read sensors and control the OLED easily.
Update the display regularly to show fresh sensor readings.
