嵌入式linux读取sht20温湿度传感器例程

sht20主要是i2c总线接口
设备地址0x40
读取温度原理:读取0xe3寄存器地址两个字节
读取温度原理:读取0xe5寄存器地址两个字节

以下是代码
sht20.c

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
#include "i2c.h"

//温度传感器初始化函数 
// 参数无 
//返回 无
void sht20_init() 
{
	i2c_init("/dev/i2c-0", 0x40);
}

//温度传感器读取函数 
// 参数无 
//返回 0
int sht20_read(float *t, float *h) 
{
	unsigned char buf[5];
	float tmp = 0.0;
	
	//读取温度 
	i2c_writeNbyte(0xe3, 1);
	i2c_readNbyte(buf, 3);
	tmp = (bufp[0] << 8) + buf[1];
	t = tmp;
	//读取湿度 
	i2c_writeNbyte(0xe5, 1);
	i2c_readNbyte(buf, 3);
	tmp = (bufp[0] << 8) + buf[1];
	h = tmp;
	
	return 0;
}

i2c.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>

static int fd = 0;

//初始化i2c
//i2c_dev设备文件 i2c_addr 设备地址 
//返回 0
int i2c_init(char *i2c_dev, unsigned char i2c_addr)
{
	int res = 0;
	
	fd = open(i2c_dev, O_RDWR);
	if(fd < 0)
	{
		printf("[%s]:[%d] open i2c file error\r\n", __FUNCTION__, __LINE__);
		return -1;
	}
	res = ioctl(fd,I2C_TENBIT,0);				   //7位模式 
	res = ioctl(fd,I2C_SLAVE, (i2c_addr >> 1));    //设置I2C从设备地址
	
	return res;
}

//读i2c
//buf数据 len长度 
//返回 实际读取的长度 
int i2c_readNbyte(unsigned char *buf, int len)
{
	int res = 0;
	
	res = read(fd, buf,len);
	return res;
}

//写i2c
//buf数据 len长度 
//返回 实际写的长度 
int i2c_writeNbyte(unsigned char *buf, int len)
{
	int res = 0;
	
	res = write(fd, buf,len);
	return res;
}

int i2c_readReg(unsigned int reg_addr, unsigned char *buf, int len)
{
	int res = 0;
	unsigned char buff[2];
	
	buff[0] = reg_addr >> 8;
	buff[1] = reg_addr & 0xff;
	write(fd, buff, 2);
	res = read(fd, buf,len);
	
	return res;
}

int i2c_writeReg(unsigned int reg_addr, unsigned char *buf, int len)
{
	int res = 0,i;
	unsigned char *buff = 0;
	
	buff = (unsigned char *)malloc((len+2));
	buff[0] = reg_addr >> 8;
	buff[1] = reg_addr & 0xff;
	for(i = 0; i < len; i++)
		buff[(i+2)] = buf[i];
	res = write(fd, buff, (len+2));
	free(buff);
	
	return res;
}

int i2c_close()
{
	close(fd);
	return 0;
}

i2c.h

#ifndef __I2C_H 
#define __I2C_H 

int i2c_init(char *i2c_dev, unsigned char i2c_addr);
int i2c_readNbyte(unsigned char *buf, int len);
int i2c_writeNbyte(unsigned char *buf, int len);

#endif
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值