Linux系统编程8-I2C通信_i2c8 linux 节点-程序员宅基地

技术标签: Linux开发  linux  

序号 内容 链接
1 多进程 点我访问
2 进程间通信 点我访问
3 多线程 点我访问
4 网络编程 点我访问
5 shell 点我访问
6 Makefile 点我访问
7 串口通信 点我访问
8 I2C通信 点我访问

一 I2C介绍

IIC(IIC,inter-Integrated circuit),两线式串行总线,用于MCU和外设间的通信。
IIC只需两根线:数据线SDA和时钟线SCL。以半双工方式实现MCU和外设之间数据传输,速度可达400kbps。

二 Linux应用层操作I2C

在实时系统中,我们用的但大部分是模拟i2c,也就是gpio模拟i2c的时序;
在Linux中,一般没人用模拟i2c,为什么?linux是非实时系统 -> 延时不准 -> 不能使用模拟i2c;
在Linux下直接使用硬件i2c。

名称 优点 缺点
硬件i2c 速度快,稳定 可移植不强
模拟i2c 可移植强 速度慢,不稳定

我们知道在哪个i2c后,就可以通过/dev下对应的i2c节点进行操作i2c总线;
在这里插入图片描述

每一个节点对应一个i2c总线;
也就是说/dev/i2c-0对应i2c0,假如你的设备挂在i2c0上,那你就需要通过系统IO对这个节点进行操作;

应用层的i2c通信是通过一个特定格式的数据包进行通信的;

#define I2C_M_TEN		0x0010	/* this is a ten bit chip address */
#define I2C_M_RD		    0x0001	/* read data, from slave to master */
#define I2C_M_NOSTART		0x4000	/* if I2C_FUNC_NOSTART */
#define I2C_M_REV_DIR_ADDR	0x2000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK	0x1000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NO_RD_ACK		0x0800	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_RECV_LEN		0x0400	/* length will be first received byte */

struct i2c_msg {
    
	__u16 addr;	     /* 器件地址 */
	__u16 flags;     /* 读写标志,0是写,1是读 */
	__u16 len;		/* buf的长度*/
	__u8 *buf;		/* 指向数据的指针 */
};

struct i2c_rdwr_ioctl_data {
    
	struct i2c_msg __user *msgs;	/* 指向i2c_msg数组的指针 */
	__u32 nmsgs;			/* i2c_msg的个数 */
}; 

2.1 如何封装数据包

2.1.1 情况1: 某i2c接口芯片,器件地址为0x12,我们想读取它0x54地址处的寄存器的值(假设8位值)
unsigned char reg = 0x54;
unsigned char val;

//正常情况只需要发2包数据即可;
//第1包就是把寄存器地址传给器件,让器件准备好值
//第2包就是读取器件发过来的值;
struct i2c_msg aaa[2] = {
    
    [0] = {
    
        .addr = 0x12,
        .flags = 0, //把0x54值写到i2c上,所以是写
        .buf = &reg,   //器件内部寄存器的地址
        .len = sizeof(reg)
    },
    
    [1] = {
    
         .addr = 0x12,
        .flags = 1, //把0x54值写到i2c上,所以是写
        .buf = &val, //读取到的值放到val里
        .len = sizeof(val)
    } 
}

struct i2c_rdwr_ioctl_data msg = {
    
	.msgs = aaa,	/* 指向i2c_msg数组的指针 */
	.nmsgs = 2;			/* i2c_msg的个数 */
};
2.1.2 情况2: 某i2c接口芯片,器件地址为0x33,我们想读取它0x1234地址处的寄存器的值(假设8位值)
unsigned char reg[2] = {
    0x12, 0x34};  //高位在低地址
unsigned char val;

//正常情况只需要发2包数据即可;
//第1包就是把寄存器地址传给器件,让器件准备好值
//第2包就是读取器件发过来的值;
struct i2c_msg aaa[2] = {
    
    [0] = {
    
        .addr = 0x33,
        .flags = 0, //把0x54值写到i2c上,所以是写
        .buf = reg,
        .len = sizeof(reg)
    },
    
    [1] = {
    
        .addr = 0x33,
        .flags = 1, //把0x54值写到i2c上,所以是写
        .buf = &val, //读取到的值放到val里
        .len = sizeof(val)
    } 
}

struct i2c_rdwr_ioctl_data msg = {
    
	.msgs = aaa,	/* 指向i2c_msg数组的指针 */
	.nmsgs = 2;			/* i2c_msg的个数 */
};
2.1.3 情况3: 某i2c接口芯片,器件地址为0x33,我们想连续读取它0x00地址处开始一直到0x07的寄存器的值(假设8位值)
unsigned char reg = 0x00;  
unsigned char val[8];

