Linux下SPI驱动详解(干货),


1. SPI总线

1.1. SPI总线概述

SPI,是英语Serial Peripheral interface的缩写,顾名思义就是串行外围设备接口。是Motorola首先在其MC68HCXX系列处理器上定义的。SPI接口主要应用在 EEPROM,FLASH,实时时钟,AD转换器,还有数字信号处理器和数字信号解码器之间。SPI,是一种高速的,全双工,同步的通信总线,并且在芯片的管脚上只占用四根线,节约了芯片的管脚,同时为PCB的布局上节省空间,提供方便,正是出于这种简单易用的特性,现在越来越多的芯片集成了这种通信协议。SPI总线的构成及信号类型如图1-1所示:

  • MOSI – 主设备数据输出,从设备数据输入 对应MOSI master output slave input
  • MISO – 主设备数据输入,从设备数据输出 对应MISO master input slave output
  • CLK – 时钟信号,由主设备产生
  • nCS – 从设备使能信号,由主设备控制

图1-1 SPI总线模型

1.2. SPI总线时序

SPI接口在Master控制下产生的从设备使能信号和时钟信号,两个双向移位寄存器按位传输进行数据交换,传输数据高位在前(MSB first),低位在后。如下图所示,在CLK的下降沿上数据改变,上升沿一位数据被存入移位寄存器。

图1-2 spi传输时序图

在一个SPI时钟周期内,会完成如下操作:(1)Master通过MOSI线发送1位数据,同时Slave通过MOSI线读取这1位数据;(2)Slave通过MISO线发送1位数据,同时Master通过MISO线读取这1位数据。Master和Slave各有一个移位寄存器,如图1-3所示,而且这两个移位寄存器连接成环状。依照CLK的变化,数据以MSB first的方式依次移出Master寄存器和Slave寄存器,并且依次移入Slave寄存器和Master寄存器。当寄存器中的内容全部移出时,相当于完成了两个寄存器内容的交换。

1.3. SPI总线传输模式

SPI总线传输一共有4种模式,这4种模式分别由时钟极性(CPOL,Clock Polarity)和时钟相位(CPHA,Clock Phase)来定义,其中CPOL参数规定了SCK时钟信号空闲状态的电平,CPHA规定了数据是在SCK时钟的上升沿被采样还是下降沿被采样。这四种模式的时序图如下图1-4所示:


  • 模式0:CPOL= 0,CPHA=0。CLK串行时钟线空闲是为低电平,数据在SCK时钟的上升沿被采样,数据在CLK时钟的下降沿切换
  • 模式1:CPOL= 0,CPHA=1。CLK串行时钟线空闲是为低电平,数据在SCK时钟的下降沿被采样,数据在CLK时钟的上升沿切换
  • 模式2:CPOL= 1,CPHA=0。CLK串行时钟线空闲是为高电平,数据在SCK时钟的下降沿被采样,数据在CLK时钟的上升沿切换
  • 模式3:CPOL= 1,CPHA=1。CLK串行时钟线空闲是为高电平,数据在SCK时钟的上升沿被采样,数据在CLK时钟的下降沿切换 其中比较常用的模式是模式0和模式3。为了更清晰的描述SPI总线的时序,下面展现了模式0下的SPI时序图1-5:

 

图1-5 mode0下的SPI时序图

1.4. SPI总线的优缺点

(1) 在点对点的通信中,SPI接口不需要进行寻址操作,且为全双工通信,显得简单高效。(2) SPI接口没有指定的流控制,没有应答机制确认是否接收到数据。

2. Linux SPI 框架

2.1. 软件架构

Linux系统对spi设备具有很好的支持,linux系统下的spi驱动程序从逻辑上可以分为3个部分:

 

图2-1 spi软件架构图

2.2. 初始化及退出流程

2.2.1. 注册spi控制器

注册spi控制器到内核分为两个阶段:第一个阶段,使用spi_alloc_master,分配一个spi_master的空间,具体流程如图2-2所示:


第二阶段,使用spi_register_master将第一阶段分配的spi_master注册到内核中,具体流程如2-3所示:

2.2.2. 注销spi控制器

spi控制器注销的流程如图2-4所示:


2.3. 关键数据结构

