#include <Wire.h>
#include <U8g2lib.h>
// 初始化U8g2对象
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
// 滚动函数
void scrollText(const char* text, const uint8_t* font, int speed) {
static int text_pos = 0; // 文本位置
static unsigned long previousMillis = 0; // 记录上一次更新的时间
static bool reset = true; // 用于控制是否需要重置文本位置
u8g2.setFont(font); // 设置字体
int text_width = u8g2.getStrWidth(text); // 计算文本宽度
int text_height = u8g2.getAscent() - u8g2.getDescent(); // 计算文本高度
if (reset) {
text_pos = u8g2.getDisplayWidth(); // 初始化文本位置到右边缘外
reset = false;
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= speed) {
previousMillis = currentMillis;
u8g2.clearBuffer(); // 清除显示缓冲区
int x = text_pos;
int y = (u8g2.getDisplayHeight() / 2) + (text_height / 2); // 垂直居中
u8g2.drawStr(x, y, text); // 绘制文本
text_pos-=map(constrain(speed,1,100),1,100,10,1);
// 检查文本是否完全离开屏幕左边缘
if (text_pos < -text_width) {
reset = true; // 设置标志,准备重新滚动
}
u8g2.sendBuffer(); // 发送缓冲区数据到显示屏
}
}
void setup() {
u8g2.begin();
u8g2.enableUTF8Print();
}
void loop() {
scrollText("你好!", u8g2_font_wqy12_t_gb2312, 80); // 调用滚动函数
}