Linux I2C驱动
前言
主要目的记录一下我在野火的i.MX6ULL mini开发板上面编写了一个Linux I2C设备驱动去驱动SSD1306 OLED屏幕的开发过程。源码用的是野火提供的内核源码。
SSD1306 OLED和I2C接口
这块OLED屏幕大家应该都比较熟悉了,小巧迷你,DIY很好用,很多朋友在学习stm32单片机的时候应该都使用过了,I2C总线也是我们嵌入式工程师必须学会的总线了,具体的总线细节这里也不再讲了,这里主要了解一下在Linux中使用I2C子系统去操作I2C设备,其他的知识点这里就不再讲细节了。
I2C子系统
这里先贴一张野火的图:
在Linux设备驱动中我们通过I2C子系统去进行I2C操作,图中也可以看到I2C总线是包含在platform总线之中的,也就是说I2C子系统是在platform的基础上开发的,所以流程和platform框架差不多,这里我们要做的就是修改设备树和编写对应的驱动程序,这里有几个关键的数据结构,他们都在include/linux/i2c.h
中定义:
/*** struct i2c_driver - represent an I2C device driver* @class: What kind of i2c device we instantiate (for detect)* @probe: Callback for device binding - soon to be deprecated* @probe_new: New callback for device binding* @remove: Callback for device unbinding* @shutdown: Callback for device shutdown* @alert: Alert callback, for example for the SMBus alert protocol* @command: Callback for bus-wide signaling (optional)* @driver: Device driver model driver* @id_table: List of I2C devices supported by this driver* @detect: Callback for device detection* @address_list: The I2C addresses to probe (for detect)* @clients: List of detected clients we created (for i2c-core use only)* @disable_i2c_core_irq_mapping: Tell the i2c-core to not do irq-mapping** The driver.owner field should be set to the module owner of this driver.* The driver.name field should be set to the name of this driver.** For automatic device detection, both @detect and @address_list must* be defined. @class should also be set, otherwise only devices forced* with module parameters will be created. The detect function must* fill at least the name field of the i2c_board_info structure it is* handed upon successful detection, and possibly also the flags field.** If @detect is missing, the driver will still work fine for enumerated* devices. Detected devices simply won't be supported. This is expected* for the many I2C/SMBus devices which can't be detected reliably, and* the ones which can always be enumerated in practice.** The i2c_client structure which is handed to the @detect callback is* not a real i2c_client. It is initialized just enough so that you can* call i2c_smbus_read_byte_data and friends on it. Don't do anything* else with it. In particular, calling dev_dbg and friends on it is* not allowed.*/
struct i2c_driver {unsigned int class;/* Standard driver model interfaces */int (*probe)(struct i2c_client *, const struct i2c_device_id *);int (*remove)(struct i2c_client *);/* New driver model interface to aid the seamless removal of the* current probe()'s, more commonly unused than used second parameter.*/int (*probe_new)(struct i2c_client *);/* driver model interfaces that don't relate to enumeration */void (*shutdown)(struct i2c_client *);/* Alert callback, for example for the SMBus alert protocol.* The format and meaning of the data value depends on the protocol.* For the SMBus alert protocol, there is a single bit of data passed* as the alert response's low bit ("event flag").* For the SMBus Host Notify protocol, the data corresponds to the* 16-bit payload data reported by the slave device acting as master.*/void (*alert)(struct i2c_client *, enum i2c_alert_protocol protocol,unsigned int data);/* a ioctl like command that can be used to perform specific functions* with the device.*/int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);struct device_driver driver;const struct i2c_device_id *id_table;/* Device detection callback for automatic device creation */int (*detect)(struct i2c_client *, struct i2c_board_info *);const unsigned short *address_list;struct list_head clients;bool disable_i2c_core_irq_mapping;
};
/*** struct i2c_client - represent an I2C slave device* @flags: I2C_CLIENT_TEN indicates the device uses a ten bit chip address;* I2C_CLIENT_PEC indicates it uses SMBus Packet Error Checking* @addr: Address used on the I2C bus connected to the parent adapter.* @name: Indicates the type of the device, usually a chip name that's* generic enough to hide second-sourcing and compatible revisions.* @adapter: manages the bus segment hosting this I2C device* @dev: Driver model device node for the slave.* @irq: indicates the IRQ generated by this device (if any)* @detected: member of an i2c_driver.clients list or i2c-core's* userspace_devices list* @slave_cb: Callback when I2C slave mode of an adapter is used. The adapter* calls it to pass on slave events to the slave driver.** An i2c_client identifies a single device (i.e. chip) connected to an* i2c bus. The behaviour exposed to Linux is defined by the driver* managing the device.*/
struct i2c_client {unsigned short flags; /* div., see below */unsigned short addr; /* chip address - NOTE: 7bit *//* addresses are stored in the *//* _LOWER_ 7 bits */char name[I2C_NAME_SIZE];struct i2c_adapter *adapter; /* the adapter we sit on */struct device dev; /* the device structure */int init_irq; /* irq set at initialization */int irq; /* irq issued by device */struct list_head detected;
#if IS_ENABLED(CONFIG_I2C_SLAVE)i2c_slave_cb_t slave_cb; /* callback for slave mode */
#endif
};
struct i2c_driver
用来注册i2c驱动,struct i2c_client
代表一个i2c设备,从成员可以看出有设备名称,对应的设备名称,对应的适配器。
/*** struct i2c_algorithm - represent I2C transfer method* @master_xfer: Issue a set of i2c transactions to the given I2C adapter* defined by the msgs array, with num messages available to transfer via* the adapter specified by adap.* @smbus_xfer: Issue smbus transactions to the given I2C adapter. If this* is not present, then the bus layer will try and convert the SMBus calls* into I2C transfers instead.* @functionality: Return the flags that this algorithm/adapter pair supports* from the I2C_FUNC_* flags.* @reg_slave: Register given client to I2C slave mode of this adapter* @unreg_slave: Unregister given client from I2C slave mode of this adapter** The following structs are for those who like to implement new bus drivers:* i2c_algorithm is the interface to a class of hardware solutions which can* be addressed using the same bus algorithms - i.e. bit-banging or the PCF8584* to name two of the most common.** The return codes from the @master_xfer field should indicate the type of* error code that occurred during the transfer, as documented in the kernel* Documentation file Documentation/i2c/fault-codes.*/
struct i2c_algorithm {/* If an adapter algorithm can't do I2C-level access, set master_xferto NULL. If an adapter algorithm can do SMBus access, setsmbus_xfer. If set to NULL, the SMBus protocol is simulatedusing common I2C messages *//* master_xfer should return the number of messages successfullyprocessed, or a negative value on error */int (*master_xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs,int num);int (*smbus_xfer) (struct i2c_adapter *adap, u16 addr,unsigned short flags, char read_write,u8 command, int size, union i2c_smbus_data *data);/* To determine what the adapter supports */u32 (*functionality) (struct i2c_adapter *);#if IS_ENABLED(CONFIG_I2C_SLAVE)int (*reg_slave)(struct i2c_client *client);int (*unreg_slave)(struct i2c_client *client);
#endif
};
/** i2c_adapter is the structure used to identify a physical i2c bus along* with the access algorithms necessary to access it.*/
struct i2c_adapter {struct module *owner;unsigned int class; /* classes to allow probing for */const struct i2c_algorithm *algo; /* the algorithm to access the bus */void *algo_data;/* data fields that are valid for all devices */const struct i2c_lock_operations *lock_ops;struct rt_mutex bus_lock;struct rt_mutex mux_lock;int timeout; /* in jiffies */int retries;struct device dev; /* the adapter device */int nr;char name[48];struct completion dev_released;struct mutex userspace_clients_lock;struct list_head userspace_clients;struct i2c_bus_recovery_info *bus_recovery_info;const struct i2c_adapter_quirks *quirks;struct irq_domain *host_notify_domain;
};
在Linux I2C子系统框架中,struct i2c_adapter
表示一个具体的物理i2c控制器,而其中的struct i2c_alogrithm
代表的是具体的算法,这个算法指的是具体i2c控制器中如何发送和接收数据,这部分有芯片厂家实现,我们作为驱动工程师只需要关注struct i2c_driver
和struct i2c_client
这两个数据结构就好,在内核加入设备树机制之后struct i2c_client
的内容由Linux i2c子系统核心从设备树获取信息,我们主要关注struct i2c_driver
即可,这里写一个简单的例子:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/of.h>
#include <linux/kernel.h>
#include <linux/delay.h>int ssd1306_master_send_cmd(struct i2c_client *client, const char cmd)
{char msg[2] = {0x00, cmd};return i2c_master_send(client, msg, 2);
}int ssd1306_master_send_dat(struct i2c_client *client, const char dat)
{char msg[2] = {0x40, dat};return i2c_master_send(client, msg, 2);
}int ssd1306_probe(struct i2c_client *client, const struct i2c_device_id *id)
{printk("SSD1306 PROBE!\n");/** Initial ssd1306* */msleep(100);ssd1306_master_send_cmd(client, 0xae);...return 0;
}struct i2c_device_id ssd1306_id_table[] = {{"ssd1306"},{}
};struct of_device_id of_ssd1306_table[] = {{.compatible = "ssd1306"},{}
};struct i2c_driver ssd1306_drv = {.probe = ssd1306_probe,.id_table = ssd1306_id_table,.driver = {.name = "ssd1306",.owner = THIS_MODULE,.of_match_table = of_ssd1306_table}
};static int __init ssd1306_init(void)
{i2c_add_driver(&ssd1306_drv);return 0;
}
module_init(ssd1306_init);static void __exit ssd1306_exit(void)
{i2c_del_driver(&ssd1306_drv);
}
module_exit(ssd1306_exit);
MODULE_LICENSE("GPL");
在驱动里面我们调用i2c_add_driver()
函数去注册i2c驱动,相对的使用i2c_del_driver()
函数来注销i2c驱动,发送数据我们用i2c_master_send()
函数进行数据的发送,他们都在include/linux/i2c.h
下声明定义,原型如下:
extern int i2c_register_driver(struct module *, struct i2c_driver *);
extern void i2c_del_driver(struct i2c_driver *);/* use a define to avoid include chaining to get THIS_MODULE */
#define i2c_add_driver(driver) \i2c_register_driver(THIS_MODULE, driver)/*** i2c_master_send - issue a single I2C message in master transmit mode* @client: Handle to slave device* @buf: Data that will be written to the slave* @count: How many bytes to write, must be less than 64k since msg.len is u16** Returns negative errno, or else the number of bytes written.*/
static inline int i2c_master_send(const struct i2c_client *client,const char *buf, int count)
{return i2c_transfer_buffer_flags(client, (char *)buf, count, 0);
};
我们写好的代码应该放在内核源码的driver/char
目录下并修改该目录Makefile
添加obj-m += ssd1306.o
,ssd1306.c
是我的代码文件名,之后回到内核源码根目录执行$ make modules
编译模块,一切正常的话就可以在driver/char
目录下面看到ssd1306.ko文件了,将这个模块复制到开发板,具体的ssd1306 OLED初始化部分我就省略了,不然代码太长了,下面是设备树的修改,我自己直接在&i2c1
的引用节点下添加:
ssd1306@0x3c {compatible = "ssd1306";reg = <0x3c>
}
reg
的值就是设备地址。仔细看过代码很多朋友会疑惑为什么我用了设备树,还要写一个i2c_device_id表,如果是老一些的内核代码,它的i2c设备匹配会要求这个表不为NULL,不然不能通过匹配,这里写上是为了避免这样的麻烦。保存设备树之后回到源码根目录$ make dtbs
编译设备树,之后将开发板上的设备树替换掉重启开发板,开机之后加载模块,没问题的话内核日志就会输出一条SSD1306 PROBE!
,而屏幕也会被点亮并初始化,至此就完成了一个在Linux下用I2C子系统去进行I2C操作的简单例子。
最后
写的比较简单,需要较多的前置知识,比如内核构造,platform框架,设备树,I2C总线,SSD1306的知识,大家不熟悉的可以自行查阅相关资料补充,谢谢大家。