Raspberry Pi - Ultrasonic Sensor - OLED

This tutorial instructs you how to measure the distance using an ultrasonic sensor and then displaying it on an OLED.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×SSD1306 I2C OLED Display 128x64
1×SSD1306 I2C OLED Display 128x32
1×Ultrasonic Sensor
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) USB-C Power Cable with On/Off Switch for Raspberry Pi 4B
1×(Optional) Plastic Case and Cooling Fan for Raspberry Pi 4B

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of OLED and Ultrasonic Sensor

If you are unfamiliar with OLED and Ultrasonic Sensor (including pinout, functioning, programming, etc.), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and Ultrasonic Sensor OLED

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code - Ultrasonic Sensor - OLED

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
pip install Adafruit-SSD1306
  • Create a Python script file ultrasonic_oled.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-ultrasonic-sensor-oled """ import time import RPi.GPIO as GPIO import Adafruit_SSD1306 # GPIO pin configuration for the ultrasonic sensor TRIG_PIN = 16 ECHO_PIN = 20 # OLED display configuration OLED_RESET_PIN = None # Set to GPIO pin if your display has a reset pin OLED = Adafruit_SSD1306.SSD1306_128_64(rst=OLED_RESET_PIN) # Initialize the OLED display OLED.begin() # Clear the display OLED.clear() OLED.display() def measure_distance(): # Trigger the ultrasonic sensor GPIO.output(TRIG_PIN, True) time.sleep(0.00001) GPIO.output(TRIG_PIN, False) pulse_start, pulse_end = 0, 0 # Record the time when the ultrasonic wave is transmitted while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() # Record the time when the reflected wave is received while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() # Calculate the time duration of the pulse pulse_duration = pulse_end - pulse_start # Calculate the distance using the speed of sound (343 m/s) distance = pulse_duration * 17150 return round(distance, 2) try: # Set up GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) while True: # Read distance from ultrasonic sensor distance = measure_distance() # Clear the display OLED.clear() # Display distance on OLED OLED.draw.text((0, 0), "Distance:", font=None, fill=255) OLED.draw.text((0, 16), "{} cm".format(distance), font=None, fill=255) # Display on OLED OLED.display() # Print distance to console (optional) print("Distance: {} cm".format(distance)) # Delay for readability time.sleep(1) except KeyboardInterrupt: print("Program terminated by user.") finally: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 ultrasonic_oled.py

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

  • Move your hand in front of the sensor.
  • Check out the result on the OLED and the Serial Monitor.

※ NOTE THAT:

This code will align the text on an OLED display both horizontally and vertically. For more information, please refer to How to vertical/horizontal center on OLED.

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!