2.3.1. spi_device

  1. struct spi_device { 
  2.         struct device         dev;      /*spi控制器对应的device结构 
  3.         struct spi_master   *master;      /*设备使用的master结构,挂在哪个主控制器下*/ 
  4.         u32                     max_speed_hz;   /*通讯时钟最大频率*/ 
  5.         u8                      chip_select;     /*片选号,每个master支持多个spi_device  */  
  6.         u8                      mode; 
  7. #define SPI_CPHA        0x01                    /* clock phase */ 
  8. #define SPI_CPOL        0x02                    /* clock polarity */ 
  9. #define SPI_MODE_0      (0|0)                   /* (original MicroWire) */ 
  10. #define SPI_MODE_1      (0|SPI_CPHA) 
  11. #define SPI_MODE_2      (SPI_CPOL|0) 
  12. #define SPI_MODE_3      (SPI_CPOL|SPI_CPHA) 
  13. #define SPI_CS_HIGH     0x04                    /* chipselect active high? */ 
  14. #define SPI_LSB_FIRST   0x08                    /* per-word bits-on-wire */ 
  15. #define SPI_3WIRE       0x10                    /* SI/SO signals shared */ 
  16. #define SPI_LOOP        0x20                    /* loopback mode */ 
  17. #define SPI_NO_CS       0x40                    /* 1 dev/bus, no chipselect */ 
  18. #define SPI_READY       0x80                    /* slave pulls low to pause */ 
  19.         u8                      bits_per_word;    /*每个字长的比特数,默认是8*/ 
  20.         int                     irq; 
  21.         void                    *controller_state; /*控制器状态*/ 
  22.         void                    *controller_data;   /*控制器数据*/ 
  23.         char                    modalias[SPI_NAME_SIZE]; /* 设备驱动的名字 */ 
  24.         int                     cs_gpio;        /* chip select gpio */ 
  25.  
  26.         /* 
  27.          * likely need more hooks for more protocol options affecting how 
  28.          * the controller talks to each chip, like: 
  29.          *  - memory packing (12 bit samples into low bits, others zeroed) 
  30.          *  - priority 
  31.          *  - drop chipselect after each word 
  32.          *  - chipselect delays 
  33.          *  - ... 
  34.          */ 
  35. }; 

spi_device代表一个外围spi设备,由master controller driver注册完成后扫描BSP中注册设备产生的设备链表并向spi_bus注册产生。在内核中,每个spi_device代表一个物理的spi设备。

2.3.2. spi_driver

  1. struct spi_driver { 
  2.         const struct spi_device_id *id_table; /*支持的spi_device设备表*/ 
  3.  
  4.         int                     (*probe)(struct spi_device *spi); 
  5.         int                     (*remove)(struct spi_device *spi); 
  6.         void                    (*shutdown)(struct spi_device *spi); 
  7.         int                     (*suspend)(struct spi_device *spi, pm_message_t mesg); 
  8.         int                     (*resume)(struct spi_device *spi); 
  9.         struct device_driver    driver; 
  10. }; 

spi_driver代表一个SPI protocol drivers,即外设驱动

2.3.3. struct spi_master

  1. struct spi_master { 
  2.         struct device   dev;  /*spi控制器对应的device结构*/ 
  3.  
  4.         struct list_head list;  /*链表 
  5.  
  6.         /* other than negative (== assign one dynamically), bus_num is fully 
  7.          * board-specific.  usually that simplifies to being SOC-specific. 
  8.          * example:  one SOC has three SPI controllers, numbered 0..2, 
  9.          * and one board's schematics might show it using SPI-2.  software 
  10.          * would normally use bus_num=2 for that controller. 
  11.          */ 
  12.         s16                     bus_num; /*总线(或控制器编号)*/ 
  13.  
  14.         /* chipselects will be integral to many controllers; some others 
  15.          * might use board-specific GPIOs. 
  16.          */ 
  17.         u16                     num_chipselect; /*片选数量*/ 
  18.  
  19.         /* some SPI controllers pose alignment requirements on DMAable 
  20.          * buffers; let protocol drivers know about these requirements. 
  21.          */ 
  22.         u16                     dma_alignment; 
  23.  
  24.         /* spi_device.mode flags understood by this controller driver */ 
  25.         u16                     mode_bits;   /* master支持的设备模式 */ 
  26.  
  27.         /* bitmask of supported bits_per_word for transfers */ 
  28.         u32                     bits_per_word_mask; 
  29.  
  30.         /* other constraints relevant to this driver */ 
  31.         u16                     flags; /*用于限定某些限制条件的标志位 
  32. #define SPI_MASTER_HALF_DUPLEX  BIT(0)          /* can't do full duplex */ 
  33. #define SPI_MASTER_NO_RX        BIT(1)          /* can't do buffer read */ 
  34. #define SPI_MASTER_NO_TX        BIT(2)          /* can't do buffer write */ 
  35.  
  36.         /* lock and mutex for SPI bus locking */ 
  37.         spinlock_t              bus_lock_spinlock; 
  38.         struct mutex            bus_lock_mutex; 
  39.  
  40.         /* flag indicating that the SPI bus is locked for exclusive use */ 
  41.         bool                    bus_lock_flag; 
  42.  
  43.         /* Setup mode and clock, etc (spi driver may call many times). 
  44.          * 
  45.          * IMPORTANT:  this may be called when transfers to another 
  46.          * device are active.  DO NOT UPDATE SHARED REGISTERS in ways 
  47.          * which could break those transfers. 
  48.          */ 
  49.         int                     (*setup)(struct spi_device *spi); /*根据spi设备更新硬件配置。设置spi工作模式、时钟等*/ 
  50.  
  51.         /* bidirectional bulk transfers 
  52.          * 
  53.          * + The transfer() method may not sleep; its main role is 
  54.          *   just to add the message to the queue. 
  55.          * + For now there's no remove-from-queue operation, or 
  56.          *   any other request management 
  57.          * + To a given spi_device, message queueing is pure fifo 
  58.          * 
  59. * + The master's main job is to process its message queue, 
  60.          *   selecting a chip then transferring data 
  61.          * + If there are multiple spi_device children, the i/o queue 
  62.          *   arbitration algorithm is unspecified (round robin, fifo, 
  63.          *   priority, reservations, preemption, etc) 
  64.          * 
  65.          * + Chipselect stays active during the entire message 
  66.          *   (unless modified by spi_transfer.cs_change != 0). 
  67.          * + The message transfers use clock and SPI mode parameters 
  68.          *   previously established by setup() for this device 
  69.          */ 
  70.         int                     (*transfer)(struct spi_device *spi, 
  71.                                                 struct spi_message *mesg);   /*添加消息到队列的方法,此函数不可睡眠。它的职责是安排发生的传送并且调用注册的回调函数complete()*/ 
  72.  
  73.  
  74.  
  75.         /* called on release() to free memory provided by spi_master */ 
  76.         void                    (*cleanup)(struct spi_device *spi);/*cleanup函数会在spidev_release函数中被调用,spidev_release被登记为spi dev的release函数。*/ 
  77.  
  78.  
  79.         /* 
  80.          * These hooks are for drivers that want to use the generic 
  81.          * master transfer queueing mechanism. If these are used, the 
  82.          * transfer() function above must NOT be specified by the driver. 
  83.          * Over time we expect SPI drivers to be phased over to this API. 
  84.          */ 
  85.         bool                      queued;  
  86.         struct kthread_worker  kworker; /*用于管理数据传输消息队列的工作队列线程*/ 
  87.         struct task_struct     *kworker_task; 
  88.         struct kthread_work    pump_messages; /*具体实现数据传输队列的工作队列*/ 
  89.         spinlock_t               queue_lock; 
  90.         struct list_head        queue; /*该控制器的消息队列,所有等待传输的队列挂在该链表下*/ 
  91.         struct spi_message     *cur_msg;/*当前正在处理的消息队列*/ 
  92.         bool                       busy; /忙状态*/ 
  93.         bool                       running; /*正在跑*/ 
  94.         bool                       rt;  
  95.  
  96.         int (*prepare_transfer_hardware)(struct spi_master *master); /*回调函数,正式发起传输前会被调用,用于准备硬件资源*/ 
  97.         int (*transfer_one_message)(struct spi_master *master, struct spi_message *mesg); /*单个消息的原子传输回调函数,队列中每个消息都会回调一次该回调来完成传输工作*/ 
  98.       int (*unprepare_transfer_hardware)(struct spi_master *master); /*清理回调函数*/ 
  99.         /* gpio chip select */ 
  100.         int                     *cs_gpios; 
  101. }; 

