最近把按键驱动整合到一个大的程序中,老是出现没有按键,却自动触发按键的现象,调了挺久的,如下是单独运行时的代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
char buttons[10]={'0','0','0','0','0','0','0','0','0','0'};
int ret;
int j;
int main(void)
{
int buttons_fd;
buttons_fd = open("/dev/buttons",0);
if(buttons_fd < 0)
{
perror("open device buttons");
exit(1);
}
else
{
printf("open button device ok: buttons_fd = %d\n");
}
while(1)
{
char current_buttons[10];
int count_of_changed_key;
int i;
//read(buttons_fd,current_buttons,sizeof current_buttons);
if(read(buttons_fd,current_buttons,sizeof current_buttons)!=sizeof current_buttons)
{
perror("read buttons:\n");
exit(1);
}
for(i=0,count_of_changed_key=0;i
{
if(buttons[i]!=current_buttons[i])
{
buttons[i]=current_buttons[i];
printf("%skey %d is %s",count_of_changed_key?",":"",i 1,buttons[i]=='0'?"up":"down");
count_of_changed_key ;
}
}
if(count_of_changed_key)
{
printf("\n");
}
}
close(buttons_fd);
return 0;
}
这个在单独运行时,可以做到有按键按下时,打印keyX is up/down,加入大程序中就不行了,没有按键按下也会打印keyX is up/down,而且有一个非常有趣的现象就是打印的keyX越来越小。
经过考虑,因为linux下驱动和应用层通讯,应用层只能读驱动层,但是驱动层读不了应用层的数据,所以我在驱动中是这么做的,当按键按下,我把该键值置为‘1’,然后等待应用层来读,当按键弹起,则把键值置为‘0’,这样只需要判断这一次和上一次的键值是否相同就知道是否有键按下。
但是因为把这个封装成函数,就出现了一个问题,当跳出这个函数后,重新进入该函数扫描键值,button数组将被初始化,导致之前存放的键值丢失,从而就出现了就算没有按键然后又信息打印。我们解决方法是把button数组作为全局变量或者加上static,就可以不丢失键值,也就能正常使用了。