//正常情况只需要发2包数据即可;
//第1包就是把寄存器地址传给器件,让器件准备好值
//第2包就是读取器件发过来的值;
struct i2c_msg aaa[2] = {
    
    [0] = {
    
        .addr = 0x33,
        .flags = 0, //把0x54值写到i2c上,所以是写
        .buf = &reg,
        .len = sizeof(reg)
    },
    
    [1] = {
    
        .addr = 0x33,
        .flags = 1, //把0x54值写到i2c上,所以是写
        .buf = val, //读取到的值放到val里
        .len = sizeof(val)
    } 
}

struct i2c_rdwr_ioctl_data msg = {
    
	.msgs = aaa,	/* 指向i2c_msg数组的指针 */
	.nmsgs = 2;			/* i2c_msg的个数 */
};

2.2 DEMO 完整代码

2.2.1 I2C-触摸屏

触摸屏ft5x06的i2c器件地址是0x38;

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

int fd;
unsigned char i2c_read(unsigned char slave_addr, unsigned char reg)
{
    
	int ret;
	unsigned char val;
	struct i2c_msg aaa[2] ={
    
		[0] = {
    
			.addr = slave_addr,
			.flags = 0,
			.buf = &reg,  //内部寄存器地址
			.len = sizeof(reg)
			},
		[1] = {
    
			.addr = slave_addr,
			.flags = 1,
			.buf = &val,
			.len = sizeof(val)
			},

			};
	struct i2c_rdwr_ioctl_data msg =
	{
    
		.msgs = aaa,     // 指向i2c_msg数组的指针
		.nmsgs = 2		// i2c_msg的个数	
	};
		
	ret = ioctl(fd,I2C_RDWR,&msg);   //发命令
	if(ret < 0)
		{
    
			perror("ioctl error:");
			return ret;
		}
	return val;	
}




void mydelay(int s,int us)
{
    
	struct timeval tv;
	tv.tv_sec = s;
	tv.tv_usec = us;
	//只用来延时,不检测读写
	select(0,NULL,NULL,NULL,&tv);
}

int main(int argc,char **argv)
{
    
	unsigned int x_val1,y_val1,x_val2,y_val2;	
	unsigned char ID1,ID2,x_valh,x_vall,y_valh,y_vall;
	fd = open("/dev/i2c-1",O_RDWR);
	if(fd < 0 )
		{
    
			perror("open error:");
			return fd;
		}
	while(1)
		{
    			
			x_val1 = (i2c_read(0x38,0x03)&0x0f) << 8 | i2c_read(0x38,0x04);//读x轴的数据
			y_val1 = (i2c_read(0x38,0x05)&0x0f) << 8 | i2c_read(0x38,0x06);// 读y轴的数据
			
			x_valh = i2c_read(0x38,0x09); // 读x轴的高4位数据        		数据需要连续读才能获得正确的数据,如果读了高位有延时再读低位,\
			y_valh = i2c_read(0x38,0x0b); // 读y轴的高4位数据				则数据已经发生改变,读出的数据是错误数据
			x_vall = i2c_read(0x38,0x0a); // 读x轴的低8位数据	
			y_vall = i2c_read(0x38,0x0c); // 读y轴的低8位数据	
			x_val2 = (x_valh & 0x0f) << 8 | x_vall;
			y_val2 = (y_valh & 0x0f) << 8 | y_vall;
			//usleep(30000);
			mydelay(0,30000);
			printf("val1:%dx%d      val2:%dx%d\n",x_val1,y_val1,x_val2,y_val2);
		}
}
2.2.2 I2C-MPU6050
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <linux/i2c.h>
#include <linux/i2c-dev.h>

#include <sys/ioctl.h>

/*寄存器地址*/
#define SMPLRT_DIV      0x19
#define PWR_MGMT_1      0x6B
#define CONFIG          0x1A
#define ACCEL_CONFIG    0x1C

#define ACCEL_XOUT_H    0x3B
#define ACCEL_XOUT_L    0x3C
#define ACCEL_YOUT_H    0x3D
#define ACCEL_YOUT_L    0x3E
#define ACCEL_ZOUT_H    0x3F
#define ACCEL_ZOUT_L    0x40
#define GYRO_XOUT_H     0x43
#define GYRO_XOUT_L     0x44
#define GYRO_YOUT_H     0x45
#define GYRO_YOUT_L     0x46
#define GYRO_ZOUT_H     0x47
#define GYRO_ZOUT_L     0x48

//从机地址 MPU6050地址
#define Address         0x68

//MPU6050操作相关函数
static int mpu6050_init(int fd,uint8_t addr);
static int i2c_write(int fd, uint8_t addr,uint8_t reg,uint8_t val);
static int i2c_read(int fd, uint8_t addr,uint8_t reg,uint8_t * val);
static short GetData(int fd,uint8_t addr,unsigned char REG_Address);

