lvgl 简易计算器
时间: 2023-10-11 13:14:17 浏览: 232
简易计算器
你想了解如何使用 LVGL 创建一个简易计算器吗?下面是一个使用 LVGL 创建简易计算器的示例代码:
```c
#include <lvgl.h>
lv_obj_t *textbox;
lv_obj_t *label;
lv_obj_t *btns[16];
void btn_click_event(lv_obj_t *btn, lv_event_t event)
{
if (event == LV_EVENT_CLICKED) {
char txt[2];
lv_btn_get_text(btn, txt);
if (txt[0] == '=') {
char result[16];
lv_textarea_get_text(textbox, result, sizeof(result));
int num1, num2;
char op;
sscanf(result, "%d %c %d", &num1, &op, &num2);
int res;
switch (op) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
res = 0;
break;
}
sprintf(result, "%d", res);
lv_label_set_text(label, result);
} else {
lv_textarea_add_char(textbox, txt[0]);
}
}
}
void create_calculator(lv_obj_t *parent)
{
lv_obj_t *container = lv_cont_create(parent, NULL);
lv_obj_set_style_local_bg_color(container, LV_CONT_PART_MAIN, LV_COLOR_WHITE);
textbox = lv_textarea_create(container, NULL);
lv_textarea_set_one_line(textbox, true);
lv_obj_align(textbox, container, LV_ALIGN_IN_TOP_MID, 0, 10);
label = lv_label_create(container, NULL);
lv_obj_align(label, textbox, LV_ALIGN_OUT_BOTTOM_MID, 0, 10);
const char *btn_labels[16] = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (int i = 0; i < 16; i++) {
btns[i] = lv_btn_create(container, NULL);
lv_obj_set_event_cb(btns[i], btn_click_event);
lv_obj_t *label = lv_label_create(btns[i], NULL);
lv_label_set_text(label, btn_labels[i]);
}
lv_obj_set_pos(btns[0], 0, 100);
lv_obj_set_pos(btns[1], 80, 100);
lv_obj_set_pos(btns[2], 160, 100);
lv_obj_set_pos(btns[3], 240, 100);
lv_obj_set_pos(btns[4], 0, 180);
lv_obj_set_pos(btns[5], 80, 180);
lv_obj_set_pos(btns[6], 160, 180);
lv_obj_set_pos(btns[7], 240, 180);
lv_obj_set_pos(btns[8], 0, 260);
lv_obj_set_pos(btns[9], 80, 260);
lv_obj_set_pos(btns[10], 160, 260);
lv_obj_set_pos(btns[11], 240, 260);
lv_obj_set_pos(btns[12], 0, 340);
lv_obj_set_pos(btns[13], 80, 340);
lv_obj_set_pos(btns[14], 160, 340);
lv_obj_set_pos(btns[15], 240, 340);
}
int main(void)
{
lv_init();
lv_obj_t *scr = lv_scr_act();
create_calculator(scr);
while (1) {
lv_task_handler();
usleep(5000);
}
return 0;
}
```
这个示例代码使用了 LVGL 库来创建一个简易计算器。它使用了文本框、标签和按钮来实现计算器的功能。你可以根据需要进行修改和扩展。记得在编译和运行代码之前,确保已经正确配置好了 LVGL 库。
希望这可以帮助到你!如果还有其他问题,请随时提问。
阅读全文