1、引言
用SHT30测温湿度,SHT30是I2C通信总线,具体信息去看Datasheet文档:https://pdf1.alldatasheet.com/datasheet-pdf/view/897974/ETC2/SHT30.html。操作系统是Linux,机器是CM3计算板,当然也可以是树莓派和其他主机。
2、设备树打开I2C接口
linux的I2C需要打开I2C的设备树才能在/dev中找到,具体方式是:
sudo vim /dev/config.txt
打开注释或者新增以下内容:
dtparam=i2c_arm=on
dtoverlay=i2c0
dtoverlay=i2c1
然后重启,查看/dev下边有没有i2c-0和i2c-1出现。执行:ls /dev/
3、一切皆文件的驱动编写
linux中的I2C驱动主要包括ioctl,write,read三个函数。其中,ioctl的cmd常用到以下配置:
- I2C_SLAVE:I2C从机地址,用来设定I2C从机地址;
- I2C_SLAVE_FORCE:用来修改I2C从机地址;
- I2C_TENBIT:设置从机地址占用的位数,取值为0表示从机地址为7 bit;取值为1表示机地址为10bit。
具体地,贴代码了:
/******************************************************************************** File Name : cm3I2C.c* Description : This file provides code for the gateway i2c driver.* Author : jackwang by jiawang16@foxmail.com* Date : 2019-08-17******************************************************************************
*/
/*! Include header */
#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>
#include <unistd.h>
#include <sys/ioctl.h>#include "cm3I2C.h"/*! debug info define */
#define __DEBUG 1
#if __DEBUG#define debug printf
#else#define debug
#endif/*! cm3 i2c dev setup, e.g. /dev/i2c-0 */
int cm3I2CSetup(char* dev)
{int fd;fd = open(dev, O_RDWR);if ( fd < 0 ){debug("[Error] failed to open the i2c bus: %s.\n", dev);return -1;}return fd;
}/*! cm3 i2c slave address bits setup, 0->7,1->10 */
int cm3I2CSlaveAddrBitSetup(int fd, int bits)
{if ( ioctl(fd, I2C_TENBIT, bits) < 0) {debug("[Error] failed to set i2c addr bits.\n");return -1;}return 0;
}/*! cm3 i2c slave address setup */
int cm3I2CSlaveAddrSetup(int fd, int addr)
{if ( ioctl(fd, I2C_SLAVE_FORCE, addr) < 0 ){debug("[Error] failed to set i2c slave address.\n");return -1;}return 0;
}/*! cm3 i2c read slave device reg */
int cm3I2CRead(int fd, unsigned char*buf, int buflength)
{if ( read(fd, buf, buflength) <0){debug("[Error] failed to read i2c.\n");return -1;}return 0;
}/*! cm3 i2c write slave device reg */
int cm3I2CWrite(int fd, unsigned char*buf, int buflength)
{if ( write(fd, buf, buflength) != buflength ){debug("[Error] failed to write i2c.\n");return -1;}return 0;
}/*! cm3 i2c dev-handler close */
void cm3I2CClose(int fd)
{close(fd);
}