int main(int argc,char *argv[] )
{
    
   int  fd;
   fd = I2C_SLAVE;

   //打开相对应的i2c设备
   fd = open("/dev/i2c-0",O_RDWR );
   if(fd < 0)
   {
    
      perror("/dev/i2c-0");
      exit(1);
   }

   //初始化MPU6050
   mpu6050_init(fd,Address);
   while(1)
   {
    
      usleep(1000 * 10);
      printf("ACCE_X:%6d\n ", GetData(fd,Address,ACCEL_XOUT_H));
      usleep(1000 * 10);
      printf("ACCE_Y:%6d\n ", GetData(fd,Address,ACCEL_YOUT_H));
      usleep(1000 * 10);
      printf("ACCE_Z:%6d\n ", GetData(fd,Address,ACCEL_ZOUT_H));
      usleep(1000 * 10);
      printf("GYRO_X:%6d\n ", GetData(fd,Address,GYRO_XOUT_H));
      usleep(1000 * 10);
      printf("GYRO_Y:%6d\n ", GetData(fd,Address,GYRO_YOUT_H));
      usleep(1000 * 10);
      printf("GYRO_Z:%6d\n\n ", GetData(fd,Address,GYRO_ZOUT_H));
      sleep(1);
   }

   close(fd);

   return 0;
}

static int mpu6050_init(int fd,uint8_t addr)
{
    
    i2c_write(fd, addr,0x6b,0x00);
    i2c_write(fd, addr,0x19,0x07);
    i2c_write(fd, addr,0x1a,0x06);
    i2c_write(fd, addr,0x1c,0x01);
    i2c_write(fd, addr,0x6b,0x80);
    i2c_write(fd, addr,0x6b,0x00);
    i2c_write(fd, addr,0x6b,0x00);
    i2c_write(fd, addr,0x19,0x09);
    i2c_write(fd, addr,0x1a,0x04);
    i2c_write(fd, addr,0x1b,0x00);
    i2c_write(fd, addr,0x1c,0x08);

   return 0;
}

static int i2c_write(int fd, uint8_t addr,uint8_t reg,uint8_t val)
{
    
   int retries;
   uint8_t data[2];

   data[0] = reg;
   data[1] = val;

   //设置地址长度:0为7位地址
   ioctl(fd,I2C_TENBIT,0);


   //设置从机地址
   if (ioctl(fd,I2C_SLAVE,addr) < 0)
   {
    
      printf("fail to set i2c device slave address!\n");
      close(fd);
      return -1;
   }

   //设置收不到ACK时的重试次数
   ioctl(fd,I2C_RETRIES,5);

   if (write(fd, data, 2) == 2)
   {
    
      return 0;
   }
   else
   {
    
      return -1;
   }

}

static int i2c_read(int fd, uint8_t addr,uint8_t reg,uint8_t * val)
{
    
   int retries;

   //设置地址长度:0为7位地址
   ioctl(fd,I2C_TENBIT,0);

   //设置从机地址
   if (ioctl(fd,I2C_SLAVE,addr) < 0)
   {
    
      printf("fail to set i2c device slave address!\n");
      close(fd);
      return -1;
   }

   //设置收不到ACK时的重试次数
   ioctl(fd,I2C_RETRIES,5);

   if (write(fd, &reg, 1) == 1)
   {
    
      if (read(fd, val, 1) == 1)
      {
    
            return 0;
      }
   }
   else
   {
    
      return -1;
   }
}

