Skip to content

How to use a 3.2 inch 256x64 OLED display with a distance sensor?

By admin
You connect a 3.2 inch 256x64 OLED display to a distance sensor by wiring the display’s SPI interface to your microcontroller’s SPI pins, hooking the sensor’s output to an analog or digital input, and then writing code that reads the sensor data and updates the display in real time. The 3.2 inch 256x64 oled display module runs on a SSD1322 controller, which supports 4-wire SPI at clock speeds up to 10 MHz, giving you a frame refresh rate of about 60 Hz for monochrome graphics. A typical distance sensor like the HC-SR04 ultrasonic module outputs a pulse width proportional to distance, with a range of 2 cm to 400 cm and a resolution of 0.3 cm. When you combine these, the display can show distance readings as a numeric value, a bar graph, or even a scrolling waveform, all updated every 50 ms.

Hardware Wiring and Pin Configurations

Start with the display’s SPI pins: CS (chip select), DC (data/command), SCK (serial clock), and MOSI (master out slave in). On an Arduino Uno, map these to digital pins 10 (CS), 9 (DC), 13 (SCK), and 11 (MOSI). The display also needs a 3.3V power supply, but the logic level is 3.3V tolerant, so you can use a voltage divider if your microcontroller runs at 5V. The HC-SR04 sensor has four pins: VCC (5V), GND, Trig (trigger), and Echo (echo). Connect Trig to pin 7 and Echo to pin 6 on the Arduino. The sensor draws about 15 mA during operation, and the display consumes around 20 mA with all pixels off, spiking to 40 mA when fully lit. A 100 µF capacitor between VCC and GND on the display power rail helps filter noise from the sensor’s ultrasonic bursts.

For the SPI wiring, keep the wires under 20 cm to avoid signal degradation at 10 MHz. Use twisted pairs for SCK and MOSI if possible. The display’s contrast is set via a command in the initialization sequence, typically at 0x7F for a 50% duty cycle, but you can adjust it to 0x9F for brighter output in direct sunlight. The sensor’s Echo pin outputs a 5V pulse, so you need a voltage divider (two resistors: 1kΩ and 2kΩ) to drop it to 3.3V before connecting to the Arduino’s pin 6, which is 5V tolerant but safer with the divider.

Initializing the Display and Sensor in Code

Use the Adafruit_SSD1322 library for the display, which handles the SPI commands. In the setup function, call display.begin() and display.setContrast(0x7F). The sensor requires a 10 µs trigger pulse on the Trig pin, then measure the pulse width on Echo with pulseIn(). The distance in cm is pulse width in microseconds divided by 58.0. For a 3.2 inch 256x64 display, the pixel resolution is 256 columns by 64 rows, so you can map the distance range (0 to 400 cm) to a 256-pixel bar graph. For example, each pixel represents about 1.56 cm. The display’s buffer is 2048 bytes (256x64/8), so you can update the entire screen in 2 ms at 10 MHz SPI, leaving plenty of time for sensor reads.

Here’s a typical timing breakdown: a sensor read takes 30 ms (including the 20 ms echo timeout), a display update takes 2 ms, and serial output (if used) takes 1 ms. That’s a 33 ms loop, giving you about 30 updates per second. The SSD1322 supports partial updates, so you can only redraw the area that changes, like the numeric value, reducing the update time to 0.5 ms. The library’s drawPixel() function is slow for large areas, so use drawFastHLine() or fillRect() for bar graphs.

Displaying Distance Data as a Numeric Value

To show the distance in centimeters, set the text size to 2 (16x16 pixels per character) and position it at the top-left corner. The display’s font is 8x8 pixels by default, so a 3-digit number like “123 cm” takes 48 pixels wide. Use display.setCursor(0, 0), display.print(distance), and display.print(" cm"). The sensor’s accuracy is ±3 mm at 2 m, but the display’s resolution is limited to 1 cm due to the pulse width measurement. For a 3.2 inch display, the viewing angle is 160 degrees, so you can read the value from any angle. The OLED’s contrast ratio is 2000:1, making the text readable even in bright ambient light up to 10,000 lux.

For a more precise reading, use the sensor’s average of 5 samples to reduce noise. The standard deviation of the HC-SR04 is about 2 mm at 1 m, so averaging 5 readings gives a 0.9 mm standard deviation. Display the average with one decimal place, like “123.4 cm”, but note that the sensor’s datasheet specifies a 0.3 cm resolution, so the decimal is only for visual smoothing. The display’s pixel pitch is 0.28 mm, so a 16x16 pixel character is about 4.5 mm tall, visible from 1 m away.

Creating a Bar Graph for Distance Visualization

