飞凌嵌入式ElfBoard ELF1板卡-使用AHT20进行环境监测之编写程序
编程步骤(一)打开设备
fd = open(AHT20_DEV, O_RDWR);
if(fd < 0) {
printf("can't open file %s\r\n", AHT20_DEV);
return -1;
}设置宏定义AHT20_DEV为设备节点/dev/aht20,使用open以可读写的方式打开,如果打开错误返回-1。
(二)读取数据
ret = read(fd, databuf, sizeof(databuf));read函数的作用是把从设备中读取到的数据存到databuf数组中。
(三)数据类型转换
c1 = databuf*1000/1024/1024;//
t1 = databuf *200*10/1024/1024-500;
hum = (float)c1/10.0;
temp = (float)t1/10.0;因为温湿度不能用常量表示,所以需要做相应数学计算转换成浮点量。
(四)关闭设备
close(fd);详细代码
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;
int c1,t1;
float hum,temp;
int ret = 0;
fd = open(AHT20_DEV, O_RDWR);
if(fd < 0) {
printf("can't open file %s\r\n", AHT20_DEV);
return -1;
}
while (1) {
ret = read(fd, databuf, sizeof(databuf));
if(ret == 0) { /* ?????? */
c1 = databuf*1000/1024/1024;//
t1 = databuf *200*10/1024/1024-500;
hum = (float)c1/10.0;
temp = (float)t1/10.0;
printf("hum = %0.2f temp = %0.2f \r\n",hum,temp);
usleep(500000);
}
}
close(fd);
return 0;
}
页:
[1]