a. ioctl 命令说明
需要的头文件
#include <sys/ioctl.h>
格式:int ioctl(int fd, unsigned long request, …)
fd 必须被打开
第二个参数是一个依赖设备的请求代码
第三个参数是一个无类型的内存指针
返回值:成功为0,失败返回-1,并且设置errno
b. 如果要看头文件中的<linux/watchdog.h>,可以到linux板上cat /usr/include/linux/watchdog.h
也可以发送到虚拟机上看
scp /usr/include/linux/watchdog.h liu@192.168.0.112:/home/liu/Desktop/arm/
c. 相关的宏和函数
WDIOC_SETTIMEOUT _IOWR(WATCHDOG_IOCTL_BASE, 6, int)
WDIOC_KEEPALIVE _IOR(WATCHDOG_IOCTL_BASE, 5, int)
atoi: string to int
d. 需要输入的传参
watchdog文件位置,动作,时间
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/watchdog.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main(int argc,char *argv[]){
if(argc<2|strncmp("/dev/",argv[1],5))
exit(1);
int fd = open(argv[1],O_RDWR);
int sec = atoi(argv[3]);
if(fd<0){
perror("open error");
exit(1);
}
//
if(!strcmp(argv[2],"STO"))
{
if(ioctl(fd,WDIOC_SETTIMEOUT,&sec)<0)
perror("ioctl set timeout");
}else if(!strcmp(argv[2],"KA")){
if(ioctl(fd,WDIOC_KEEPALIVE)<0){
perror("ioctl keep alive");
}
sleep(2);
}
while(1);
close(fd);
return 0;
}
a. 说明
此处不涉及相关驱动(后续待学习),用文件读写的方式读取文件中的陀螺仪、加速度计及温度值;
涉及到分辨率的问题,所以需要转换,假设16位的寄存器,量程位+_2000,其分辨率为:
2
15
/
2000
2^{15}/2000
215/2000
b. 代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd = open(argv[1],O_RDWR);
if(fd<0)
{
perror("open error");
exit(1);
}
int ret;
int buf[7];
int x,y,z,ax,ay,az,temp;
float fx,fy,fz,fax,fay,faz,ftemp;
while (1){
if((ret = read(fd,buf,sizeof(buf)))==0)
{
lseek(fd,0,SEEK_SET);
x = buf[0];
y = buf[1];
z = buf[2];
ax = buf[3];
ay = buf[4];
az = buf[5];
temp = buf[6];
fx = (float)(x) / 16.4;
fy = (float)(y) / 16.4;
fz = (float)(z) / 16.4;
fax = (float)(ax) / 2048;
fay = (float)(ay) / 2048;
faz = (float)(az) / 2048;
ftemp = (float)(temp-25) / 326.8 + 25;
sleep(1);
printf("x = %5.2f,\ty = %5.2f,\tz = %5.2f\nax = %5.2f\tay = %5.2f\taz = %5.2f\ntemp = %5.2f\n",fx,fy,fz,fax,fay,faz,ftemp);
}
}
return 0;
}
c. 结果