static short GetData(int fd,uint8_t addr,unsigned char REG_Address)
{
    
   char H, L;

   i2c_read(fd, addr,REG_Address, &H);
   usleep(1000);
   i2c_read(fd, addr,REG_Address + 1, &L);
   return (H << 8) +L;
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/L1643319918/article/details/120129026

智能推荐

C++ 学习笔记(对双端队列进行封装,实现数据生产者消费者)-程序员宅基地

文章浏览阅读698次。#pragma once #include <deque>#include <condition_variable>template <typename T>class MsgList { public: void add(const T& msg) { std::unique_lock<std::mutex> lock(mutex); queue.

python水表识别图像识别深度学习 CNN_水表 深度学习 识别-程序员宅基地

文章浏览阅读551次,点赞8次,收藏8次。重点:项目和文档是本人近期原创所作!程序可以将水表图片里面的数据进行深度学习,提取相关信息训练,lw1.3万字重复15%,可以直接上交那种!具体和看下面的目录。python水表识别,图像识别深度学习 CNN,Opencv,Keras。_水表 深度学习 识别

【DataSet】遥感图像方面的人工智能数据集_群智感知 图像数据集-程序员宅基地

文章浏览阅读288次。遥感图像方面的人工智能数据集数据集类别常用数据集目标检测数据集DSTL 卫星图像数据集;RSOD-Dataset 数据集;NWPUVHR-10地理遥感数据集图像分割数据集Inria AerialImage Labeling Dataset 遥感图像数据集遥感图像分类数据集UCMerced Land-Use Data Set 土地遥感数据集_群智感知 图像数据集

python使用镜像安装opencv_opencv_python安装镜像-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏11次。如何在pycharm中安装opencv_opencv_python安装镜像

手把手教你IDEA创建SSM项目结构_idea创建ssm web项目-程序员宅基地

文章浏览阅读595次,点赞2次,收藏8次。我的小站SSM项目需要用来管理依赖,所以我们需要先配置好,配置很容易,我就不演示了。首先,我们新建项目,勾选,选择模板,然后创建。这里耐心等待下载完成。可以看到,这里没用相关的文件夹。我们直接在文件夹上右键新建文件夹,下面会显示一个,直接创建就可以。此时,我们按照规范来,创建一个包。项目结构多种多样,比如三层架构啥的,按照你的需求来。我这里就稍微演示一下。这里这些结构都是可以自己按照规范命名,结构也有很多,分层架构方法也有很多,这里权当借鉴一下。我这里整合了一份依赖,如需使用可按照自己需求和对于版本进_idea创建ssm web项目

2022年-2023年中职网络安全web渗透任务整理合集_server2280 中职组-程序员宅基地

文章浏览阅读3.2k次。2022年-2023年中职网络安全web渗透任务整理合集_server2280 中职组

随便推点

canal异常 Could not find first log file name in binary log index file_canal could not find first log file name in binary-程序员宅基地

文章浏览阅读4.4k次,点赞3次,收藏2次。Could not find first log file name in binary log index file问题解决解决过程问题最近在使用canal来监测数据库的变化,处理变动的数据。由于有一段时间没有用了,这次启动在日志文件中看到这个异常 Could not find first log file name in binary log index file,详细信息如下:2020-12-16 19:14:42.053 [destination = tradeAndRefund , addr_canal could not find first log file name in binary log index file

【练习】生成10个1到20之间的不重复的随机数并降序输出-程序员宅基地

文章浏览阅读960次。分析:1.创建一个Random对象;2.创建一个hashset的集合对象;3.循环生成10个1-20的随机数4.输出。package edu.xalead;import java.util.*;public class Test { public static void main(String[] args) { Random r...

linux系统扩展名大全,Linux系统文件扩展名学习-程序员宅基地

文章浏览阅读3.2k次。Linux系统下的扩展名并不能标识该文件是属于哪一种类型的文件。文件是否可以执行等都跟文件的扩展名无关。因为文件script没有执行权限,所以也就无法执行,sh-3.2# touch ./scriptsh-3.2# ls -lh ./script-rw-r--r-- 1 root root 0 Dec 28 06:15 ./scriptsh-3.2#sh-3.2# ./scriptsh: /scr..._linux的扩展名

WPF TabControl 滚动选项卡_wpf 使用tabcontrol如何给切换的页面增加滚动条-程序员宅基地

文章浏览阅读1.3k次,点赞27次,收藏19次。我原本以为是很简单的事情,但是没想到实际做起来还是有很多的基础知识点的。我们平常写TabControl的时候,可能都很习惯了直接写TabControl+TabItem。但是TabControl负责了什么布局,TabItem负责了什么布局,我们都不知道。在《深入浅出WPF》中,我们可以看到TabControl属于ItemsControl我们去看看控件模板样式副本。WPF的xaml的优点是每个控件都是单独的逻辑,耦合低。缺点是写起来麻烦,每次改动约等于重新写一个新的。通过增加自己的工作量来降低了耦合我们可以看_wpf 使用tabcontrol如何给切换的页面增加滚动条

Apache Jmeter常用插件下载及安装及软硬件性能指标_jmeter插件下载-程序员宅基地

文章浏览阅读2.1k次,点赞24次,收藏47次。Apache Jmeter常用插件下载及安装_jmeter插件下载

SpringBoot 2.X整合Mybatis_springboot2.1.5整合mybatis不需要配置mapper-locations-程序员宅基地

文章浏览阅读5.9k次,点赞6次,收藏18次。实际上Mybatis的整合过程像极了我们程序员的一生。在SpringBoot 整合Mybatis之前,我们回忆回忆以前 MyBatis 单独使用时,myBatis 核心配置文件要配置数据源、事务、连接数据库账号、密码....是的全是这货一个人干,都要亲力亲为。这就是我们的低谷期myBatis 与 spring 整合的时候,配置数据源、事务、连接数据库的账号什么的都交由 spring 管理就行,就不用什么都自己管理自己去干。这就是我们春风得意的时候,事业有着落...再后来,Spring_springboot2.1.5整合mybatis不需要配置mapper-locations

推荐文章

热门文章

相关标签