Linux I2C驱动程序

Linux I2C驱动

前言

主要目的记录一下我在野火的i.MX6ULL mini开发板上面编写了一个Linux I2C设备驱动去驱动SSD1306 OLED屏幕的开发过程。源码用的是野火提供的内核源码。

SSD1306 OLED和I2C接口

这块OLED屏幕大家应该都比较熟悉了,小巧迷你,DIY很好用,很多朋友在学习stm32单片机的时候应该都使用过了,I2C总线也是我们嵌入式工程师必须学会的总线了,具体的总线细节这里也不再讲了,这里主要了解一下在Linux中使用I2C子系统去操作I2C设备,其他的知识点这里就不再讲细节了。

I2C子系统

这里先贴一张野火的图:
Linux 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_driverstruct 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.ossd1306.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的知识,大家不熟悉的可以自行查阅相关资料补充,谢谢大家。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/50776.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

习题2.24

没啥好说&#xff0c; 先看解释器给出的结果 说起来也简单&#xff0c;这是一个多层的列表&#xff0c;第一个元素是1 第二个元素是&#xff08;2 &#xff08; 3 4&#xff09;&#xff09; 第二层第一个是2 第二个是 &#xff08;3 4&#xff09; 第三层第一个是 3 第二个…

stm32入门-----ADC模数转换器(理论篇——上)

目录 前言 一、ADC模数转换器 1.简介 2.ADC的结构 3.输入通道 4.转换模式 5.触发控制 6.数据对齐 7.转换时间 8.校准 前言 本期就开始学习ADC模数转换器&#xff0c;这个大家在学习51单片机的时候应该就接触过了&#xff0c;实际上就是把模拟电压转换为…

YOLOv5改进 | 卷积模块 | 即插即用的递归门控卷积gnConv

秋招面试专栏推荐 &#xff1a;深度学习算法工程师面试问题总结【百面算法工程师】——点击即可跳转 &#x1f4a1;&#x1f4a1;&#x1f4a1;本专栏所有程序均经过测试&#xff0c;可成功执行&#x1f4a1;&#x1f4a1;&#x1f4a1; 专栏目录&#xff1a; 《YOLOv5入门 改…

认识到自己的无知,需要一定的智慧

知识本是补药&#xff0c;却被变成毒药——“新无知”的三种表现 今天&#xff0c;一个人如果把评书、演义、宫廷剧当作真实历史&#xff0c;把当年从教科书上学来的过时理论当做“观世界”的金科玉律&#xff0c;并以此嘲笑别人“无知”的&#xff0c;属于典型的“新古人”—…

线程的同步和优先级

文章目录 前言一、优先级和同步各是什么&#xff1f;二、使用方法 1.线程的优先级2.线程的同步总结 前言 线程不仅可以实现代码的单线程运行和并发运行&#xff0c;在线程安全的情况下&#xff0c;还可以实现共同处理相同的系统资源。该篇文章还介绍了开发者如何设置线程运行的…

【数据结构】单链表带头双向循环链表的实现

一、链表的概念及结构 1.链表的概念 概念&#xff1a;链表是一种物理存储结构上非连续、非顺序的存储结构&#xff0c;数据元素的逻辑顺序是通过链表中的指针链接次序实现的 。 2.链表的结构 一般讲的链表包括数据域和指针域&#xff1a; 二、链表的种类 实际中链表的结构…

昇思25天学习打卡营第1天|简单深度学习

前言 昇思MindSpore是一个全场景深度学习框架&#xff0c;旨在实现易开发、高效执行、全场景统一部署三大目标。 其中&#xff0c;易开发表现为API友好、调试难度低&#xff1b;高效执行包括计算效率、数据预处理效率和分布式训练效率&#xff1b;全场景则指框架同时支持云、边…

fatal: refusing to merge unrelated histories

出现本地仓库和远程仓库的代码合并不兼容问题&#xff0c;解决方法&#xff1a; 添加--allow-unrelated-histories&#xff0c;让git允许提交不关联的历史代码。 成功提交&#xff1a;

gitee的fork

通过fork操作&#xff0c;可以复制小组队长的库。通过复制出一模一样的库&#xff0c;先在自己的库修改&#xff0c;最后提交给队长&#xff0c;队长审核通过就可以把你做的那一份也添加入库 在这fork复制一份到你自己的仓库&#xff0c;一般和这个项目同名 现在你有了自己的库…

