編程步驟
(一)打開設(shè)備
fd = open(AHT20_DEV, O_RDWR);
if(fd < 0) {
printf("can't open file %srn", AHT20_DEV);
return -1;
}
設(shè)置宏定義AHT20_DEV為設(shè)備節(jié)點(diǎn)/dev/aht20,使用open以可讀寫的方式打開,如果打開錯(cuò)誤返回-1。
(二)讀取數(shù)據(jù)
ret = read(fd, databuf, sizeof(databuf));
read函數(shù)的作用是把從設(shè)備中讀取到的數(shù)據(jù)存到databuf數(shù)組中。
(三)數(shù)據(jù)類型轉(zhuǎn)換
c1 = databuf[0]*1000/1024/1024; //
t1 = databuf[1] *200*10/1024/1024-500;
hum = (float)c1/10.0;
temp = (float)t1/10.0;
因?yàn)闇貪穸炔荒苡贸A勘硎?,所以需要做相?yīng)數(shù)學(xué)計(jì)算轉(zhuǎn)換成浮點(diǎn)量。
(四)關(guān)閉設(shè)備
close(fd);
詳細(xì)代碼
elf1_cmd_aht20.c:
#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 AHT20_DEV "/dev/aht20"
int main(int argc, char *argv[])
{
int fd;
unsigned int databuf[2];
int c1,t1;
float hum,temp;
int ret = 0;
fd = open(AHT20_DEV, O_RDWR);
if(fd < 0) {
printf("can't open file %srn", AHT20_DEV);
return -1;
}
while (1) {
ret = read(fd, databuf, sizeof(databuf));
if(ret == 0) { /* ?????? */
c1 = databuf[0]*1000/1024/1024; //
t1 = databuf[1] *200*10/1024/1024-500;
hum = (float)c1/10.0;
temp = (float)t1/10.0;
printf("hum = %0.2f temp = %0.2f rn",hum,temp);
usleep(500000);
}
}
close(fd);
return 0;
}
閱讀全文