我想不依靠输入而是触摸屏实现
时间: 2024-03-03 21:47:30 浏览: 80
好的,如果要使用触摸屏输入三个点的坐标,可以使用 Linux 下的输入子系统(input subsystem)来实现。下面是修改后的代码:
```
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <linux/input.h> // 添加了输入子系统的头文件
int lcd_fd = 0;
int input_fd = 0; // 用来保存触摸屏的文件标识符
int OPEN_FIEL(char *pathname) {
int fd = open(pathname,O_RDWR);
if(fd == -1) {
perror("open file fault!\n");
}
return fd;
}
void CLOSE_FIEL(int fd) {
close(fd);
}
void Lcd_Draw_Point(int x,int y,unsigned int color) {
if(x<800 && x>=0 && y<480 && y>=0) {
int offset = 4*(y*800+x);
lseek(lcd_fd,offset,SEEK_SET);
write(lcd_fd,&color,4);
}
}
void Lcd_Clear(unsigned int color) {
unsigned int temp_arr[480*800] = {0};
for(int i =0;i<480*800;i++) {
temp_arr[i] = color;
}
write(lcd_fd,temp_arr,(480*800*4));
}
void Lcd_draw_line(int y,unsigned int color) {
for(int i =0;i<800;i++) {
Lcd_Draw_Point(i,y,color);
}
}
void Lcd_draw_triangle(int x1, int y1, int x2, int y2, int x3, int y3, unsigned int color) {
float area = fabs((x1 - x3) * (y2 - y1) - (x1 - x2) * (y3 - y1)) / 2.0;
int step_y = (y1 < y2) ? 1 : -1;
int min_y = y1;
int max_y = y3;
if (y2 < min_y) {
min_y = y2;
} else if (y2 > max_y) {
max_y = y2;
}
for (int y = min_y; y <= max_y; y += step_y) {
float x_left = x1 + (y - y1) * (x3 - x1) / (y3 - y1);
float x_right = x2 + (y - y2) * (x3 - x2) / (y3 - y2);
for (int x = x_left; x <= x_right; x++) {
Lcd_Draw_Point(x, y, color);
}
}
}
int main() {
lcd_fd = OPEN_FIEL("/dev/fb0");
Lcd_Clear(0xffffffff);
// 打开触摸屏
input_fd = OPEN_FIEL("/dev/input/event0");
// 读取三个点的坐标
int x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0;
int point_count = 0;
while (point_count < 3) {
struct input_event ev;
read(input_fd, &ev, sizeof(struct input_event));
if (ev.type == EV_ABS && ev.code == ABS_X) {
if (point_count == 0) {
x1 = ev.value;
} else if (point_count == 1) {
x2 = ev.value;
} else if (point_count == 2) {
x3 = ev.value;
}
} else if (ev.type == EV_ABS && ev.code == ABS_Y) {
if (point_count == 0) {
y1 = ev.value;
} else if (point_count == 1) {
y2 = ev.value;
} else if (point_count == 2) {
y3 = ev.value;
}
} else if (ev.type == EV_KEY && ev.code == BTN_TOUCH && ev.value == 0) {
point_count++;
}
}
// 绘制三角形
Lcd_draw_triangle(x1, y1, x2, y2, x3, y3, 0xffff0000);
CLOSE_FIEL(lcd_fd);
CLOSE_FIEL(input_fd); // 关闭触摸屏
return 0;
}
```
修改后的代码打开了触摸屏设备文件 `/dev/input/event0`,然后在一个循环中读取输入事件,当读取到 `ABS_X` 和 `ABS_Y` 类型的事件时,将事件的值保存到三个点的坐标变量中,当读取到 `BTN_TOUCH` 类型的事件时,说明一个点已经输入完成,将点的计数器 `point_count` 加 1。当 `point_count` 等于 3 时,就说明三个点都已经输入完成,此时调用 `Lcd_draw_triangle` 函数绘制三角形。注意,触摸屏的坐标值可能会超出屏幕的范围,因此需要在绘制三角形前添加检查坐标值是否在有效范围内的代码。
阅读全文