編程步驟
(一)打開設(shè)備
#define ICM20607_DEV "/dev/icm20607"
fd = open(ICM20607_DEV, O_RDWR);
if(fd < 0) {
printf("can't open file %srn", ICM20607_DEV);
return -1;
}
宏定義板卡上的傳感器節(jié)點(diǎn)為/dev/icm20607;
使用open()打開傳感器,如果錯(cuò)誤返回-1;
(二)讀取數(shù)據(jù)
ret = read(fd, databuf, sizeof(databuf));
使用read將設(shè)備中的數(shù)據(jù)讀取出來放入datebuf中。
(三)定義數(shù)組成員
gyro_x_adc = databuf[0];
gyro_y_adc = databuf[1];
gyro_z_adc = databuf[2];
accel_x_adc = databuf[3];
accel_y_adc = databuf[4];
accel_z_adc = databuf[5];
temp_adc = databuf[6];
把x、y、z軸的角速度,x、y、z軸的加速度和溫度一共7個(gè)元素填入數(shù)組內(nèi),這些成員是從設(shè)備中讀取出來的數(shù)據(jù)。
(四)數(shù)據(jù)類型轉(zhuǎn)換
gyro_x_act = (float)(gyro_x_adc) / 16.4;
gyro_y_act = (float)(gyro_y_adc) / 16.4;
gyro_z_act = (float)(gyro_z_adc) / 16.4;
accel_x_act = (float)(accel_x_adc) / 2048;
accel_y_act = (float)(accel_y_adc) / 2048;
accel_z_act = (float)(accel_z_adc) / 2048;
temp_act = ((float)(temp_adc) - 25 ) / 326.8 + 25;
因?yàn)榻撬俣?、加速度和溫度這些都不能用常量表示,所以需要給他們轉(zhuǎn)換成浮點(diǎn)量,并做相應(yīng)數(shù)學(xué)計(jì)算,以轉(zhuǎn)換成我們可讀的數(shù)據(jù)。
(五)關(guān)閉設(shè)備
close(fd);
詳細(xì)代碼
elf1_cmd_icm20607:
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "sys/ioctl.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include <poll.h>
#include <sys/select.h>
#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#define ICM20607_DEV "/dev/icm20607"
int main(int argc, char *argv[])
{
int fd;
signed int databuf[7];
unsigned char data[14];
signed int gyro_x_adc, gyro_y_adc, gyro_z_adc;
signed int accel_x_adc, accel_y_adc, accel_z_adc;
signed int temp_adc;
float gyro_x_act, gyro_y_act, gyro_z_act;
float accel_x_act, accel_y_act, accel_z_act;
float temp_act;
int ret = 0;
fd = open(ICM20607_DEV, O_RDWR);
if(fd < 0) {
printf("can't open file %srn", ICM20607_DEV);
return -1;
}
while (1) {
ret = read(fd, databuf, sizeof(databuf));
if(ret == 0) { /* ?????? */
gyro_x_adc = databuf[0];
gyro_y_adc = databuf[1];
gyro_z_adc = databuf[2];
accel_x_adc = databuf[3];
accel_y_adc = databuf[4];
accel_z_adc = databuf[5];
temp_adc = databuf[6];
/* ????? */
gyro_x_act = (float)(gyro_x_adc) / 16.4;
gyro_y_act = (float)(gyro_y_adc) / 16.4;
gyro_z_act = (float)(gyro_z_adc) / 16.4;
accel_x_act = (float)(accel_x_adc) / 2048;
accel_y_act = (float)(accel_y_adc) / 2048;
accel_z_act = (float)(accel_z_adc) / 2048;
temp_act = ((float)(temp_adc) - 25 ) / 326.8 + 25;
printf("rn");
printf("raw value:rn");
printf("gx = %d, gy = %d, gz = %drn", gyro_x_adc, gyro_y_adc, gyro_z_adc);
printf("ax = %d, ay = %d, az = %drn", accel_x_adc, accel_y_adc, accel_z_adc);
printf("temp = %drn", temp_adc);
printf("rn");
printf("act value:rn");
printf("act gx = %.2f度/S, act gy = %.2f度/S, act gz = %.2f度/Srn", gyro_x_act, gyro_y_act, gyro_z_act);
printf("act ax = %.2fg, act ay = %.2fg, act az = %.2fgrn", accel_x_act, accel_y_act, accel_z_act);
printf("act temp = %.2f攝氏度rn", temp_act);
}
sleep(1); /*1s */
}
close(fd);
return 0;
}