CM3計算板讀取SHT30以及I2C驅動

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常用到以下配置:

  1.     I2C_SLAVE:I2C從機地址,用來設定I2C從機地址;
  2.     I2C_SLAVE_FORCE:用來修改I2C從機地址;
  3.     I2C_TENBIT:設置從機地址佔用的位數,取值爲0表示從機地址爲7 bit;取值爲1表示機地址爲10bit。
     

具體地,貼代碼了:

/*
  ******************************************************************************
  * File Name          : cm3I2C.c
  * Description        : This file provides code for the gateway i2c driver.
  * Author             : jackwang by [email protected]
  * 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);
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章