spi_master代表一个spi控制器。

2.3.4. struct spi_message 和spi_transfer

要完成和SPI设备的数据传输工作,我们还需要另外两个数据结构:spi_message和spi_transfer。

spi_message包含了一个的spi_transfer结构序列,一旦控制器接收了一个spi_message,其中的spi_transfer应该按顺序被发送,并且不能被其它spi_message打断,所以我们认为spi_message就是一次SPI数据交换的原子操作。下面我们看看这两个数据结构的定义:

struct spi_message :

  1. struct spi_message { 
  2.         struct list_head        transfers;  /*spi_transfer链表队列,此次消息的传输段队列,一个消息可以包含多个传输段。*/ 
  3.  
  4.         struct spi_device       *spi; /*传输的目的设备*/ 
  5.         unsigned                is_dma_mapped:1;  /*如果为真,此次调用提供dma和cpu虚拟地址。*/ 
  6.  
  7.         /* REVISIT:  we might want a flag affecting the behavior of the 
  8.          * last transfer ... allowing things like "read 16 bit length L" 
  9.          * immediately followed by "read L bytes".  Basically imposing 
  10.          * a specific message scheduling algorithm. 
  11.          * 
  12.          * Some controller drivers (message-at-a-time queue processing) 
  13.          * could provide that as their default scheduling algorithm.  But 
  14.          * others (with multi-message pipelines) could need a flag to 
  15.          * tell them about such special cases. 
  16.          */ 
  17.  
  18.         /* completion is reported through a callback */ 
  19.         void                    (*complete)(void *context);/*异步调用完成后的回调函数*/ 
  20.         void                    *context; /*回调函数的参数*/ 
  21.         unsigned                actual_length; /*实际传输的长度*/ 
  22.         int                     status; /*该消息的发送结果,成功被置0,否则是一个负的错误码。*/ 
  23.  
  24.         /* for optional use by whatever driver currently owns the 
  25.          * spi_message ...  between calls to spi_async and then later 
  26.          * complete(), that's the spi_master controller driver. 
  27.          */ 
  28.         struct list_head        queue; 
  29.         void                    *state; 
  30. }; 

