模拟智能家居项目Part7

来自于两周的粤嵌实习,主要是网络编程和线程控制部分比较重要,贯穿了常用的C语言用法,值得做一个复盘,共有11个部分,本节介绍了模拟触摸屏事件。

Posted by LJJ on July 2, 2020

模拟智能家居项目

基本原理

  • 输入事件

    • 在linux系统下,输入设备(鼠标,键盘,触摸屏。。。)输入的信息,系统把这些信息处理成 事件并且用一个结构体表示

      struct input_event {
      			struct timeval time;		//输入事件发生的时间
          				
      			__u16 type;					//输入事件的类型
      				type == EV_KEY;按键事件(键盘)        
      				type == EV_ABS;absolution //绝对事件 
      			__u16 code;		//根据这个type的不同,code的含义也不一样
      				type == EV_KEY;		
      					code就为按键的键值 
      						KEY_Q
      						KEY_W
      						...
      				type == EV_ABS;
      					code ==ABS_X 表示x事件 
      					code ==ABS_Y 表示y事件
          						
      			__s32 value; //根据type的不同,value的含义也不同
      				type == EV_KEY;
      				code == KEY_Q;
      					value 就为按键的状态 
      						1	按下去
      						0	弹起来
          						
      				type == EV_ABS;
      				code == ABS_X;
      					value 就为相应的x方向的坐标
      				code == ABS_Y;
      					value 就为相应的y方向的坐标
      		};
      
  • 对触摸屏事件的获取(获取坐标)

    • 打开触摸屏
    • 读取信息
    • 分析信息
    • 打印信息
  • 触摸屏对应的文件位置/dev/ubuntu_event

  • 编写代码的时候要这个头文件#include<linux/input.h>

任务要求

  • 结合状态图显示代码 把触摸屏获取事件的代码整合进去
  • 首先显示的是关闭状态的状态图
  • 当你点击一下触摸屏的时候这个状态图进行切换 关-》开

代码实现

  • 鼠标点击获取坐标部分

    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include<linux/input.h>	
      
      
    void touch_event(int fd)
    {
    	//2.读取信息
    	struct input_event ev;
    	int x = 0,y = 0;
    	while(1)
    	{
    		int ret = read(fd, &ev, sizeof(ev));
    		if(ret == -1)
    		{
    			perror("read touch_fd error\n");
    		}
    		//printf("read byte is %d\n",ret);
    		if(ret != sizeof(ev))
    		{
    			continue;
    		}
    		//3.分析信息
    		//printf("ev.type = %d, ev.code = %d, ev.value = %d\n",ev.type,ev.code,ev.value);
      		
      	
    		if(ev.type == EV_ABS)		//触摸屏事件
    		{
    			if(ev.code == ABS_X)  //x事件
    			{
    				x = ev.value;	//代表横坐标
    			}
    			else if(ev.code == ABS_Y)  //y事件
    			{
    				y = ev.value;		//代表纵坐标
    				//4.打印信息
    				printf("(%d,%d)\n",x,y);
      				
    			}
      			
      			
    		}
    	}
      	
    	//5.关闭触摸屏
    	close(fd);
    }
      
    int main()
    {
    	//1.打开触摸屏
    	int touch_fd = open("/dev/ubuntu_event",O_RDWR);
    	if(touch_fd < 0)
    	{
    		perror("open touch_fd error\n");
    	}
      	
    	touch_event(touch_fd);
      	
      
    	return 0;
    }