//应用程序实现的方法有两种:
(平时实验就是积累项目经验, 到真正项目时就可以轻装上阵了,不要以为会了就不动手做实验)
1>用 select系统调用监控 驱动是否可读 如果有按键按下 表示可读 就调用 read函数读取数据(按键值 是那个按键按下)然后再执行相应的操作(好像有点多余,因为本来测试的应用程序就在轮询,多线程除外!)
2>在按键驱动中增加异步通知的方法,按键按下时驱动发送一个信号给应用程序,应用程序收到按下信号再去控制灯亮
3>还有一种方式就是,在应用程序中一直read按键当读到按下,就亮灯。
//led_key_app3.c 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <sys/ioctl.h> 5 #include <sys/types.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 #include <sys/select.h> 9 #include <sys/time.h> 10 #include <errno.h> 11 #include<string.h> 12 13 void check_key(int buttons_fd, int leds_fd); 14 15 int main(void) 16 { 17 int buttons_fd; 18 int leds_fd; 19 //int save = 0; 20 //int j = 0; 21 buttons_fd = open("/dev/button_by_hui", 0); 22 if (buttons_fd < 0) { 23 perror("open device buttons"); 24 exit(1); 25 } 26 27 leds_fd = open("/dev/leds_by_hui",0); 28 if(leds_fd < 0) { 29 perror("open device leds"); 30 exit(1); 31 } 32 ioctl(leds_fd, 0, 0); //初始化led 为灭 33 34 while (1) { 35 check_key(buttons_fd, leds_fd); 36 }//end of while(1) 37 38 close(buttons_fd); 39 close(leds_fd); 40 return 0; 41 } 42 43 void check_key(int buttons_fd, int leds_fd) 44 { 45 static char save[6]={'0','0','0','0','0','0'}; 46 static char current_buttons[6] = {'0', '0', '0', '0', '0', '0'}; 47 int i; 48 static unsigned char no_off; 49 if (read(buttons_fd, current_buttons, sizeof current_buttons) != sizeof current_buttons) { 50 perror("read buttons error\n"); 51 exit(1); 52 } 53 if ((strncmp(save, current_buttons, 6)) != 0 ){ 54 for ( i = 0; i < sizeof (current_buttons) / sizeof (current_buttons[0]); i++) { 55 if (save[i] != current_buttons[i]) { 56 printf("The %d key is pressed!(no_off=%d)\n", i+1, no_off); 57 ioctl(leds_fd, (~no_off)&1, i); 58 } 59 }// end of for 60 no_off = ~no_off; 61 } 62 }