链表字段queue用于把该结构挂在代表控制器的spi_master结构的queue字段上,控制器上可以同时被加入多个spi_message进行排队。另一个链表字段transfers则用于链接挂在本message下的spi_tranfer结构。complete回调函数则会在该message下的所有spi_transfer都被传输完成时被调用,以便通知协议驱动处理接收到的数据以及准备下一批需要发送的数据。我们再来看看spi_transfer结构:spi_transfer

  1. struct spi_transfer { 
  2.         /* it's ok if tx_buf == rx_buf (right?) 
  3.          * for MicroWire, one buffer must be null 
  4.          * buffers must work with dma_*map_single() calls, unless 
  5.          *   spi_message.is_dma_mapped reports a pre-existing mapping 
  6.          */ 
  7.         const void     *tx_buf; /*发送缓冲区*/ 
  8.         void            *rx_buf; /*接收缓冲区*/ 
  9.         unsigned        len; /*缓冲区长度,tx和rx的大小(字节数)。指它们各自的大小*/ 
  10.  
  11.         dma_addr_t      tx_dma; /*tx的dma地址*/ 
  12.         dma_addr_t      rx_dma;  /*rx的dma地址*/ 
  13.   
  14.         unsigned        cs_change:1; /*当前spi_transfer发送完成之后重新片选*/ 
  15.         u8              bits_per_word; /*每个字长的比特数,0代表使用spi_device中的默认值8*/ 
  16.         u16             delay_usecs; /*发送完成一个spi_transfer后的延时时间,此次传输结束和片选改变之间的延时,之后就会启动另一个传输或者结束整个消息*/ 
  17.         u32             speed_hz; /*通信时钟。如果是0,使用默认值*/ 
  18.  
  19. #ifdef CONFIG_SPI_LOMBO 
  20.         struct lombo_spi_operate_para *esop; 
  21. #endif 
  22.  
  23.         struct list_head transfer_list; /*用于链接到spi_message,用来连接的双向链接节点*/ 
  24.  
  25. }; 

首先,transfer_list链表字段用于把该transfer挂在一个spi_message结构中,tx_buf和rx_buf提供了非dma模式下的数据缓冲区地址,len则是需要传输数据的长度,tx_dma和rx_dma则给出了dma模式下的缓冲区地址。原则来讲,spi_transfer才是传输的最小单位,之所以又引进了spi_message进行打包,我觉得原因是:有时候希望往spi设备的多个不连续的地址(或寄存器)一次性写入,如果没有spi_message进行把这样的多个spi_transfer打包,因为通常真正的数据传送工作是在另一个内核线程(工作队列)中完成的,不打包的后果就是会造成更多的进程切换,效率降低,延迟增加,尤其对于多个不连续地址的小规模数据传送而言就更为明显。

2.3.5. spi_board_info

  1. struct spi_board_info { 
  2.         /* the device name and module name are coupled, like platform_bus; 
  3.          * "modalias" is normally the driver name. 
  4.          * 
  5.          * platform_data goes to spi_device.dev.platform_data, 
  6.          * controller_data goes to spi_device.controller_data, 
  7.          * irq is copied too 
  8.          */ 
  9.         char            modalias[SPI_NAME_SIZE]; /*名字*/ 
  10.  
  11.         const void      *platform_data; /*平台数据*/ 
  12.         void            *controller_data; /*控制器数据*/ 
  13.         int             irq; 
  14.  
  15.         /* slower signaling on noisy or low voltage boards */ 
  16.         u32             max_speed_hz; /*最大速率*/ 
  17.  
  18.  
  19.         /* bus_num is board specific and matches the bus_num of some 
  20.          * spi_master that will probably be registered later. 
  21.          * 
  22.          * chip_select reflects how this chip is wired to that master; 
  23.          * it's less than num_chipselect. 
  24.          */ 
  25.         u16             bus_num; /*spi总线编号*/ 
  26.         u16             chip_select; /*片选*/ 
  27.  
  28.         /* mode becomes spi_device.mode, and is essential for chips 
  29.          * where the default of SPI_CS_HIGH = 0 is wrong. 
  30.          */ 
  31.         u8              mode; /*模式 */ 
  32.  
  33.         /* ... may need additional spi_device chip config data here. 
  34.          * avoid stuff protocol drivers can set; but include stuff 
  35.          * needed to behave without being bound to a driver: 
  36.          *  - quirks like clock rate mattering when not selected 
  37.          */ 
  38. }; 

2.4. 数据传输流程

整体的数据传输流程大致上是这样的:

传输示意图如图2-5所示:


2.4.1. 数据准备

2.4.1.1. spi_message_init

  1. static inline void spi_message_init(struct spi_message *m) 
  2.  memset(m, 0, sizeof *m); 
  3.  INIT_LIST_HEAD(&m->transfers); 

初始化spi_message:清空message,初始化transfers链表头。

2.4.1.2. spi_message_add_tail

  1. static inline void 
  2. spi_message_add_tail(struct spi_transfer *t, struct spi_message *m) 
  3.  list_add_tail(&t->transfer_list, &m->transfers); 

将spi_transfer加入到spi_message的链表尾部。

2.4.2. 数据传输

SPI数据传输可以有两种方式:同步方式和异步方式。所谓同步方式是指数据传输的发起者必须等待本次传输的结束,期间不能做其它事情,用代码来解释就是,调用传输的函数后,直到数据传输完成,函数才会返回。而异步方式则正好相反,数据传输的发起者无需等待传输的结束,数据传输期间还可以做其它事情,用代码来解释就是,调用传输的函数后,函数会立刻返回而不用等待数据传输完成,我们只需设置一个回调函数,传输完成后,该回调函数会被调用以通知发起者数据传送已经完成。同步方式简单易用,很适合处理那些少量数据的单次传输。但是对于数据量大、次数多的传输来说,异步方式就显得更加合适。对于SPI控制器来说,要支持异步方式必须要考虑以下两种状况:

  • 对于同一个数据传输的发起者,既然异步方式无需等待数据传输完成即可返回,返回后,该发起者可以立刻又发起一个message,而这时上一个message还没有处理完。
  • 对于另外一个不同的发起者来说,也有可能同时发起一次message传输请求 首先分析spi_sync()接口的实现流程,如图2-6:

