LVGL➕编码器按键实现了一个数控电源,如何实现设置电压参数控件实现逐位调整电压,代码
时间: 2024-03-20 20:41:42 浏览: 118
以下是一个使用LVGL和编码器按键实现逐位调整电压的示例代码,其中使用了滑动条控件和标签控件来显示电压值:
```c
#include "lvgl/lvgl.h"
#include "encoder.h"
#define VOLTAGE_MIN 0
#define VOLTAGE_MAX 100
#define VOLTAGE_STEP 1
static lv_obj_t* slider;
static lv_obj_t* label;
static int voltage = 50;
void slider_event_handler(lv_obj_t* obj, lv_event_t event)
{
if (event == LV_EVENT_VALUE_CHANGED) {
voltage = lv_slider_get_value(slider);
char buf[16];
snprintf(buf, sizeof(buf), "Voltage: %d", voltage);
lv_label_set_text(label, buf);
}
}
void encoder_event_handler(int32_t direction)
{
int new_voltage = voltage + direction * VOLTAGE_STEP;
if (new_voltage < VOLTAGE_MIN) {
new_voltage = VOLTAGE_MIN;
} else if (new_voltage > VOLTAGE_MAX) {
new_voltage = VOLTAGE_MAX;
}
lv_slider_set_value(slider, new_voltage, LV_ANIM_ON);
voltage = new_voltage;
char buf[16];
snprintf(buf, sizeof(buf), "Voltage: %d", voltage);
lv_label_set_text(label, buf);
}
void setup_ui()
{
lv_theme_t* theme = lv_theme_night_init(0, NULL);
lv_theme_set_current(theme);
lv_obj_t* scr = lv_disp_get_scr_act(NULL);
slider = lv_slider_create(scr, NULL);
lv_obj_set_size(slider, lv_pct(70), lv_pct(70));
lv_obj_align(slider, NULL, LV_ALIGN_CENTER, 0, 0);
lv_slider_set_range(slider, VOLTAGE_MIN, VOLTAGE_MAX);
lv_slider_set_value(slider, voltage, LV_ANIM_ON);
lv_obj_set_event_cb(slider, slider_event_handler);
label = lv_label_create(scr, NULL);
lv_label_set_text(label, "Voltage: 50");
lv_obj_align(label, slider, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);
lv_obj_set_style_text_font(label, lv_theme_get_font_small(), 0);
encoder_init();
encoder_set_event_handler(encoder_event_handler);
}
int main()
{
lv_init();
setup_ui();
while (1) {
lv_task_handler();
delay_ms(5);
}
}
```
在以上示例代码中,`encoder.h`文件中包含了编码器按键的驱动代码和相关函数。`VOLTAGE_MIN`、`VOLTAGE_MAX`和`VOLTAGE_STEP`分别定义了电压控制的最小值、最大值和逐步调整步长。`slider_event_handler()`函数处理滑动条的事件,将滑动条的值更新为当前电压值,并将电压值显示在标签控件上。`encoder_event_handler()`函数处理编码器按键的事件,根据旋转方向计算新的电压值,并将其更新到滑动条和标签控件上。`setup_ui()`函数初始化界面,包括创建滑动条和标签控件,并将其添加到屏幕上。最后,在`main()`函数中调用`setup_ui()`函数,并在主循环中调用`lv_task_handler()`函数来处理LVGL事件循环。
阅读全文