A horizontal bar graph on the 256x64 display can represent distance from 0 to 400 cm. Use the full width of 256 pixels, with each pixel representing 1.56 cm. Draw a background rectangle with display.fillRect(0, 16, 256, 16, BLACK) to clear the bar area, then fill the bar with display.fillRect(0, 16, barWidth, 16, WHITE), where barWidth = distance / 1.56. The bar height is 16 pixels, centered vertically. Add a scale at the bottom with tick marks every 50 cm: display.drawFastVLine(32, 40, 4, WHITE) for 50 cm, 64 for 100 cm, and so on. The sensor’s maximum range is 400 cm, so the bar fills the entire width at 400 cm.

The bar graph updates in 1 ms because fillRect() is hardware-accelerated by the SSD1322. The display’s refresh rate is 60 Hz, so the bar appears smooth. The HC-SR04 has a 15-degree beam angle, so the bar graph shows the distance to the nearest object within that cone. For a 3.2 inch display, the bar graph is 64 mm wide, so each 1 mm of the bar represents 6.25 cm of distance. This is useful for parking sensors where you need a quick visual cue. The display’s power consumption is 0.12 W at full brightness, so it’s suitable for battery-powered projects.

Implementing a Scrolling Waveform for Real-Time Distance

A scrolling waveform plots distance over time on the 256x64 display. The Y-axis represents distance from 0 to 400 cm, with 64 pixels, so each pixel is 6.25 cm. The X-axis scrolls from left to right, with each new sample plotted at the rightmost column. Use a circular buffer to store the last 256 readings. In each loop, shift the existing waveform left by one pixel using display.scroll() or by redrawing the entire line. The SSD1322 has a hardware scroll function, but it’s for vertical scrolling only, so you need to redraw the waveform manually.

Plot each point with display.drawPixel(x, 63 - (distance / 6.25)). The sensor’s update rate is 30 Hz, so the waveform scrolls at 30 pixels per second, covering the full width in 8.5 seconds. The display’s pixel response time is under 10 µs, so the waveform appears crisp. The sensor’s accuracy is ±3 mm, but the waveform’s resolution is 6.25 cm per pixel, so small changes are lost. For a finer resolution, limit the Y-axis to 0 to 100 cm, giving 1.56 cm per pixel. The waveform helps detect motion patterns, like a person walking towards the sensor. The display’s 3.2 inch diagonal means the waveform is 64 mm tall, so each 1 mm of height represents 6.25 cm of distance.

Handling Multiple Distance Ranges and Display Modes

You can switch between numeric, bar graph, and waveform modes using a button or a serial command. The display’s buffer is 2048 bytes, so you can store three different screen layouts and switch between them in 2 ms. Use a state variable: mode 0 for numeric, mode 1 for bar graph, mode 2 for waveform. In each loop, call the appropriate display function. The sensor’s range can be set to short (2 cm to 50 cm), medium (2 cm to 200 cm), or long (2 cm to 400 cm) by adjusting the bar graph scale. For short range, the bar graph uses 256 pixels for 50 cm, giving 0.2 cm per pixel, which is finer than the sensor’s 0.3 cm resolution, so you see the sensor noise.

For the numeric mode, display the distance with a unit label. For the bar graph, add a threshold line at 20 cm for warning. For the waveform, show the last 10 seconds of data. The display’s contrast can be adjusted per mode: set contrast to 0x9F for waveform mode to see the line clearly, and 0x7F for numeric mode to save power. The HC-SR04 sensor has a 40 kHz ultrasonic frequency, which is inaudible to humans, but the display’s SPI clock at 10 MHz can generate EMI, so keep the sensor wire away from the SPI lines by at least 5 cm.

Power Management and Long-Term Reliability

The 3.2 inch OLED display consumes 40 mA at 3.3V with all pixels on, and 20 mA with 50% pixels on. The HC-SR04 sensor consumes 15 mA during operation and 2 mA in standby. Total current is 55 mA at 3.3V, or 0.18 W. For a 2000 mAh battery, the system runs for 36 hours continuously. The display’s lifetime is 50,000 hours to half brightness, and the sensor’s lifetime is 100,000 cycles. The SSD1322 controller has a built-in charge pump for the OLED voltage, so no external boost converter is needed. The display’s operating temperature is -40°C to +85°C, while the sensor’s is 0°C to +70°C, so the sensor limits the system in cold environments.

To reduce power, put the display to sleep with display.sleep() and wake it with display.wake(). The sensor can be triggered every 100 ms instead of 30 ms, reducing the update rate to 10 Hz and cutting power by 30%. The display’s SPI bus can be shared with other devices, but the CS pin must be pulled high when not in use. The sensor’s Echo pin has a 5V output, so a level shifter is mandatory for 3.3V microcontrollers. The display’s 256x64 resolution is 16,384 pixels, so each pixel is individually addressable, allowing for custom fonts or icons like a car silhouette for parking assist.

Calibration and Accuracy Considerations