其次分析spi_async_locked接口的实现流程,如图2-7所示:

spi_queued_transfer接口的实现流程如图3-8所示:


spi_pump_messages函数的处理流程如图3-9所示:

图中transfer_one_message是spi控制器驱动要实现的,主要功能是处理spi_message中的每个spi_transfer。

2.5. 关键函数解析

2.5.1. spi_alloc_master

原型:

  1. struct spi_master *spi_alloc_master(struct device *dev, unsigned size) 

功能:分配一个spi_master结构体指针。

参数:dev:spi控制器device指针 size :分配的driver-private data大小

返回值 :成功,返回spi_master指针;否则返回NULL

2.5.2. spi_register_master

原型:

  1. int spi_register_master(struct spi_master *master)  

功能 注册spi控制器驱动到内核。

参数 master:spi_master指针

返回值 成功,返回0;否则返回错误码

2.5.3. spi_unregister_master

原型:

  1. void spi_unregister_master(struct spi_master *master)  

功能 注销spi控制器驱动。

参数 master:spi_master指针

返回值 无

3. Demo

(参考自正点原子)

  1. #include <linux/types.h> 
  2. #include <linux/kernel.h> 
  3. #include <linux/delay.h> 
  4. #include <linux/ide.h> 
  5. #include <linux/init.h> 
  6. #include <linux/module.h> 
  7. #include <linux/errno.h> 
  8. #include <linux/gpio.h> 
  9. #include <linux/cdev.h> 
  10. #include <linux/device.h> 
  11. #include <linux/of_gpio.h> 
  12. #include <linux/semaphore.h> 
  13. #include <linux/timer.h> 
  14. #include <linux/i2c.h> 
  15. #include <linux/spi/spi.h> 
  16. #include <linux/of.h> 
  17. #include <linux/of_address.h> 
  18. #include <linux/of_gpio.h> 
  19. #include <linux/platform_device.h> 
  20. #include <asm/mach/map.h> 
  21. #include <asm/uaccess.h> 
  22. #include <asm/io.h> 
  23. #include "icm20608reg.h" 
  24. /*************************************************************** 
  25. Copyright © ALIENTEK Co., Ltd. 1998-2029. All rights reserved. 
  26. 文件名  : icm20608.c 
  27. 作者    : 左工 
  28. 版本     : V1.0 
  29. 描述     : ICM20608 SPI驱动程序 
  30. 其他     : 无 
  31. 论坛  :  
  32. 日志     : 初版V1.0 2019/9/2 左工创建 
  33. ***************************************************************/ 
  34. #define ICM20608_CNT 1 
  35. #define ICM20608_NAME "icm20608" 
  36.  
  37. struct icm20608_dev { 
  38.  dev_t devid;    /* 设备号   */ 
  39.  struct cdev cdev;   /* cdev  */ 
  40.  struct class *class;  /* 类   */ 
  41.  struct device *device;  /* 设备   */ 
  42.  struct device_node *nd;  /* 设备节点 */ 
  43.  int major;     /* 主设备号 */ 
  44.  void *private_data;   /* 私有数据   */ 
  45.  int cs_gpio;    /* 片选所使用的GPIO编号  */ 
  46.  signed int gyro_x_adc;  /* 陀螺仪X轴原始值   */ 
  47.  signed int gyro_y_adc;  /* 陀螺仪Y轴原始值  */ 
  48.  signed int gyro_z_adc;  /* 陀螺仪Z轴原始值   */ 
  49.  signed int accel_x_adc;  /* 加速度计X轴原始值  */ 
  50.  signed int accel_y_adc;  /* 加速度计Y轴原始值 */ 
  51.  signed int accel_z_adc;  /* 加速度计Z轴原始值  */ 
  52.  signed int temp_adc;  /* 温度原始值    */ 
  53. }; 
  54.  
  55. static struct icm20608_dev icm20608dev; 
  56.  
  57. /* 
  58.  * @description : 从icm20608读取多个寄存器数据 
  59.  * @param - dev:  icm20608设备 
  60.  * @param - reg:  要读取的寄存器首地址 
  61.  * @param - val:  读取到的数据 
  62.  * @param - len:  要读取的数据长度 
  63.  * @return   : 操作结果 
  64.  */ 
  65. static int icm20608_read_regs(struct icm20608_dev *dev, u8 reg, void *buf, int len) 
  66.  int ret; 
  67.  unsigned char txdata[len]; 
  68.  struct spi_message m; 
  69.  struct spi_transfer *t; 
  70.  struct spi_device *spi = (struct spi_device *)dev->private_data; 
  71.  
  72.  gpio_set_value(dev->cs_gpio, 0);    /* 片选拉低,选中ICM20608 */ 
  73.  t = kzalloc(sizeof(struct spi_transfer), GFP_KERNEL); /* 申请内存 */ 
  74.  
  75.  /* 第1次,发送要读取的寄存地址 */ 
  76.  txdata[0] = reg | 0x80;  /* 写数据的时候寄存器地址bit8要置1 */ 
  77.  t->tx_buf = txdata;   /* 要发送的数据 */ 
  78.  t->len = 1;     /* 1个字节 */ 
  79.  spi_message_init(&m);  /* 初始化spi_message */ 
  80.  spi_message_add_tail(t, &m);/* 将spi_transfer添加到spi_message队列 */ 
  81.  ret = spi_sync(spi, &m); /* 同步发送 */ 
  82.  
  83.  /* 第2次,读取数据 */ 
  84.  txdata[0] = 0xff;   /* 随便一个值,此处无意义 */ 
  85.  t->rx_buf = buf;   /* 读取到的数据 */ 
  86.  t->len = len;    /* 要读取的数据长度 */ 
  87.  spi_message_init(&m);  /* 初始化spi_message */ 
  88.  spi_message_add_tail(t, &m);/* 将spi_transfer添加到spi_message队列 */ 
  89.  ret = spi_sync(spi, &m); /* 同步发送 */ 
  90.  
  91.  kfree(t);         /* 释放内存 */ 
  92.  gpio_set_value(dev->cs_gpio, 1);   /* 片选拉高,释放ICM20608 */ 
  93.  
  94.  return ret; 
  95.  
  96. /* 
  97.  * @description : 向icm20608多个寄存器写入数据 
  98.  * @param - dev:  icm20608设备 
  99.  * @param - reg:  要写入的寄存器首地址 
  100.  * @param - val:  要写入的数据缓冲区 
  101.  * @param - len:  要写入的数据长度 
  102.  * @return    :   操作结果 
  103.  */ 
  104. static s32 icm20608_write_regs(struct icm20608_dev *dev, u8 reg, u8 *buf, u8 len) 
  105.  int ret; 
  106.  
  107.  unsigned char txdata[len]; 
  108.  struct spi_message m; 
  109.  struct spi_transfer *t; 
  110.  struct spi_device *spi = (struct spi_device *)dev->private_data; 
  111.  
  112.  t = kzalloc(sizeof(struct spi_transfer), GFP_KERNEL); /* 申请内存 */ 
  113.  gpio_set_value(dev->cs_gpio, 0);   /* 片选拉低 */ 
  114.  
  115.  /* 第1次,发送要读取的寄存地址 */ 
  116.  txdata[0] = reg & ~0x80; /* 写数据的时候寄存器地址bit8要清零 */ 
  117.  t->tx_buf = txdata;   /* 要发送的数据 */ 
  118.  t->len = 1;     /* 1个字节 */ 
  119.  spi_message_init(&m);  /* 初始化spi_message */ 
  120.  spi_message_add_tail(t, &m);/* 将spi_transfer添加到spi_message队列 */ 
  121.  ret = spi_sync(spi, &m); /* 同步发送 */ 
  122.  
  123.  /* 第2次,发送要写入的数据 */ 
  124.  t->tx_buf = buf;   /* 要写入的数据 */ 
  125.  t->len = len;    /* 写入的字节数 */ 
  126.  spi_message_init(&m);  /* 初始化spi_message */ 
  127.  spi_message_add_tail(t, &m);/* 将spi_transfer添加到spi_message队列 */ 
  128.  ret = spi_sync(spi, &m); /* 同步发送 */ 
  129.  
  130.  kfree(t);     /* 释放内存 */ 
  131.  gpio_set_value(dev->cs_gpio, 1);/* 片选拉高,释放ICM20608 */ 
  132.  return ret; 
  133.  
  134. /* 
  135.  * @description : 读取icm20608指定寄存器值,读取一个寄存器 
  136.  * @param - dev:  icm20608设备 
  137.  * @param - reg:  要读取的寄存器 
  138.  * @return    :   读取到的寄存器值 
  139.  */ 
  140. static unsigned char icm20608_read_onereg(struct icm20608_dev *dev, u8 reg) 
  141.  u8 data = 0; 
  142.  icm20608_read_regs(dev, reg, &data, 1); 
  143.  return data; 
  144.  
  145. /* 
  146.  * @description : 向icm20608指定寄存器写入指定的值,写一个寄存器 
  147.  * @param - dev:  icm20608设备 
  148.  * @param - reg:  要写的寄存器 
  149.  * @param - data: 要写入的值 
  150.  * @return   :    无 
  151.  */  
  152.  
  153. static void icm20608_write_onereg(struct icm20608_dev *dev, u8 reg, u8 value) 
  154.  u8 buf = value; 
  155.  icm20608_write_regs(dev, reg, &buf, 1); 
  156.  
  157. /* 
  158.  * @description : 读取ICM20608的数据,读取原始数据,包括三轴陀螺仪、 
  159.  *     : 三轴加速度计和内部温度。 
  160.  * @param - dev : ICM20608设备 
  161.  * @return   : 无。 
  162.  */ 
  163. void icm20608_readdata(struct icm20608_dev *dev) 
  164.  unsigned char data[14]; 
  165.  icm20608_read_regs(dev, ICM20_ACCEL_XOUT_H, data, 14); 
  166.  
  167.  dev->accel_x_adc = (signed short)((data[0] << 8) | data[1]);  
  168.  dev->accel_y_adc = (signed short)((data[2] << 8) | data[3]);  
  169.  dev->accel_z_adc = (signed short)((data[4] << 8) | data[5]);  
  170.  dev->temp_adc    = (signed short)((data[6] << 8) | data[7]);  
  171.  dev->gyro_x_adc  = (signed short)((data[8] << 8) | data[9]);  
  172.  dev->gyro_y_adc  = (signed short)((data[10] << 8) | data[11]); 
  173.  dev->gyro_z_adc  = (signed short)((data[12] << 8) | data[13]); 
  174.  
  175. /* 
  176.  * @description  : 打开设备 
  177.  * @param - inode  : 传递给驱动的inode 
  178.  * @param - filp  : 设备文件,file结构体有个叫做privateate_data的成员变量 
  179.  *        一般在open的时候将private_data似有向设备结构体。 
  180.  * @return    : 0 成功;其他 失败 
  181.  */ 
  182. static int icm20608_open(struct inode *inode, struct file *filp) 
  183.  filp->private_data = &icm20608dev; /* 设置私有数据 */ 
  184.  return 0; 
  185.  
  186. /* 
  187.  * @description  : 从设备读取数据  
  188.  * @param - filp  : 要打开的设备文件(文件描述符) 
  189.  * @param - buf  : 返回给用户空间的数据缓冲区 
  190.  * @param - cnt  : 要读取的数据长度 
  191.  * @param - offt  : 相对于文件首地址的偏移 
  192.  * @return    : 读取的字节数,如果为负值,表示读取失败 
  193.  */ 
  194. static ssize_t icm20608_read(struct file *filp, char __user *buf, size_t cnt, loff_t *off) 
  195.  signed int data[7]; 
  196.  long err = 0; 
  197.  struct icm20608_dev *dev = (struct icm20608_dev *)filp->private_data; 
  198.  
  199.  icm20608_readdata(dev); 
  200.  data[0] = dev->gyro_x_adc; 
  201.  data[1] = dev->gyro_y_adc; 
  202.  data[2] = dev->gyro_z_adc; 
  203.  data[3] = dev->accel_x_adc; 
  204.  data[4] = dev->accel_y_adc; 
  205.  data[5] = dev->accel_z_adc; 
  206.  data[6] = dev->temp_adc; 
  207.  err = copy_to_user(buf, data, sizeof(data)); 
  208.  return 0; 
  209.  
  210. /* 
  211.  * @description  : 关闭/释放设备 
  212.  * @param - filp  : 要关闭的设备文件(文件描述符) 
  213.  * @return    : 0 成功;其他 失败 
  214.  */ 
  215. static int icm20608_release(struct inode *inode, struct file *filp) 
  216.  return 0; 
  217.  
  218. /* icm20608操作函数 */ 
  219. static const struct file_operations icm20608_ops = { 
  220.  .owner = THIS_MODULE, 
  221.  .open = icm20608_open, 
  222.  .read = icm20608_read, 
  223.  .release = icm20608_release, 
  224. }; 
  225.  
  226. /* 
  227.  * ICM20608内部寄存器初始化函数  
  228.  * @param   : 无 
  229.  * @return  : 无 
  230.  */ 
  231. void icm20608_reginit(void) 
  232.  u8 value = 0; 
  233.   
  234.  icm20608_write_onereg(&icm20608dev, ICM20_PWR_MGMT_1, 0x80); 
  235.  mdelay(50); 
  236.  icm20608_write_onereg(&icm20608dev, ICM20_PWR_MGMT_1, 0x01); 
  237.  mdelay(50); 
  238.  
  239.  value = icm20608_read_onereg(&icm20608dev, ICM20_WHO_AM_I); 
  240.  printk("ICM20608 ID = %#X\r\n", value);  
  241.  
  242.  icm20608_write_onereg(&icm20608dev, ICM20_SMPLRT_DIV, 0x00);  /* 输出速率是内部采样率     */ 
  243.  icm20608_write_onereg(&icm20608dev, ICM20_GYRO_CONFIG, 0x18);  /* 陀螺仪±2000dps量程     */ 
  244.  icm20608_write_onereg(&icm20608dev, ICM20_ACCEL_CONFIG, 0x18);  /* 加速度计±16G量程      */ 
  245.  icm20608_write_onereg(&icm20608dev, ICM20_CONFIG, 0x04);   /* 陀螺仪低通滤波BW=20Hz     */ 
  246.  icm20608_write_onereg(&icm20608dev, ICM20_ACCEL_CONFIG2, 0x04); /* 加速度计低通滤波BW=21.2Hz    */ 
  247.  icm20608_write_onereg(&icm20608dev, ICM20_PWR_MGMT_2, 0x00);  /* 打开加速度计和陀螺仪所有轴     */ 
  248.  icm20608_write_onereg(&icm20608dev, ICM20_LP_MODE_CFG, 0x00);  /* 关闭低功耗       */ 
  249.  icm20608_write_onereg(&icm20608dev, ICM20_FIFO_EN, 0x00);  /* 关闭FIFO      */ 
  250.  
  251.  /* 
  252.   * @description     : spi驱动的probe函数,当驱动与 
  253.   *                    设备匹配以后此函数就会执行 
  254.   * @param - client  : spi设备 
  255.   * @param - id      : spi设备ID 
  256.   *  
  257.   */  
  258. static int icm20608_probe(struct spi_device *spi) 
  259.  int ret = 0; 
  260.  
  261.  /* 1、构建设备号 */ 
  262.  if (icm20608dev.major) { 
  263.   icm20608dev.devid = MKDEV(icm20608dev.major, 0); 
  264.   register_chrdev_region(icm20608dev.devid, ICM20608_CNT, ICM20608_NAME); 
  265.  } else { 
  266.   alloc_chrdev_region(&icm20608dev.devid, 0, ICM20608_CNT, ICM20608_NAME); 
  267.   icm20608dev.major = MAJOR(icm20608dev.devid); 
  268.  } 
  269.  
  270.  /* 2、注册设备 */ 
  271.  cdev_init(&icm20608dev.cdev, &icm20608_ops); 
  272.  cdev_add(&icm20608dev.cdev, icm20608dev.devid, ICM20608_CNT); 
  273.  
  274.  /* 3、创建类 */ 
  275.  icm20608dev.class = class_create(THIS_MODULE, ICM20608_NAME); 
  276.  if (IS_ERR(icm20608dev.class)) { 
  277.   return PTR_ERR(icm20608dev.class); 
  278.  } 
  279.  
  280.  /* 4、创建设备 */ 
  281.  icm20608dev.device = device_create(icm20608dev.class, NULL, icm20608dev.devid, NULL, ICM20608_NAME); 
  282.  if (IS_ERR(icm20608dev.device)) { 
  283.   return PTR_ERR(icm20608dev.device); 
  284.  } 
  285.  
  286.  /* 获取设备树中cs片选信号 */ 
  287.  icm20608dev.nd = of_find_node_by_path("/soc/aips-bus@02000000/spba-bus@02000000/ecspi@02010000"); 
  288.  if(icm20608dev.nd == NULL) { 
  289.   printk("ecspi3 node not find!\r\n"); 
  290.   return -EINVAL; 
  291.  }  
  292.  
  293.  /* 2、 获取设备树中的gpio属性,得到BEEP所使用的BEEP编号 */ 
  294.  icm20608dev.cs_gpio = of_get_named_gpio(icm20608dev.nd, "cs-gpio", 0); 
  295.  if(icm20608dev.cs_gpio < 0) { 
  296.   printk("can't get cs-gpio"); 
  297.   return -EINVAL; 
  298.  } 
  299.  
  300.  /* 3、设置GPIO1_IO20为输出,并且输出高电平 */ 
  301.  ret = gpio_direction_output(icm20608dev.cs_gpio, 1); 
  302.  if(ret < 0) { 
  303.   printk("can't set gpio!\r\n"); 
  304.  } 
  305.  
  306.  /*初始化spi_device */ 
  307.  spi->mode = SPI_MODE_0; /*MODE0,CPOL=0,CPHA=0*/ 
  308.  spi_setup(spi); 
  309.  icm20608dev.private_data = spi; /* 设置私有数据 */ 
  310.  
  311.  /* 初始化ICM20608内部寄存器 */ 
  312.  icm20608_reginit();   
  313.  return 0; 
  314.  
  315. /* 
  316.  * @description     : spi驱动的remove函数,移除spi驱动的时候此函数会执行 
  317.  * @param - client  : spi设备 
  318.  * @return          : 0,成功;其他负值,失败 
  319.  */ 
  320. static int icm20608_remove(struct spi_device *spi) 
  321.  /* 删除设备 */ 
  322.  cdev_del(&icm20608dev.cdev); 
  323.  unregister_chrdev_region(icm20608dev.devid, ICM20608_CNT); 
  324.  
  325.  /* 注销掉类和设备 */ 
  326.  device_destroy(icm20608dev.class, icm20608dev.devid); 
  327.  class_destroy(icm20608dev.class); 
  328.  return 0; 
  329.  
  330. /* 传统匹配方式ID列表 */ 
  331. static const struct spi_device_id icm20608_id[] = { 
  332.  {"alientek,icm20608", 0},   
  333.  {} 
  334. }; 
  335.  
  336. /* 设备树匹配列表 */ 
  337. static const struct of_device_id icm20608_of_match[] = { 
  338.  { .compatible = "alientek,icm20608" }, 
  339.  { /* Sentinel */ } 
  340. }; 
  341.  
  342. /* SPI驱动结构体 */  
  343. static struct spi_driver icm20608_driver = { 
  344.  .probe = icm20608_probe, 
  345.  .remove = icm20608_remove, 
  346.  .driver = { 
  347.    .owner = THIS_MODULE, 
  348.       .name = "icm20608", 
  349.       .of_match_table = icm20608_of_match,  
  350.      }, 
  351.  .id_table = icm20608_id, 
  352. }; 
  353.       
  354. /* 
  355.  * @description : 驱动入口函数 
  356.  * @param   : 无 
  357.  * @return   : 无 
  358.  */ 
  359. static int __init icm20608_init(void) 
  360.  return spi_register_driver(&icm20608_driver); 
  361.  
  362. /* 
  363.  * @description : 驱动出口函数 
  364.  * @param   : 无 
  365.  * @return   : 无 
  366.  */ 
  367. static void __exit icm20608_exit(void) 
  368.  spi_unregister_driver(&icm20608_driver); 
  369.  
  370. module_init(icm20608_init); 
  371. module_exit(icm20608_exit); 
  372. MODULE_LICENSE("GPL"); 
  373. MODULE_AUTHOR(yikoulinux"); 

相关内容