esp32s3连接hcsr04超声波模块实现实时测距 并且在ST7789屏幕上显示距离使用Visual Studio Code编程
时间: 2025-06-24 09:39:26 浏览: 18
### 使用 Visual Studio Code 为 ESP32-S3 编程,连接 HC-SR04 进行实时测距并将结果显示在 ST7789 屏幕上
#### 系统概述
本方案旨在利用 ESP32-S3 的强大处理能力,配合 HC-SR04 超声波模块完成距离测量,并通过 ST7789 彩色显示屏动态显示结果。以下是完整的实现方法和代码示例。
---
#### 开发环境准备
1. 安装 **PlatformIO** 插件到 Visual Studio Code。
2. 配置 `platformio.ini` 文件以支持 ESP32-S3 和必要的库:
```ini
[env:esp32-s3-devkitc-1]
platform = espressif32
board = esp32s3-devkitc-1
framework = arduino
monitor_speed = 115200
lib_deps =
Adafruit-ST7789-Library @ ^1.6.1
ArduinoJson @ ^6.19.0
```
---
#### 示例代码
以下是一个完整的代码示例,用于实现 HC-SR04 测距并通过 ST7789 显示:
```cpp
#include <Arduino.h>
#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
// Define pins for HC-SR04 and ST7789
#define TRIGGER_PIN 13 // Trigger pin of HC-SR04
#define ECHO_PIN 14 // Echo pin of HC-SR04
#define TFT_CS 5 // Chip Select pin for ST7789
#define TFT_DC 18 // Data/Command pin for ST7789
#define TFT_RST 19 // Reset pin for ST7789
// Initialize the ST7789 screen
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
void setup() {
Serial.begin(115200); // Start serial communication
pinMode(TRIGGER_PIN, OUTPUT); // Set trigger pin as output
pinMode(ECHO_PIN, INPUT); // Set echo pin as input
// Initialize the ST7789 display
tft.init(240, 240); // Init ST7789 with width=height=240 pixels
tft.setRotation(1); // Rotate display orientation if needed
tft.fillScreen(ST77XX_BLACK); // Clear the screen by filling it black
drawText("Starting...", 50, 100, ST77XX_GREEN);
}
void loop() {
long duration;
float distance;
// Send a 10us pulse to the trigger pin
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the echo signal
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance based on speed of sound (340 m/s)
distance = duration * 0.034 / 2; // Distance in centimeters
// Display results both via serial and on the ST7789 screen
Serial.printf("Distance: %.2f cm\n", distance);
updateDisplay(distance);
delay(500); // Wait before next measurement
}
/**
* Function to clear previous text and redraw new content.
*/
void drawText(const char* text, uint16_t x, uint16_t y, uint16_t color) {
tft.setCursor(x, y);
tft.setTextColor(color);
tft.setTextSize(2);
tft.setTextWrap(false);
tft.print(text);
}
/**
* Update the ST7789 display with current distance information.
*/
void updateDisplay(float distance) {
tft.fillScreen(ST77XX_BLACK); // Clear the screen first
String distStr = String(distance, 2); // Format distance to two decimal places
distStr += " cm"; // Append unit label
// Center-align the text vertically and horizontally
uint16_t strWidth = tft.textWidth(distStr.c_str());
uint16_t strHeight = tft.fontHeight();
uint16_t centerX = (tft.width() - strWidth) / 2;
uint16_t centerY = (tft.height() - strHeight) / 2;
drawText(distStr.c_str(), centerX, centerY, ST77XX_WHITE);
}
```
---
#### 功能详解
1. **HC-SR04 距离测量**
- 使用 `pulseIn()` 函数检测回响信号的高电平持续时间[^1]。
- 基于声音传播速度 \(v = 340 \text{m/s}\),计算实际距离公式为:\[ \text{distance} = \frac{\text{duration} \times v}{2 \times 1e6} \]
2. **ST7789 显示屏管理**
- 初始化屏幕分辨率设为 \(240 \times 240\) 像素。
- 更新界面时先清屏 (`fillScreen`),再绘制新内容以保持画面整洁[^3]。
3. **优化用户体验**
- 添加延迟防止频繁刷新造成视觉疲劳。
- 文字居中对齐提升美观度。
---
#### 注意事项
- 确保硬件接线无误,尤其是电源电压匹配问题(HC-SR04 推荐使用 \(5V\) 输入)。
- 若发现测量误差较大,可能源于外部干扰或超声波反射面不平整[^2]。
---
###
阅读全文
相关推荐


















