在物联网和嵌入式开发中,ESP32 和 OLED 显示屏的结合是非常常见的应用场景之一。本文将详细介绍如何使用 ESP32 和 OLED 显示屏实现信息滚动展示功能。我们将从硬件连接、软件配置以及代码实现等多个方面进行深入解析。
ESP32 和 OLED 显示屏通过 I2C 协议通信,具体的引脚连接如下:
确保连接正确后,可以开始软件部分的配置。
文件 -> 首选项
,在“附加开发板管理器网址”中添加以下链接:
https://dl.espressif.com/dl/package_esp32_index.json
工具 -> 开发板 -> 开发板管理器
,搜索并安装 ESP32
。工具 -> 管理库
,搜索并安装上述两个库。以下是实现信息滚动展示的核心代码:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
String message = "Welcome to the world of IoT with ESP32 and OLED!";
int x = 0; // Starting position of the text on the screen
int y = 0; // Vertical position of the text
void setup() {
Serial.begin(115200);
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for most OLEDs
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Set text color to white
display.setCursor(0, 0); // Start at top-left corner
display.display();
}
void loop() {
display.clearDisplay(); // Clear the display buffer
// Draw the scrolling text
display.setCursor(x, y);
display.println(message);
// Update the position of the text
x--;
if (x < -message.length() * 6) { // Reset position when text goes off-screen
x = SCREEN_WIDTH;
}
display.display(); // Send the buffer to the display
delay(100); // Adjust speed of scrolling
}
初始化 OLED 显示屏
display.begin()
方法初始化 OLED 显示屏,指定 I2C 地址(通常为 0x3C
)。滚动逻辑
display.setCursor(x, y)
设置文本的起始位置。x
坐标逐渐减小以实现向左滚动的效果。x < -message.length() * 6
),重置 x
坐标到屏幕右侧。刷新显示
display.display()
方法将缓冲区内容更新到 OLED 屏幕上。delay()
控制滚动速度。可以通过 WiFi 或蓝牙模块让 ESP32 获取动态信息(如天气、时间等),并在 OLED 上滚动展示。例如:
如果需要在多行上实现滚动效果,可以通过调整 y
坐标实现多行文字的滚动。
以下是实现滚动展示的主要流程图:
flowchart TD A[初始化] --> B[设置显示屏参数] B --> C[清空屏幕] C --> D{是否需要滚动} D --是--> E[绘制文本] E --> F[更新坐标] F --> G[刷新屏幕] G --> H[延时] H --> D D --否--> I[结束]