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.
|Raspberry Pi 4 Model B
|SSD1306 I2C OLED Display 128x64
|(Optional) Screw Terminal Adapter for Raspberry Pi
Or you can buy the following sensor kit:
|DIYables Sensor Kit 30 types, 69 units
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:
This image is created using Fritzing. Click to enlarge image
Raspberry Pi Code - Ultrasonic Sensor - OLED
- 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:
- Prior to utilizing the OLED display with a Raspberry Pi, we need to enable I2C interface on Raspberry Pi. See How to enable I2C interface on Raspberry Pi
- Install the OLED library by running the following command:
- Create a Python script file ultrasonic_oled.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
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.