搜索代码

Arduino Code and Video for HC-SR04 Ultrasonic Distance Sensor with SSD1306 OLED Display

Arduino Code and Video for HC-SR04 Ultrasonic Distance Sensor with SSD1306 OLED Display

In this tutorial, we will demonstrate how to use the HC-SR04 ultrasonic distance sensor in conjunction with the SSD1306 OLED display to visualize distance measurements. This project allows you to measure distances without needing a computer, making it ideal for various applications, including robotics. By the end of this project, you will have a functional setup that displays distance readings directly on the OLED screen.

How HC-SR04 ulrasonic sensor work
SSD1306 OLED display

As we proceed, I will explain the wiring connections required for both components and provide a walk-through of the Arduino code that integrates these components. This will help you understand how the sensor measures distance and how to output that data to the OLED display. For further clarification, you can refer to the video associated with this tutorial (in video at 00:00).

Hardware Explained

The main components of this project are the HC-SR04 ultrasonic distance sensor and the SSD1306 OLED display. The HC-SR04 operates using ultrasonic sound waves; it emits a sound pulse via the trigger pin and listens for the echo on the echo pin. By calculating the time taken for the sound to return, it can determine the distance to an object. This sensor is very effective for short-range measurements, typically up to 400-500 cm.

The SSD1306 OLED display is an I2C interface display that allows you to display text and graphics. It communicates via two pins: SDA (data line) and SCL (clock line). In our setup, these pins connect to specific Arduino pins, allowing for easy integration and control.

Datasheet Details

ManufacturerVarious
Part numberHC-SR04
Logic/IO voltage5 V
Supply voltage5 V
Output current (per channel)15 mA
Peak current (per channel)20 mA
PWM frequency guidanceN/A
Input logic thresholds0.3*Vcc to 0.7*Vcc
Voltage drop / RDS(on) / saturationN/A
Thermal limits0-70 °C
Package4-pin module
Notes / variantsStandard module

  • Ensure proper power supply (5 V) for both components.
  • Use pull-up resistors if necessary for I2C communication.
  • Keep trigger and echo lines short to avoid interference.
  • Check the orientation of the ultrasonic sensor for accurate readings.
  • Use a stable surface for the display to avoid mechanical vibrations.

Wiring Instructions

Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED
Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED

To connect the HC-SR04 ultrasonic sensor, start by wiring the VCC pin (usually red) to the 5V pin on the Arduino. Next, connect the GND pin (typically black or yellow) to one of the Arduino's GND pins. The trigger pin (often blue) should be wired to digital pin 12 on the Arduino, while the echo pin (usually green) should be connected to digital pin 11.

For the SSD1306 OLED display, connect the VCC pin to the 5V pin on the Arduino and the GND pin to GND. The SCL pin should be connected to pin A5 and the SDA pin to pin A4 on the Arduino. If you are using a different Arduino model that has dedicated I2C pins, connect the display directly to those pins instead.

Code Examples & Walkthrough

In the setup function, we initialize the display and the serial communication. The following excerpt demonstrates how the display is set up:

void setup() {
   Serial.begin(9600);// set serial monitor with 9600 baud
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D
}

Here, the display is initialized with the I2C address, allowing it to communicate with the Arduino. The serial monitor is also set up to print distance values.

In the main loop, we clear the display, measure the distance, and print it. The following code snippet shows how we handle the distance measurement:

void loop() {
   display.clearDisplay();
   String distance  = String(sonar.ping_cm());// get distance and convert it to string for display
   robojaxText(distance +"cm", 3, 20, 3, false);
   display.display();
   delay(50); // Wait 50ms between pings
}

This loop continuously measures the distance and updates the display with the current reading. The `robojaxText` function is used to display the text on the OLED screen.

Demonstration / What to Expect

When the setup is complete and the code is uploaded, you should see the distance displayed on the OLED screen in centimeters. As you move an object closer or farther from the sensor, the displayed value should change accordingly. Ensure that the sensor is oriented correctly and is not obstructed (in video at 02:30).

Video Timestamps

  • 00:00 - Introduction to the project
  • 01:15 - Wiring instructions
  • 02:30 - Code explanation
  • 04:00 - Demonstration of the sensor

图像

HC-SR04 ulrasonic sensor
HC-SR04 ulrasonic sensor
How HC-SR04 ulrasonic sensor work
How HC-SR04 ulrasonic sensor work
Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED
Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED
SSD1306 OLED display
SSD1306 OLED display
SSD1306 OLED display-dimensions
SSD1306 OLED display-dimensions
SSD1306_128x64_OLDE-4
SSD1306_128x64_OLDE-4
SSD1306 OLED display-back
SSD1306 OLED display-back
44-This is the Arduino code for an HC-SR04 ultrasonic distance sensor with an SSD1306 display.
语言: C++
/*
 * This is the Arduino code for the HC-SR04 Ultrasonic Distance Sensor with SSD1306 Display
 * to measure the distance using Arduino for a robotic car and other applications
 * Watch the video https://youtu.be/Pgx5fNF4Q6M
 * 
 * Written by Ahmad Shamshiri for Robojax Video
 * Date: December 21, 2017, in Ajax, Ontario, Canada
 * Permission granted to share this code given that this
 * note is kept with the code.
 * Disclaimer: this code is "AS IS" and for educational purposes only.
 * 
 */

/* Original Code 
   from https://github.com/adafruit/Adafruit_SSD1306
// https://playground.arduino.cc/Code/NewPing
 * Modified for Robojax video on December 21, 2017
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
*/
//// start of SSD1306 display 
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2


#define LOGO16_GLCD_HEIGHT 64 
#define LOGO16_GLCD_WIDTH  128 
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
  B00000001, B11000000,
  B00000001, B11000000,
  B00000011, B11100000,
  B11110011, B11100000,
  B11111110, B11111000,
  B01111110, B11111111,
  B00110011, B10011111,
  B00011111, B11111100,
  B00001101, B01110000,
  B00011011, B10100000,
  B00111111, B11100000,
  B00111111, B11110000,
  B01111100, B11110000,
  B01110000, B01110000,
  B00000000, B00110000 };

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
//// end of SSD1306 display 

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.



void setup() {
   Serial.begin(9600);// set serial monitor with 9600 baud
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
  
}// setup end


void loop() {
   display.clearDisplay();
  robojaxText("Distance", 3, 0, 2, false);
  String distance  = String(sonar.ping_cm());// get distance and convert it to string for display
  robojaxText(distance +"cm", 3, 20, 3, false);
    display.display();

  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

}// loop end


/*
 * robojaxText(String text, int x, int y,int size, boolean d)
 * text is the text string to be printed
 * x is the integer x position of text
 * y is the integer y position of text
 * size is the text size, 1, 2, 3 etc
 * d is either true or false.  Use true to display.
 */
void robojaxText(String text, int x, int y,int size, boolean d) {

  display.setTextSize(size);
  display.setTextColor(WHITE);
  display.setCursor(x,y);
  display.println(text);
  if(d){
    display.display();
  }

}

资源与参考

文件📁

没有可用的文件。