linux驱动使用全局变量吗,linux驱动和应用问题

最近把按键驱动整合到一个大的程序中,老是出现没有按键,却自动触发按键的现象,调了挺久的,如下是单独运行时的代码:

#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,就可以不丢失键值,也就能正常使用了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值