mini2440应用例程学习(二)—— buttons - 11hwu2


二、 buttons_test.c 源码文件解读分析: 
1 ) buttons_test.c 源代码及注释:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
int main(void)
{
  int buttons_fd;
  char buttons[6] = {'0', '0', '0', '0', '0', '0'}; //按键状态初始值
  buttons_fd = open("/dev/buttons", 0);	 //打开buttons设备,返回设备文件描述符
  if (buttons_fd < 0) {
    perror("open device buttons");
    exit(1);    //打开失败出错退出
  }
  for (;;) {  //死循环
    char current_buttons[6];	 //存放当前按键状态值
    int count_of_changed_key;  
    int i;
    if (read(buttons_fd, current_buttons, sizeof current_buttons) != sizeof current_buttons) { //读按键值
      perror("read buttons:");
      exit(1);		//若从buttons设备读取的字符数不等于6个字节则出错退出
    }
    for (i = 0, count_of_changed_key = 0; i < sizeof buttons / sizeof buttons[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判断
      }
    }
    if (count_of_changed_key) {
      printf("\n");
    }
         
         
  }
  close(buttons_fd);
  return 0;
}
( 2 )分析程序时遇到的主要疑问如下:        
      在读取设备后获得当前按键情况,对比发现有改变则使用以下语句输出相关信息:
printf("%skey %d is %s", count_of_changed_key? ", ": "", i+1, buttons[i] == '0' ? "up" : "down");
该 语句中需要输出的部分都是用一个选择表达式来确定的。第一部分当out_of_changed_key的值不为0时则对应输出 ", ",否则输出空字符串;第二部分为按键序号;第三部分当buttons中的数值为0时输出up否则输出down。最困扰的地方是第一部分,我当时是这样想 的:当有按键按下,out_of_changed_key的值为0,输出空字符串,之后out_of_changed_key自加1,后来应该会为真吧, 那就应该输出","了,实际结果却不是这样的。其实后来想想还是因为忽略了一个地方,该语句处在一个for死循环中,每循环一次都会初始化为0。(个人觉 得count_of_changed_key? ", ": ""这条表达式没有什么意义,因为根本就不会有输出逗号的机会。搞不懂程序开发者当时的思路) 
参考:     
    ① mini2440用户手册     
    ②源码来自mini2440开发板自带光盘
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值