#include <U8g2lib.h>
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, SCL, SDA, U8X8_PIN_NONE);
// 屏幕尺寸
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
//滑动窗口移动速度
#define SLIDE_PIXEL_MAX 10
const char* configs[] = {
"1 AAAAAAA",
"2 BBBBBBBB",
"3 CCCCCCCC",
"4 DDDDDDDD",
"5 EEEEEEEE",
"6 FFFFFFFF",
"7 GGG",
"8 HHHHHH",
"9 IIII",
};
int currentPage = 0; // 当前页面
int selectedConfig = 0; // 当前选中配置项
int numConfigs = sizeof(configs) / sizeof(configs[0]); // 配置项个数
int frameYPos = 20; // 动效框的当前位置
int targetYPos = 20; // 动效框的目标位置
void setup() {
u8g2.begin(); // 初始化U8g2库
Serial.begin(115200);
Serial.println("Start");
pinMode(5, INPUT_PULLUP); // 按键上
pinMode(4, INPUT_PULLUP); // 按键下
}
void loop() {
UI_Config_Page();
delay(50); // 延迟以避免按键抖动
}
void UI_Draw_Title(byte y, const char *title) {
// 设置标题字体
u8g2.setFont(u8g2_font_ncenB08_tr);
// 获取字符串宽度
int strWidth = u8g2.getStrWidth(title);
// 计算水平居中位置
int centerX = (SCREEN_WIDTH - strWidth) / 2;
// 在计算出的居中位置绘制字符串
u8g2.drawStr(centerX, y, title);
}
void UI_Config_Page() {
u8g2.clearBuffer();
UI_Draw_Title(10, "System Cfg");
// 根据屏幕尺寸和字体自适应计算每个配置项的高度
int itemHeight = u8g2.getMaxCharHeight();
// 根据屏幕尺寸和配置项高度计算每页最大显示项数
int maxItemsPerPage = (SCREEN_HEIGHT - 30) / itemHeight;
// 根据当前页码计算起始和终止的配置项
int startItem = currentPage * maxItemsPerPage;
int endItem = min(startItem + maxItemsPerPage, numConfigs);
// 显示配置项
for (int i = startItem; i < endItem; i++) {
int yPos = 20 + (i - startItem) * itemHeight;
u8g2.drawStr(0, yPos, configs[i]);
Serial.print("Draw index:");
Serial.println(i);
}
// 动效框滑动效果
if (frameYPos < targetYPos) {
frameYPos += min(SLIDE_PIXEL_MAX, targetYPos - frameYPos); // 向下滑动
} else if (frameYPos > targetYPos) {
frameYPos -= min(SLIDE_PIXEL_MAX, frameYPos - targetYPos); // 向上滑动
}
u8g2.drawFrame(0, frameYPos - itemHeight + 2, SCREEN_WIDTH, itemHeight);
u8g2.sendBuffer();
// 检测按键操作
if (digitalRead(4) == LOW) { // 向上按键
if (selectedConfig > 0) {
selectedConfig--;
if (selectedConfig < currentPage * maxItemsPerPage) {
currentPage--;
}
targetYPos = 20 + (selectedConfig % maxItemsPerPage) * itemHeight;
}
delay(200); // 延迟以避免按键抖动
}
if (digitalRead(5) == LOW) { // 向下按键
if (selectedConfig < numConfigs - 1) {
selectedConfig++;
if (selectedConfig >= (currentPage + 1) * maxItemsPerPage) {
currentPage++;
}
targetYPos = 20 + (selectedConfig % maxItemsPerPage) * itemHeight;
}
delay(200); // 延迟以避免按键抖动
}
}