git 学习总结

文章目录 一、 git 基础操作1、工作区2、暂存区3、本地仓库4、远程仓库 二、git 的本质三、分支git 命令总结 作者: baron 一、 git 基础操作 如图所示 git 总共有几个区域 工作区, 暂存区, 本地仓库, 远程仓库. 1、工作区 存放项目代码的地方&#xff0c;他有两种状态 Unm…

Vue3时间选择器datetimerange在数据库存开始时间和结束时间

♥️作者&#xff1a;小宋1021 &#x1f935;‍♂️个人主页&#xff1a;小宋1021主页 ♥️坚持分析平时学习到的项目以及学习到的软件开发知识&#xff0c;和大家一起努力呀&#xff01;&#xff01;&#xff01; &#x1f388;&#x1f388;加油&#xff01; 加油&#xff01…

大数据-49 Redis 缓存问题中 穿透、雪崩、击穿、数据不一致、HotKey、BigKey

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; 目前已经更新到了&#xff1a; Hadoop&#xff08;已更完&#xff09;HDFS&#xff08;已更完&#xff09;MapReduce&#xff08;已更完&am…

《GPT-4o mini:开启开发与创新的新纪元》

在科技发展的快速进程中&#xff0c;OpenAI 推出的 GPT-4o mini 模型如同一阵春风&#xff0c;给开发者们带来了新的希望和机遇。它以其卓越的性能和极具吸引力的价格&#xff0c;成为了行业内热议的焦点。 当我首次听闻 GPT-4o mini 的消息时&#xff0c;内心充满了好奇与期待…

详解Mysql InnoDB引擎 04

文章目录 1. InnoDB 简介2. 逻辑存储结构2.1 表空间 idb文件2.2 段2.3 区 1M2.4 页 16KB2.5 行 3. 架构3.1 内存结构3.1.1 Buffer Pool 缓冲池3.1.2 Change Buffer 更改缓冲区3.1.3 Adaptive Hash Index3.1.4 Log Buffer 3.2 磁盘结构 4. 后台线程5. 事务原理5.1 redo log 重做…

运行python项目出现ModuleNotFoundError: No module named ‘sklearn‘问题

问题1&#xff1a;ModuleNotFoundError: No module named sklearn 1.WindowsR键&#xff0c;输入cmd&#xff0c;进入命令行窗口 2.安装sklearn&#xff0c;使用清华镜像安装&#xff1a; python -m pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple …

算法学习day22

一、函数的独占时间 给你一个进程数量&#xff0c;和运行日志。运行日志log的格式为:进程id:(start/end):运行时间 其中一个进程运行时可以被另一个优先级较高的进程抢占cpu。求每个进程独占cpu的时间。 输入&#xff1a;n 2, logs ["0:start:0","1:start:…

Spring Boot - 优雅实现支持通配符和IP段的IP访问黑白名单机制

文章目录 CodeIpAccessInterceptoraddInterceptor工具类配置文件 application.yml单元测试 Code 废话不多说&#xff0c;直接上码 IpAccessInterceptor package cn.cloud.bus.module.servicebus.framework.ipconfig;import cn.cloud.bus.module.servicebus.util.IpFilterUti…

深入理解计算机系统 CSAPP 家庭作业11.10

A: //home.html <form action"/cgi-bin/adder" method"GET"><ul><li><label for"n1">n1:</label><input type"text" id"n1" name"n1" /> //name的值决定页面提交后&#xf…

栈知识梳理和函数实现

参考此文章数据结构——栈&#xff0c;此文章写的更详细&#xff0c;由于我们都是学自于比特课程&#xff0c;这里做个自我备份&#xff0c;方便后续查阅、修改和补充。 栈知识梳理和函数实现 前言1.栈是什么&#xff1f;2.栈的接口实现2.1初始化栈2.2入栈2.3 出栈2.4 获取栈顶…

C语言图书信息管理系统

题目&#xff1a;图书信息管理系统 内容及主要功能描述&#xff1a; 该系统用于管理图书信息&#xff0c;包括图书的增加、删除、查找、修改、浏览、按出版社统计图书数量等功能。具体功能包括&#xff1a; 增加图书&#xff1a;输入图书信息并添加到系统中。删除图书&#x…