#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK |
U8G_I2C_OPT_FAST);
int progress = 0;
const int buttonPin = 2;
const int ledPin = 13;
//
按钮连接到
D2
引脚
// LED
连接到
D13
引脚(板载
LED
)
bool isButtonPressed = false; //
按钮是否被按下
bool isLoading = false;
bool isLoaded = false;
void setup() {
//
是否正在加载
//
是否加载完成
pinMode(buttonPin, INPUT_PULLUP); //
设置按钮引脚为输⼊上拉
//
设置
LED
引脚为输出
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
u8g.setFont(u8g_font_tpssb);
u8g.setColorIndex(1);
}
void loop() {
//
检测按钮状态(消抖处理)
//
初始
LED
熄灭
static int lastButtonState = HIGH;
static unsigned long lastDebounceTime = 0;
static const unsigned long debounceDelay = 50; //
消抖延时
int currentButtonState = digitalRead(buttonPin);
//
检测按钮状态变化
if (currentButtonState != lastButtonState) {
lastDebounceTime = millis();
}
//
确认按钮状态稳定
if ((millis() - lastDebounceTime) > debounceDelay) {
if (currentButtonState != buttonPin) {
//
按钮状态确实发⽣了变化
if (currentButtonState == LOW) {
//
按钮被按下(低电平触发,因为是上拉输⼊)
if (!isLoading && !isLoaded) {
//
仅当不在加载中且未完成时,才开始新的加载
isButtonPressed = true;
isLoading = true;
isLoaded = false;
progress = 0; //
重置进度条
}
}
}
}
lastButtonState = currentButtonState;
//
根据当前状态显⽰不同内容
u8g.firstPage();
do {
if (isLoading) {
//
正在加载:显⽰进度条
u8g.drawStr(25, 30, "Loading...");
u8g.drawFrame(0, 40, 128, 20);
u8g.drawBox(10, 45, progress, 10);
//
更新进度(增加延时,减慢加载速度)
if (progress < 108) {
progress++;
delay(50); //
每更新⼀次进度条,延时
50
毫秒(原代码⽆此延时)
} else {
//
加载完成
isLoading = false;
isLoaded = true;
}
} else if (isLoaded) {
//
加载完成:显⽰完成信息,点亮
LED
u8g.drawStr(25, 30, "Load Complete!");
digitalWrite(ledPin, HIGH); //
点亮
LED
} else {
//
初始状态:等待按钮按下
u8g.drawStr(25, 30, "Press Button");
u8g.drawStr(25, 50, "to Start");
digitalWrite(ledPin, LOW); //
确保
LED
熄灭
}
} while (u8g.nextPage());
//
原延时(控制整体刷新频率,保持不变)
delay(10);
}