# 嵌入式 Linux 学习记录:从 input_event 解析触摸屏坐标

一、练习目标

本次练习的目标是在嵌入式 Linux 开发板上读取触摸屏输入事件,并将原始 input_event 数据解析成触摸坐标 xy

前面已经确认触摸屏设备为:

/dev/input/event0

判断依据来自:

cat /proc/bus/input/devices

其中触摸屏对应的信息为:

Name="ft5x0x"
Handlers=mouse0 event0

因此程序中打开的触摸屏设备路径为:

"/dev/input/event0"

二、input_event 结构体

Linux 输入子系统使用 struct input_event 表示一条输入事件。当前主要关注三个字段:

type   :事件类型
code   :事件编号
value  :事件值

触摸屏测试时,终端输出类似:

type = 3, code = 0, value = 175
type = 3, code = 1, value = 326
type = 1, code = 330, value = 1
type = 0, code = 0, value = 0
type = 1, code = 330, value = 0

其中:

type = 3:EV_ABS,绝对坐标事件
code = 0:ABS_X,X 坐标
code = 1:ABS_Y,Y 坐标
type = 1:EV_KEY,按键类事件
code = 330:BTN_TOUCH,触摸按键
value = 1:按下
value = 0:松开

三、touch_get_xy 函数设计

为了获取一次触摸坐标,封装了函数:

int touch_get_xy(const char *event_path, int *x, int *y);

其中:

event_path:触摸屏输入设备路径
x:用于保存 X 坐标
y:用于保存 Y 坐标
返回值 0 表示成功,-1 表示失败

这里 xy 使用指针,是因为函数返回值已经用于表示成功或失败,坐标需要通过指针参数带回调用者。

核心逻辑如下:

if (ev.type == EV_ABS && ev.code == ABS_X)
{
    *x = ev.value;
}
else if (ev.type == EV_ABS && ev.code == ABS_Y)
{
    *y = ev.value;
}
else if (ev.type == EV_KEY && ev.code == BTN_TOUCH && ev.value == 0)
{
    close(touch_fd);
    return 0;
}

含义是:

读到 ABS_X 事件时,保存 X 坐标
读到 ABS_Y 事件时,保存 Y 坐标
检测到 BTN_TOUCH 松开时,认为一次触摸结束,返回坐标

四、坐标测试结果

测试程序连续点击屏幕,可以输出多组坐标:

x = 175, y = 326
x = 214, y = 321
x = 134, y = 192
x = 239, y = 360
x = 413, y = 276

这说明程序已经可以从 /dev/input/event0 中读取触摸事件,并解析出触摸点坐标。

五、区域判断测试

开发板 LCD 分辨率为 800×480,因此可以用 X 坐标判断左半屏和右半屏:

if (x < 400)
{
    printf("left area\n");
}
else
{
    printf("right area\n");
}

测试结果:

x = 485, y = 403
right area

x = 709, y = 385
right area

x = 175, y = 326
left area

说明触摸坐标已经可以用于简单的区域判断。

六、总结

本次练习完成了触摸屏输入模块的基础封装,实现了从原始 input_event 到触摸坐标的解析。

当前已经掌握:

1. 通过 /proc/bus/input/devices 确认触摸屏 event 设备
2. 使用 open/read 读取 /dev/input/event0
3. 理解 struct input_event 中 type、code、value 的作用
4. 使用 EV_ABS、ABS_X、ABS_Y 解析坐标
5. 使用 EV_KEY、BTN_TOUCH 判断按下和松开
6. 根据 X 坐标判断左半屏和右半屏

下一步计划是将触摸坐标与 LCD/BMP 显示模块结合,实现点击左半屏显示第一张图片,点击右半屏显示第二张图片。

posted @ 2026-06-03 17:25  wwwicjh  阅读(31)  评论(0)    收藏  举报