The HC-SR04 sensor’s accuracy depends on temperature, with a 0.6% error per degree Celsius. At 25°C, the speed of sound is 346 m/s, but at 0°C it’s 331 m/s. Compensate by measuring temperature with a DS18B20 sensor and adjusting the formula: distance = (pulse width * (331.3 + 0.606 * temperature)) / 20000. The display can show the temperature as well, using the remaining 64 pixels vertically. The sensor’s beam angle is 15 degrees, so the distance reading is the average of all objects within that cone. For a 3.2 inch display, the numeric value is accurate to ±1 cm, but the bar graph shows the trend.

The display’s SPI interface has a maximum clock of 10 MHz, but the Arduino Uno’s SPI library runs at 4 MHz by default, which is fine for 30 updates per second. The sensor’s pulseIn() function has a resolution of 1 µs, so the distance resolution is 0.017 cm, but the sensor’s hardware limits it to 0.3 cm. The display’s pixel response time is 10 µs, so no ghosting occurs. The SSD1322’s internal oscillator runs at 1 MHz, so the display’s frame rate is fixed at 60 Hz. The sensor’s trigger pulse must be at least 10 µs, but a 20 µs pulse improves reliability.

Advanced Features: Object Detection and Alarms

You can set a threshold distance on the display, say 10 cm, and trigger an alarm when the sensor reads below that. The display shows a red warning icon (a 16x16 pixel exclamation mark) at the top-right corner. The SSD1322 supports grayscale with 4 bits per pixel, so you can use 16 shades of gray for the icon. The sensor’s update rate is 30 Hz, so the alarm responds within 33 ms. The display’s contrast can be set to maximum (0x9F) for the alarm state to attract attention. The HC-SR04 sensor has a blind spot of 2 cm, so objects closer than 2 cm show as 0 cm, and the display shows “ERR” for error.

For a multi-sensor setup, use two HC-SR04 sensors with separate Trig and Echo pins, and display the distances side by side on the 256x64 screen. Each sensor gets 128 pixels horizontally, with a vertical bar graph for each. The display’s buffer can handle two independent graphs, updating each in 1 ms. The total loop time is 60 ms for two sensors, giving 16 updates per second. The display’s 3.2 inch size is large enough to show two graphs with labels. The sensors must be triggered sequentially to avoid crosstalk, with a 10 ms delay between triggers.

Common Pitfalls and Debugging

One common issue is the display not initializing because the CS pin is not pulled low. Check the wiring with a multimeter: the display’s VCC should be 3.3V, and the SCK pin should show a 10 MHz square wave on an oscilloscope. The sensor’s Echo pin may float if the trigger pulse is too short; use a 20 µs pulse. The display’s SPI mode is 0 (CPOL=0, CPHA=0), so the library must match that. The HC-SR04 sensor has a 5V logic level, so a voltage divider is essential for 3.3V microcontrollers. The display’s reset pin can be tied to the microcontroller’s reset or to a GPIO, but a 10 µF capacitor on the reset line prevents glitches.

If the display shows garbage, reinitialize it with a hardware reset: pull the reset pin low for 10 ms, then high. The sensor’s readings may spike due to noise; add a 10 µF capacitor between VCC and GND on the sensor. The display’s SPI wires can pick up noise from the sensor’s ultrasonic bursts, so use shielded cables. The SSD1322’s command set includes a display on/off command, so ensure you call display.display() after drawing. The sensor’s maximum range is 400 cm, but the display’s bar graph can be scaled to 500 cm for safety.

Performance Metrics and Data Rates

The display’s SPI data rate is 10 Mbps, so a full screen update (2048 bytes) takes 1.6 ms at 10 MHz, but the library overhead adds 0.4 ms. The sensor’s pulseIn() function takes 30 ms for a 400 cm range, so the sensor is the bottleneck. The system’s throughput is 30 readings per second, with a latency of 33 ms from sensor to display. The display’s pixel write time is 0.1 µs per pixel, so a 256-pixel line takes 25.6 µs. The SSD1322’s internal RAM is 128 KB, but only 2 KB is used for the display buffer. The sensor’s trigger pulse width is 10 µs, and the echo pulse width ranges from 150 µs (2 cm) to 23 ms (400 cm).

The display’s contrast ratio of 2000:1 means black is truly black, so the bar graph has high visibility. The sensor’s accuracy is ±3 mm at 2 m, but the display’s numeric value is rounded to 1 cm, so the error is dominated by the sensor. The system’s power consumption is 0.18 W, so a 5V USB power bank can run it for 30 hours. The display’s viewing angle is 160 degrees, so the distance reading is visible from the side. The HC-SR04 sensor’s beam angle is 15 degrees, so the display shows the distance to the nearest object within that cone.

Plan your next trip

Get one deeply reported destination in your inbox every Friday — no listicles, no clickbait.

Join 180,000+ travelers