超声波雷达测距

姜智浩 Lv4

开发板

Arduino UNO R3

接线

HC-SR04

VCC → 3.3V 或 5V
GND → GND
Trig → Arduino D9
Echo → Arduino D10

OLED (SSD1306 I2C)

VCC → 3.3V 或 5V
GND → GND
SCL → A5
SDA → A4

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define TRIG_PIN 9
#define ECHO_PIN 10
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);

Serial.begin(9600);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("OLED init failed"));
for(;;);
}
display.clearDisplay();
display.display();
}

float getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2; // 距离(厘米)
}

int posX = 0; // 用来在横向慢慢移动

void loop() {

// 绘制两边的参考线
display.drawLine(0, 0, 0, SCREEN_HEIGHT, WHITE); // 左边的距离线
display.drawLine(SCREEN_WIDTH - 1, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT, WHITE); // 右边的距离线
display.display();

float distance = getDistance(); // 单位 cm
Serial.print("Distance: ");
Serial.println(distance);

// 归一化距离(最多显示到60cm)
int r = map(min(distance, 60.0), 0, 60, SCREEN_HEIGHT - 1, 0); // 越远越上

display.drawPixel(posX, r, WHITE);
posX++;
if (posX >= SCREEN_WIDTH) {
posX = 0;
display.clearDisplay(); // 清除屏幕从头来
}
display.display();
delay(100); // 每秒10个点
}
  • Title: 超声波雷达测距
  • Author: 姜智浩
  • Created at : 2025-04-21 11:45:14
  • Updated at : 2025-04-21 10:08:13
  • Link: https://super-213.github.io/zhihaojiang.github.io/2025/04/21/20250421超声波雷达测距/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
超声波雷达测距