在EVB335x工控板上,既有按键又有LED灯,我们可以通过编程来用按键控制LED,如使用UP键来点亮LED,用DOWN键来熄灭LED;用LEFT键来打开蜂鸣器,用RIGHT键来关闭蜂鸣器等。 实现LED灯控制的程序如下,经编译、下载和运行即可见到预期效果。
完成编译
程序代码如下:
- #include <stdio.h>
- #include <linux/input.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/ioctl.h>
- #include <linux/types.h>
- typedef struct input_event INPUT_EVENT;
- #define DEVICE_NAME "/dev/input/event0"
- int main(int argc, char **argv)
- {
- int fd,fd1;
- int num;
- INPUT_EVENT event;
- char buf;
- fd1 = open("/sys/class/leds/user-led\:red/brightness",O_WRONLY);
- if(fd1<0){
- printf("Can not open led device.");
- return 0;
- }
- fd = open( DEVICE_NAME , O_RDONLY, 0);
- if (fd < 0)
- {
- perror("Can't open button device...\n");
- return 0;
- }
- printf("Keybutton test.....\n");
- while(1)
- {
- num = read(fd, &event, sizeof(INPUT_EVENT));
- if (sizeof(INPUT_EVENT) != num)
- {
- printf("read data error\n");
- return 0;
- }
- if(event.type == EV_KEY)
- {
- switch (event.code)
- {
- case KEY_UP:
- printf("UP keybutton,the code is: %d",event.code);
- buf = '1'; // LED on
- write(fd1,&buf,1);
- break;
- case KEY_DOWN:
- printf("DOWN keybutton,the code is: %d",event.code);
- buf = '0'; // LED off
- write(fd1,&buf,1);
- break;
- case KEY_LEFT:
- printf("LEFT keybutton,the code is: %d",event.code);
- break;
- case KEY_RIGHT:
- printf("RIGHT keybutton,the code is: %d",event.code);
- break;
- case KEY_ENTER:
- printf("ENTER keybutton,the code is: %d",event.code);
- break;
- case KEY_ESC:
- printf("ESC keybutton,the code is: %d",event.code);
- break;
- }
- // keybutton status
- if(event.value)
- {
- printf(" press down\n");
- }
- else
- {
- printf(" press up\n");
- }
- printf("\n");
- }
- }
- close(fd1);
- return 0;
- }
复制代码
|