mini2440应用例程学习(二)—— buttons
硬件:mini2440开发板
程序功能描述:
在终端输入buttons(位于/usr/bin/目录)执行该程序,按下按键进行测试,显示结果如下
在终端输入buttons(位于/usr/bin/目录)执行该程序,按下按键进行测试,显示结果如下
注:down表示按下,up表示弹起
二、buttons_test.c源码文件解读分析:
(1)buttons_test.c源代码及注释:
在读取设备后获得当前按键情况,对比发现有改变则使用以下语句输出相关信息:
该 语句中需要输出的部分都是用一个选择表达式来确定的。第一部分当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开发板自带光盘
(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");
参考:
①mini2440用户手册
②源码来自mini2440开发板自带光盘

浙公网安备 33010602011771号