I2C 基础知识(物理与协议)
I2C (Inter-Integrated Circuit) 是一种简单的双向二线制同步串行总线。
html
1. 物理层:两条线
SCL (Serial Clock Line): 时钟线,由主设备(Master,通常是 SoC)产生时钟脉冲。
SDA (Serial Data Line): 数据线,双向传输数据。
物理特性: 既是开漏输出(Open-Drain),需要外部上拉电阻。空闲时两条线都是高电平。
2.通信协议(时序)
起始信号 (Start): SCL 为高时,SDA 由高变低。
发送地址 + 读写位: 发送 7位从机地址 + 1位读写位(0写,1读)。
应答信号 (ACK/NACK): 每发送 8 位数据,接收方必须拉低 SDA 进行应答。
数据传输: 传输核心数据(寄存器地址或数值)。
停止信号 (Stop): SCL 为高时,SDA 由低变高。
Linux 下的 I2C 驱动框架
Linux 为了通用性,将 I2C 驱动分成了三层,实现了主机控制器与外设的解耦。
bash
I2C 核心层 (I2C Core)
位于中间层
提供了总线驱动和设备驱动的注册、注销方法,以及通信方法。它是连接上下的纽带。
I2C 总线驱动 (I2C Adapter Driver)
位于底层
对应 SoC 内部的 I2C 控制器(STM32 的 I2C 硬件)。它负责产生 I2C 时序(Start, Stop, ACK)。
I2C 设备驱动 (I2C Client Driver)
位于上层(我们进行编写的部分)
对应具体的从机设备(如 MPU6050, EEPROM)。它不需要关心怎么产生时序,只需要告诉核心层"我要向地址 0x68 的设备写什么数据"。
主要结构体: i2c_driver (驱动逻辑) 和 i2c_client (设备描述)。
I2C 总线驱动代码 (Adapter)
在现代嵌入式 Linux 开发中,总线驱动通常由芯片原厂(如 NXP、ST)提供
html
设备树描述: 在 DTS 文件中,SoC 厂商会定义好 I2C 控制器的节点(寄存器地址、中断号、时钟等)。
platform 驱动: 总线驱动通常也是一个 platform 驱动。当驱动与 DTS 节点匹配后,会调用 probe 函数。
核心工作:
初始化 I2C 硬件控制器。
构建 i2c_algorithm,实现具体的发送/接收函数(通常名为 xxx_i2c_xfer)。
调用 i2c_add_adapter 向内核注册一个新的适配器。
I2C 设备驱动的核心函数 (Client)
我们开发重点是编写 Client Driver。
html
1. 两个核心结构体
struct i2c_client: 代表真实的物理设备(MPU6050)。
来源: 通常由内核解析设备树(Device Tree)后自动生成。
包含: 设备地址 (addr)、中断号 (irq)、所属适配器指针 (adapter)。
struct i2c_driver: 代表驱动程序逻辑。
包含: probe (匹配成功时执行), remove, driver (包含 of_match_table 用于匹配设备树)。
2. 核心通信 API 直接调用核心层提供的函数:
i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
struct i2c_msg:描述一个传输包(目标地址、读/写标志、数据长度、缓冲区)。
写操作: 构建 1 个 msg(设备地址 + Write + [寄存器地址, 数据])。
读操作: 构建 2 个 msg。
Msg 0 (Write): 发送要读取的寄存器地址。
Msg 1 (Read): 读取设备返回的数据。
MPU6050 驱动及测试程序示例
MPU6050 是一款运动处理传感器,它集成了3轴MEMS陀螺仪,3轴MEMS加速度计。
html
确认总线:挂在哪个 I2C
Pin 23 (SCL) 和 Pin 24 (SDA)
写着 I2C1_SCL 和 I2C1_SDA
因此target = <&i2c1>;
确认地址
如果 AD0 接地 (GND),地址是 0x68。
如果 AD0 接电源 (3V3),地址是 0x69。
reg = <0x68>;
确认中断:接到了哪个 GPIO
INT引脚接入>> PF13
interrupt-parent = <&gpiof>; /* 对应 PF */
interrupts = <13 IRQ_TYPE_EDGE_RISING>; /* 对应 13 */
挂载 MPU6050的设备树插件代码编写:
告诉内核,在 I2C1 总线上有一个地址为 0x68 的设备,请加载名为 fire,i2c_mpu6050 的驱动程序来管理它。
c
#include <dt-bindings/pinctrl/stm32-pinfunc.h>
#include <dt-bindings/input/input.h>
#include <dt-bindings/mfd/st,stpmic1.h>
#include <dt-bindings/gpio/gpio.h>
#include <dt-bindings/interrupt-controller/irq.h>
fragment@0 {
target = <&i2c1>; /* 依据:图上连的是 I2C1_SCL/SDA */
__overlay__ {
#address-cells = <1>;
#size-cells = <0>;
mpu6050@68 {
compatible = "fire,i2c_mpu6050";
reg = <0x68>; /* 依据:图上 AD0 接地 */
interrupt-parent = <&gpiof>; /* 依据:图上 INT 连的是 PF13 */
interrupts = <13 IRQ_TYPE_EDGE_RISING>; /* 依据:PF13 */
};
};
};
配置 I2C 控制器设备树的代码编写:
如果没有这个文件,i2c1 可能处于关闭状态 (disabled),或者引脚被挪作他用(比如被当成普通 GPIO)。
c
/dts-v1/;
/plugin/;
//#include "../stm32mp157c.dtsi"
#include <dt-bindings/pinctrl/stm32-pinfunc.h>
#include <dt-bindings/input/input.h>
#include <dt-bindings/mfd/st,stpmic1.h>
#include <dt-bindings/gpio/gpio.h>
/{
//定义资源的使用
fragment@0{
target=<&i2c1>;
__overlay__{
//两个子系统的额作用的名字
pinctrl-names = "default", "sleep";
pinctrl-0 = <&i2c1_pins_a>;
pinctrl-1 = <&i2c1_pins_sleep_a>;
i2c-scl-rising-time-ns = <100>;
i2c-scl-falling-time-ns = <7>;
status = "okay";
/delete-property/dmas;
/delete-property/dma-names;
};
};
//定义资源
fragment@1{
target=<&pinctrl>;
__overlay__{
i2c1_pins_a: i2c1-0 {
pins {
pinmux = <STM32_PINMUX('F', 14, AF5)>, /* I2C1_SCL */
<STM32_PINMUX('F', 15, AF5)>; /* I2C1_SDA */
bias-disable;
drive-open-drain;
slew-rate = <0>;
};
};
i2c1_pins_sleep_a: i2c1-1 {
pins {
pinmux = <STM32_PINMUX('F', 14, ANALOG)>, /* I2C1_SCL */
<STM32_PINMUX('F', 15, ANALOG)>; /* I2C1_SDA */
};
};
};
};
};
i2c_mpu6050.h
c
#ifndef I2C_MPU6050_H
#define I2C_MPU6050_H
//宏定义
#define SMPLRT_DIV 0x19
#define CONFIG 0x1A
#define GYRO_CONFIG 0x1B
#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 TEMP_OUT_H 0x41
#define TEMP_OUT_L 0x42
#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
#define PWR_MGMT_1 0x6B
#define WHO_AM_I 0x75
#define SlaveAddress 0xD0
#define Address 0x68 //MPU6050地址
#define I2C_RETRIES 0x0701
#define I2C_TIMEOUT 0x0702
#define I2C_SLAVE 0x0703 //IIC从器件的地址设置
#define I2C_BUS_MODE 0x0780
#endif
i2c_mpu6050.c
c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/i2c.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <asm/mach/map.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_gpio.h>
#include <asm/io.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include "i2c_mpu6050.h"
/*------------------字符设备内容----------------------*/
#define DEV_NAME "I2C1_mpu6050"
#define DEV_CNT (1)
/*定义 led 资源结构体,保存获取得到的节点信息以及转换后的虚拟寄存器地址*/
static dev_t mpu6050_devno; //定义字符设备的设备号
static struct cdev mpu6050_chr_dev; //定义字符设备结构体chr_dev
struct class *class_mpu6050; //保存创建的类
struct device *device_mpu6050; // 保存创建的设备
struct device_node *mpu6050_device_node; //rgb_led的设备树节点结构体
/*------------------IIC设备内容----------------------*/
struct i2c_client *mpu6050_client = NULL; //保存mpu6050设备对应的i2c_client结构体,匹配成功后由.prob函数带回。
/*通过i2c 向mpu6050写入数据
*mpu6050_client:mpu6050的i2c_client结构体。
*address, 数据要写入的地址,
*data, 要写入的数据
*返回值,错误,-1。成功,0
*/
static int i2c_write_mpu6050(struct i2c_client *mpu6050_client, u8 address, u8 data)
{
int error = 0;
u8 write_data[2];
struct i2c_msg send_msg; //要发送的数据结构体
/*设置要发送的数据*/
write_data[0] = address;
write_data[1] = data;
/*发送 iic要写入的地址 reg*/
send_msg.addr = mpu6050_client->addr; //mpu6050在 iic 总线上的地址
send_msg.flags = 0; //标记为发送数据
send_msg.buf = write_data; //写入的首地址
send_msg.len = 2; //reg长度
/*执行发送*/
error = i2c_transfer(mpu6050_client->adapter, &send_msg, 1);
if (error != 1)
{
printk(KERN_DEBUG "\n i2c_transfer error \n");
return -1;
}
return 0;
}
/*通过i2c 向mpu6050写入数据
*mpu6050_client:mpu6050的i2c_client结构体。
*address, 要读取的地址,
*data,保存读取得到的数据
*length,读长度
*返回值,错误,-1。成功,0
*/
static int i2c_read_mpu6050(struct i2c_client *mpu6050_client, u8 address, void *data, u32 length)
{
int error = 0;
u8 address_data = address;
struct i2c_msg mpu6050_msg[2];
/*设置读取位置msg*/
mpu6050_msg[0].addr = mpu6050_client->addr; //mpu6050在 iic 总线上的地址
mpu6050_msg[0].flags = 0; //标记为发送数据
mpu6050_msg[0].buf = &address_data; //写入的首地址
mpu6050_msg[0].len = 1; //写入长度
/*设置读取位置msg*/
mpu6050_msg[1].addr = mpu6050_client->addr; //mpu6050在 iic 总线上的地址
mpu6050_msg[1].flags = I2C_M_RD; //标记为读取数据
mpu6050_msg[1].buf = data; //读取得到的数据保存位置
mpu6050_msg[1].len = length; //读取长度
error = i2c_transfer(mpu6050_client->adapter, mpu6050_msg, 2);
if (error != 2)
{
printk(KERN_DEBUG "\n i2c_read_mpu6050 error \n");
return -1;
}
return 0;
}
/*初始化i2c
*返回值,成功,返回0。失败,返回 -1
*/
static int mpu6050_init(void)
{
int error = 0;
/*配置mpu6050*/
error += i2c_write_mpu6050(mpu6050_client, PWR_MGMT_1, 0X00);
error += i2c_write_mpu6050(mpu6050_client, SMPLRT_DIV, 0X07);
error += i2c_write_mpu6050(mpu6050_client, CONFIG, 0X06);
error += i2c_write_mpu6050(mpu6050_client, ACCEL_CONFIG, 0X01);
if (error < 0)
{
/*初始化错误*/
printk(KERN_DEBUG "\n mpu6050_init error \n");
return -1;
}
return 0;
}
/*字符设备操作函数集,open函数实现*/
static int mpu6050_open(struct inode *inode, struct file *filp)
{
// printk("\n mpu6050_open \n");
/*向 mpu6050 发送配置数据,让mpu6050处于正常工作状态*/
mpu6050_init();
return 0;
}
/*字符设备操作函数集,.read函数实现*/
static ssize_t mpu6050_read(struct file *filp, char __user *buf, size_t cnt, loff_t *off)
{
char data_H;
char data_L;
int error;
short mpu6050_result[6]; //保存mpu6050转换得到的原始数据
// printk("\n mpu6050_read \n");
i2c_read_mpu6050(mpu6050_client, ACCEL_XOUT_H, &data_H, 1);
i2c_read_mpu6050(mpu6050_client, ACCEL_XOUT_L, &data_L, 1);
mpu6050_result[0] = data_H << 8;
mpu6050_result[0] += data_L;
i2c_read_mpu6050(mpu6050_client, ACCEL_YOUT_H, &data_H, 1);
i2c_read_mpu6050(mpu6050_client, ACCEL_YOUT_L, &data_L, 1);
mpu6050_result[1] = data_H << 8;
mpu6050_result[1] += data_L;
i2c_read_mpu6050(mpu6050_client, ACCEL_ZOUT_H, &data_H, 1);
i2c_read_mpu6050(mpu6050_client, ACCEL_ZOUT_L, &data_L, 1);
mpu6050_result[2] = data_H << 8;
mpu6050_result[2] += data_L;
i2c_read_mpu6050(mpu6050_client, GYRO_XOUT_H, &data_H, 1);
i2c_read_mpu6050(mpu6050_client, GYRO_XOUT_L, &data_L, 1);
mpu6050_result[3] = data_H << 8;
mpu6050_result[3] += data_L;
i2c_read_mpu6050(mpu6050_client, GYRO_YOUT_H, &data_H, 1);
i2c_read_mpu6050(mpu6050_client, GYRO_YOUT_L, &data_L, 1);
mpu6050_result[4] = data_H << 8;
mpu6050_result[4] += data_L;
i2c_read_mpu6050(mpu6050_client, GYRO_ZOUT_H, &data_H, 1);
i2c_read_mpu6050(mpu6050_client, GYRO_ZOUT_L, &data_L, 1);
mpu6050_result[5] = data_H << 8;
mpu6050_result[5] += data_L;
// printk("AX=%d, AY=%d, AZ=%d \n",(int)mpu6050_result[0],(int)mpu6050_result[1],(int)mpu6050_result[2]);
// printk("GX=%d, GY=%d, GZ=%d \n \n",(int)mpu6050_result[3],(int)mpu6050_result[4],(int)mpu6050_result[5]);
/*将读取得到的数据拷贝到用户空间*/
error = copy_to_user(buf, mpu6050_result, cnt);
if(error != 0)
{
printk("copy_to_user error!");
return -1;
}
return 0;
}
/*字符设备操作函数集,.release函数实现*/
static int mpu6050_release(struct inode *inode, struct file *filp)
{
// printk("\n mpu6050_release \n");
/*向mpu6050发送命令,使mpu6050进入关机状态*/
return 0;
}
/*字符设备操作函数集*/
static struct file_operations mpu6050_chr_dev_fops =
{
.owner = THIS_MODULE,
.open = mpu6050_open,
.read = mpu6050_read,
.release = mpu6050_release,
};
/*----------------平台驱动函数集-----------------*/
static int mpu6050_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
int ret = -1; //保存错误状态码
printk(KERN_EMERG "\t match successed \n");
/*---------------------注册 字符设备部分-----------------*/
//采用动态分配的方式,获取设备编号,次设备号为0,
//设备名称为rgb-leds,可通过命令cat /proc/devices查看
//DEV_CNT为1,当前只申请一个设备编号
ret = alloc_chrdev_region(&mpu6050_devno, 0, DEV_CNT, DEV_NAME);
if (ret < 0)
{
printk("fail to alloc mpu6050_devno\n");
goto alloc_err;
}
//关联字符设备结构体cdev与文件操作结构体file_operations
mpu6050_chr_dev.owner = THIS_MODULE;
cdev_init(&mpu6050_chr_dev, &mpu6050_chr_dev_fops);
// 添加设备至cdev_map散列表中
ret = cdev_add(&mpu6050_chr_dev, mpu6050_devno, DEV_CNT);
if (ret < 0)
{
printk("fail to add cdev\n");
goto add_err;
}
/*创建类 */
class_mpu6050 = class_create(THIS_MODULE, DEV_NAME);
/*创建设备 DEV_NAME 指定设备名,*/
device_mpu6050 = device_create(class_mpu6050, NULL, mpu6050_devno, NULL, DEV_NAME);
mpu6050_client = client;
return 0;
add_err:
// 添加设备失败时,需要注销设备号
unregister_chrdev_region(mpu6050_devno, DEV_CNT);
printk("\n error! \n");
alloc_err:
return -1;
}
static int mpu6050_remove(struct i2c_client *client)
{
/*删除设备*/
device_destroy(class_mpu6050, mpu6050_devno); //清除设备
class_destroy(class_mpu6050); //清除类
cdev_del(&mpu6050_chr_dev); //清除设备号
unregister_chrdev_region(mpu6050_devno, DEV_CNT); //取消注册字符设备
return 0;
}
/*定义ID 匹配表*/
static const struct i2c_device_id gtp_device_id[] = {
{"fire,i2c_mpu6050", 0},
{}};
/*定义设备树匹配表*/
static const struct of_device_id mpu6050_of_match_table[] = {
{.compatible = "fire,i2c_mpu6050"},
{/* sentinel */}};
/*定义i2c总线设备结构体*/
struct i2c_driver mpu6050_driver = {
.probe = mpu6050_probe,
.remove = mpu6050_remove,
.id_table = gtp_device_id,
.driver = {
.name = "fire,i2c_mpu6050",
.owner = THIS_MODULE,
.of_match_table = mpu6050_of_match_table,
},
};
/*
*驱动初始化函数
*/
static int __init mpu6050_driver_init(void)
{
int ret;
pr_info("mpu6050_driver_init\n");
ret = i2c_add_driver(&mpu6050_driver);
return ret;
}
/*
*驱动注销函数
*/
static void __exit mpu6050_driver_exit(void)
{
pr_info("mpu6050_driver_exit\n");
i2c_del_driver(&mpu6050_driver);
}
module_init(mpu6050_driver_init);
module_exit(mpu6050_driver_exit);
MODULE_LICENSE("GPL");
上述代码流程:
html
加载驱动 (module_init)
匹配设备树 (发现 fire,i2c_mpu6050 节点)
执行 Probe (创建 /dev/I2C1_mpu6050 文件)
应用层 Open (驱动自动配置 MPU6050 寄存器初始化)
应用层 Read (驱动通过 I2C 读取 12 个寄存器 -> 拼接成 6 个数据 -> 返回给 App)
上述只实现了查询式(Polling)I2C 数据透传。