CM3计算板读取SHT30以及I2C驱动
生活随笔
收集整理的這篇文章主要介紹了
CM3计算板读取SHT30以及I2C驱动
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、引言
用SHT30測(cè)溫濕度,SHT30是I2C通信總線,具體信息去看Datasheet文檔:https://pdf1.alldatasheet.com/datasheet-pdf/view/897974/ETC2/SHT30.html。操作系統(tǒng)是Linux,機(jī)器是CM3計(jì)算板,當(dāng)然也可以是樹莓派和其他主機(jī)。
2、設(shè)備樹打開I2C接口
linux的I2C需要打開I2C的設(shè)備樹才能在/dev中找到,具體方式是:
sudo vim /dev/config.txt打開注釋或者新增以下內(nèi)容:
dtparam=i2c_arm=on dtoverlay=i2c0 dtoverlay=i2c1然后重啟,查看/dev下邊有沒有i2c-0和i2c-1出現(xiàn)。執(zhí)行:ls /dev/
3、一切皆文件的驅(qū)動(dòng)編寫
linux中的I2C驅(qū)動(dòng)主要包括ioctl,write,read三個(gè)函數(shù)。其中,ioctl的cmd常用到以下配置:
?
具體地,貼代碼了:
/******************************************************************************** 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); }?
?
總結(jié)
以上是生活随笔為你收集整理的CM3计算板读取SHT30以及I2C驱动的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go 导出 html 报告(使用 her
- 下一篇: 高压断路器故障诊断的相关方法