1. Files
Linux only implements the SPI controller side. The SPI framework and related SPI master driver files normally go to the "drivers/spi" subfolder under Linux kernel source tree.
spi.c:
The main file implements the SPI framework, including the SPI master and SPI device related function calls.
include/linux/spi/spi.h:
Header file for spi.c and some inline functions.
spidev.c:
Implements a general char device driver for SPI device. This driver can do read/write/ioctl on the SPI device.
include/linux/spi/spidev.h:
Header file for spidev.c.
spi_bitbang.c/spi_gpio.c:
A library implementing a SPI master with GPIOs using bitbang.
spi_xxxx.c
Board related SPI master and SPI device implementation.
2. SPI Framework
Linux has two level SPI devices: SPI master and SPI device.
SPI master is SPI bus controller, and it really handles the hardware. struct spi_master specifies the details of SPI master. Its driver operates the hardware to transfer and/or receive data to/from the SPI device. Under each SPI master (or SPI bus), there could be more than 1 SPI devices.
SPI device is the presentation of the SPI slave in kernel. struct spi_device specifies the details of SPI device. In order to communicate with the SPI slave device, there must be one SPI device existing in the kernel.
Normally, platform data for SPI master and device are statically defined in board specific file. To make it work, SPI master driver and SPI device driver need to be implemented.
2.1. SPI Master Driver
SPI master driver should be registered with probe() function. When SPI master device is found, the probe() function will be called.
The probe() function will initialize the SPI hardware based on the platform data of SPI master. It will allocate struct spi_master and register it to the system. The it will scan the platform data to find the SPI devices connected to this SPI bus.
scan_boardinfo() scans the platform data, and call spi_new_device() to create SPI device data structure, and set up struct spi_device based on the platform information. Then it calls the master's setup() method to further initialize, link the struct spi_device with struct spi_master, and add the SPI device to the system.
To this point, the SPI master and SPI device are created and added to the system. But it still can't communicate with the SPI device as no specific driver is installed yet.
2.2. SPI Device Driver
SPI device needs a driver to work. A general char device driver is implemented in Linux to support basic read()/write()/ioctl() methods. To link up the SPI device with this driver, just need to define the modalias of struct spi_board_info to "spidev".
If a driver is available for SPI device, its probe() method will be called when the SPI device is created and added to the system.
2.3. SPI Data Transfer
The user application needs a SPI device to access the data transfer service from SPI. Read/write/ioctl can be used for data transfer. The SPI device driver utlizes the SPI framework structures to communicate with SPI master driver. The struct spi_message is used to schedule a message to the SPI master's queue. Each message might includes a list of struct spi_transfer.
The SPI master's transfer function will be called by the SPI device driver to start the transfer. The SPI device driver normally needs to wait the SPI master finishs the transfer before return to the user application.
The SPI master driver needs to implement a mechanism to send the data on the SPI bus using the SPI device specified settings. It's the SPI master driver's responsibilities to operate the hardware to send out the data. Normally, the SPI master needs to implement:
- a message queue: to hold the messages from the SPI device driver
- a workqueue and workqueue thread: to pump the messages from the message queue and start transfer
- a tasklet and tasklet handler: to send the data on the hardware
- a interrupt handler: to handle the interrupts during the transfer
While the SPI master transfering the data, the SPI device driver normally implement a completion to wait the SPI master finishes the transfer.
3. Data Structure Example
This data structure example is taken from ST Cartesio MSP SPI Driver. Click the picture to view a big one.
2009-12-04
Linux USB Gadget Storage (quote)
Backing Storage for the File-backed Storage Gadget
Last Modified: 14 June 2005bash# modprobe g_file_storage file=/root/data/backing_file |
bash# modprobe g_file_storage file=/root/data/backing_file,/dev/hda7 |
AN IMPORTANT WARNING! While FSG is running and the gadget is connected to a USB host, that USB host will use the backing storage as a private disk drive. It will not expect to see any changes in the backing storage other than the ones it makes. Extraneous changes are liable to corrupt the filesystem and may even crash the host. Only one system (normally, the USB host) may write to the backing storage, and if one system is writing that data, no other should be reading it. The only safe way to share the backing storage between the host and the gadget's operating system at the same time is to make it read-only on both sides.
Creating a backing storage file
Backing storage requires some preparation before FSG can use it. To start with, if the backing storage is a regular file then the file must be created beforehand, with its full desired size. (FSG won't create a backing storage file and won't change the size of an existing file.) In the example above, if you wanted /root/data/backing_file to represent a 64MB drive then you would have to create it using a command something like this:bash# dd bs=1M count=64 if=/dev/zero of=/root/data/backing_file 64+0 records in 64+0 records out |
Partitioning the backing storage
However, creating the backing storage isn't enough. It's like having a raw disk drive; you still need to partition the disk and install a filesystem before you can use it. (Strictly speaking you don't need to partition it. You can treat the entire drive as a single large device, like a floppy disk. This will be confusing, though, and some versions of Windows won't work with an unpartitioned USB drive.) Okay, so how do you partition the backing storage?Answer: You create a partition table by using the fdisk program. Here's an example showing how to do it. The example assumes you will want to use the gadget with a Windows host. It's a little tricky because fdisk needs help when working with something other than an actual device. Begin by starting up fdisk and telling it the name of your backing storage. You'll get a message something like this:
bash# fdisk /root/data/backing_file Device contains neither a valid DOS partition table, nor Sun or SGI disklabel Building a new DOS disklabel. Changes will remain in memory only, until you decide to write them. After that, of course, the previous content won't be recoverable. You must set heads sectors and cylinders. You can do this from the extra functions menu. Command (m for help): |
Heads, Sectors, and Cylinders
As you see, fdisk says that it needs you to set the heads, sectors, and cylinders values. (Some versions only say they need you to set the number of cylinders, but they're wrong. You can tell by the way they'll miscalculate the size of the backing file; they're using default values and ignoring the actual file size.) The numbers you use are somewhat arbitrary; the scheme shown here works okay. Give the "x" (eXpert or eXtra) command:Command (m for help): x |
Expert command (m for help): s Number of sectors (1-63): 8 Warning: setting sector offset for DOS compatiblity |
Expert command (m for help): h Number of heads (1-256): 16 |
Expert command (m for help): c Number of cylinders (1-131071): 1024 |
Expert command (m for help): r |
Creating a primary partition
Create a new primary partition ("n" for new). Let's make it number 1. The defaults for the starting and ending cylinder are perfect because they will make the partition occupy the entire backing file, so just press Enter when asked for the First and Last cylinder:Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 First cylinder (1-1024, default 1): Using default value 1 Last cylinder or +size or +sizeM or +sizeK (1-1024, default 1024): Using default value 1024 |
Command (m for help): t Partition number (1-4): 1 Hex code (type L to list codes): b Changed system type of partition 1 to b (Win95 FAT32) |
Command (m for help): p
Disk /root/data/backing_file: 16 heads, 8 sectors, 1024 cylinders
Units = cylinders of 128 * 512 bytes
Device Boot Start End Blocks Id System
/root/data/backing_file1 1 1024 65532 b Win95 FAT32 |
Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Re-read table failed with error 25: Inappropriate ioctl for device. Reboot your system to ensure the partition table is updated. WARNING: If you have created or modified any DOS 6.x partitions, please see the fdisk manual page for additional information. Syncing disks. |
Adding a filesystem
At this point a new partition has been created but it doesn't yet contain a filesystem. The easiest way to add a filesystem is to load g_file_storage, connect the gadget to a USB host, and use the host to do the work. With a Linux host you can run mkdosfs; with a Windows host you can double-click on the drive's icon in the "My Computer" window.Accessing the backing storage from the gadget
It is possible to manipulate the data in the backing storage from the gadget (even to add the filesystem). Don't do this while the gadget is connected to a USB host! The key is to use the loop device driver with the "-o" (offset) option for the losetup program.For this to work, you have to know what the partition's offset is. If you followed the partitioning scheme given above then the offset will always be 4096. If not, you can use fdisk to find the correct offset value:
# fdisk -lu /root/data/backing_file
You must set cylinders.
You can do this from the extra functions menu.
Disk data: 0 MB, 0 bytes
16 heads, 8 sectors/track, 0 cylinders, total 0 sectors
Units = sectors of 1 * 512 = 512 bytes
Device Boot Start End Blocks Id System
/root/data/backing_file1 8 8191 4092 b Win95 FAT32 |
# losetup -o 4096 /dev/loop0 /root/data/backing_file |
# mkdosfs /dev/loop0 |
# mount -t vfat /dev/loop0 /mnt/loop |
# umount /dev/loop0 # losetup -d /dev/loop0
Labels:
linux,
technical,
usb,
usb gadget storage,
usb storage
Loop mount JFFS2 image(quote)
Loop mount JFFS2 image
maemo.org provide two solution to solve the issue.
Block Device Emulating a MTD
Kernel Memory Emulating a MTD
I think the second method is very convenient. The method is:
mknod /tmp/mtdblock0 b 31 0
modprobe mtdblock
modprobe mtdram total_size=65536 erase_size=256
modprobe jffs2
dd if=/pathtoimage/rootfs.jffs2 of=/tmp/mtdblock0
mkdir /media/jffs2
mount -t jffs2 /tmp/mtdblock0 /media/jffs2
Very good method! And I cost about 24 hours to find it. So keep it here.
FPGA Drive (quote)
XScale PXA270在Linux下的FPGA设备驱动 | |||||||||
北京航空航天大学 乾正光 王田苗 魏洪兴 | |||||||||
引言 Intel 公司推出的XScale 采用ARM V5TE结构,是Strong ARM的升级换代产品。XScale PXA270处理器最高主频可达到624M赫兹,加入了Wireless MMX、Intel SpeedStep等新技术,以其高性能、低功耗、多功能等特点在信息家电、工业控制等领域得到了广泛的应用。在嵌入式控制中,“微处理器+FPGA”是 一种常用的解决方案,FPGA(现场可编程门阵列)有编程方便、集成度高、速度快等特点,电子设计人员可以通过硬件编程的方法来实现FPGA芯片各种功能 的开发,在我们的一个数控平台的研究项目中,采用XScale PXA270作为主CPU,并对其进行FPGA扩展,使其具有插补、电机驱动、信号处理、I/O口扩展的功能。Linux以其内核精炼、高效、源代码开放 且免费等优势,嵌入式领域得到了广泛的应用。下面以Intel XScale PXA270上的Altera FLEX/ACEX的应用为例,详细介绍Linux下的FPGA设备驱动的实现。 1 Altera FLEX/ACEX芯片结构 Altera FLEX/ACEX芯片是基于查找表LUT(Look-Up-Table)原理而实现的,LUT本质上就是一个RAM。目前FPGA中多使用4输入的 LUT,所以每个LUT可以看成一个有4位地址线的16×1的RAM。当用户通过原理图或HDL语言描述一个逻辑电路以后,FPGA开发软件会自动计算逻 辑电路的所有可能的结果,并把结果事先写入RAM,这样,每输入一个信号进行逻辑运算都等于输入一个地址进行查表,找出地址对应的内容,然后输出即可。 由 于LUT主要适合SRAM工艺生产,所以目前大部分FPGA都是基于SRAM工艺的,而SRAM工艺的芯片在 掉电后信息就会丢失,一定要外加1片专用配置芯片(本实验电路使用Altera EPC2LC20),在上电时,由这个专用配置芯片把数据加载到FPGA中然后FPGA即可正常工作。由于配置时间很短,因此不会影响系统正常工作,在使 用ACEX1K50之前,应对其进行设计编程,实现相应寄存器及I/O口的功能。有关FPGA的详细内容请参阅相关资料。 2 Intel XScale PXA270处理器的系统存储器接口 PXA270处理器的可编程静态存储体系结构如图1所示。 3.1 Linux下设备驱动基本原理 设备驱动程序是应用程序与硬件之间的一个中间软件层,设备驱动程序为应用程序屏蔽了硬件的细节。这样在应用程序看来,硬件设备只是一个设备文件,应用程序 可以像操作普通文件一样对应用设备进行操作,设备驱动程序是内核的一部分,它主要实现的功能有:对设备进行初始化和释放;把数据从内核传送到硬件和从硬件 读取数据;读取应用程序传送给设备文件的数据,回送应用程序请求的数据以及检测和处理设备出现的错误。 Linux 将设备分为最基本的两大类:一类是字符设备;另一类是块设备,字符设备和块设备的主要区别在于是否使用了缓冲技术,字符设备以单个字节为单位进行顺序读/ 写操作,通常不使用缓冲技术,块设备为了提高效率,利用一块系统内存作为读/写操作的缓冲区,由于涉及缓冲区管理、调度和同步等问题,实现起来比字符设备 复杂得多。 Linux通过设备文件系统对设备进行管理,各种设备都以文件的形式存放在/dev目录下,称为 “设备文件”。应用程序可以像普通文件一样打开、关闭和读/写这些设备文件,为了管理这些设备,系统为设备编了号,每个设备号又分为主设备号和次设备号, 主设备号用来区分不同种类的设备,而次设备号用来区分同一类型的多个设备,Linux为所有的设备文件都提供了统一的操作函数接口,方法是使用数据结构 struct FILE_operations,这个数据结构中包括许多操作函数的指针,如open()、close()、read()和write()等,但由于外设 的种类较多,操作方式各不相同,struct file_operations结构体中的成员为一系列的接口函数,如用于读/写的read/write函数和用于控制的ioct1等。打开一个文件就是 调用这个文件file_operations中的open操作,不同类型的文件(如普通的磁盘数据文件)有不同的file_operations成员函 数,接口函数完成磁盘数据块读/写操作,而对于各种设备文件,则最终调用各自驱动程序中的I/O函数进行具体设备的操作,这样,应用程序根本不必考虑操作 的是设备还是普通文件,可一律当做文件处理,具有非常清晰、统一的I/O接口,所以file_operations是文件层次的I/O接口。 3.2 ACEX1K50在Linux下设备驱动的实现 驱动程序中使用内存映射可以提供给用户程序直接访问设备内存的能力。使用内存映射得好处是处理大文件时速度明显快于标准文件I/O,无论读/写,都少了一次用户空间与内核空间之间的复制,在用户空间对ACEX1K50 FPGA设备的访问是通过内存映射来实现的。 ACEX1K50可以看作是硬件连接在PXA270微处理器的nCS<2>上的一段物理地址来寻址。因为有虚拟内存管理单元,所以如果Linux下,必须先把物理地址映射到虚拟地址空间,然后才能对该段地址进行读/写。 在 内核驱动程序的初始化阶段,通过ioremap()将ACEX1K50的这段物理地址映射到内核虚拟空间;在驱动程序的mmap系统调用中,使用 remap_page_range()将该块COM映射到用户虚拟空间,这样内核空间和用户空间都能访问ACEX1K50的这段被映射后的虚拟地址。 由于ACEX1K50位于nCS<2>上,参照PXA270静态存储体系结构映射表,其物理起始地址为0x08000000。另外,其设备名称及主次设备号定义如下: ioremap()的作为是把一个物理内存地址点映射为一个内核指针,被映射数据的长度由size参数设定,该函数的实质上把一块物理区域二次映射到一个可以从驱动程序里访问的虚拟地址上去,以下是该函数的定义: void*ioremap(unsigned long phys_addr,unsigned long size); 设备驱动通过fpga_init()函数初始化FPGA设备,最终通过init_module(fpga_init)在内核启动时初始化FPGA设备。 fpga_init()函数的流程如图3所示。 pxa270_fpga_base=(unsigned long)ioremap(FPGA_PHY_START,SZ_4K); 可以通过ioremap()调用的返回值pxa270_fpga_base来判断FPGA物理地址到内核虚拟空间是否映射成功。 if(!pxa270_fpga_base){ printk(“ioremap pxa270 fpga failed\n”); return-EINVAL; } 向设备文件系统注销FPGA设备通过调用cheanup_module()函数来实现。其代码如下: 当设备驱动实现后就可以在用户空间使用该设备了。在用户空间主要是通过调用mmap()函数来实现对FPGA设备的访问。以下是用户空间应用程序的一个示例: 本文通过介绍ACEX1K50在Linux操作系统下设备驱动的实现过程,为FPGA在嵌入式领域的应用提供了一种方法。在实际应用中,通过用户程序能够很好地实现对FPGA硬件编程后的各种功能的控制。 |
Linux kernel Competion Events
Completions are a simple synchronization mechanism that is preferable to sleeping and waking up in some situations. If you have a task that must simply sleep until some process has run its course, completions can do it easily and without race conditions. They are not strictly a 2.6 feature, having been added in 2.4.7, but they merit a quick summary here.
A completion is, essentially, a one-shot flag that says "things may proceed." Working with completions requires including <linux/completion.h> and creating a variable of type struct completion. This structure may be declared and initialized statically with:
If you do not use complete_all(), you should be able to use a completion structure multiple times without problem. It does not hurt, however, to reinitialize the structure before each use - so long as you do it before initiating the process that will call complete()! The macro INIT_COMPLETION() can be used to quickly reinitialize a completion structure that has been fully initialized at least once.
A completion is, essentially, a one-shot flag that says "things may proceed." Working with completions requires including <linux/completion.h> and creating a variable of type struct completion. This structure may be declared and initialized statically with:
DECLARE_COMPLETION(my_comp);A dynamic initialization would look like:
struct completion my_comp;
init_completion(&my_comp);
When your driver begins some process whose completion must be waited for, it's simply a matter of passing your completion event to wait_for_completion(): void wait_for_completion(struct completion *comp);When some other part of your code has decided that the completion has happened, it can wake up anybody who is waiting with one of:
void complete(struct completion *comp);
void complete_all(struct completion *comp);
The first form will wake up exactly one waiting process, while the second will wake up all processes waiting for that event. Note that completions are implemented in such a way that they will work properly even if complete() is called before wait_for_completion(). If you do not use complete_all(), you should be able to use a completion structure multiple times without problem. It does not hurt, however, to reinitialize the structure before each use - so long as you do it before initiating the process that will call complete()! The macro INIT_COMPLETION() can be used to quickly reinitialize a completion structure that has been fully initialized at least once.
Linux 2.6 SPI Device Driver(quote)
Linux 2.6下SPI设备模型
--------基于AT91RM9200分析
Atmel公司的ARM AT系列,其SPI驱动在kernel 2.6.23里已经包含。如果你打了at91-patch补丁的话,则在内核配置时要小心。在Device Drivers---- > Character devices ---- >取消选中SPI Driver(legacy) for at91rm9200 processor 。同时Device Drivers---- >SPI Support ---- > 选中SPI Support ,Atmel SPI Controler,同时选中 User mode SPI device driver support 。
SPI Driver(legacy) for at91rm9200 processor是保留选项,为了兼容以前版本。如果同时选中SPI Driver(legacy) for at91rm9200 processor,则在/sys里无法注册类spidev,也就无法将设备和驱动联系在一起。与现有atmel spi驱动发生冲突。
各选项对应的编译情况如下:
[*]SPI support ---- Config_SPI 开启SPI功能
[*]Debug support for SPI drivers ---- config SPI_DEBUG 开启SPI debug调试
----SPI Master Controller Drivers ---- depends on SPI_MASTER 生成spi.o
<*>Atmel SPI Controller ---- config SPI_ATMEL 生成atmel_spi.o
<*>Bitbanging SPI master ---- config SPI_BITBANG 生成spi_bitbang.o
<*>AT91RM9200 Bitbang SPI Master ---- CONFIG_SPI_AT91 spi_at91_bitbang.o
---- SPI Protocol Masters ---- depends on SPI_MASTER
< >SPI EEPROMs from most vendors ---- config SPI_AT25 生成at25.o
<*>User mode SPI device driver support ---- config SPI_SPIDEV 生成spidev.o
总线
注册SPI总线
#spi.c
struct bus_type spi_bus_type = {
.name = "spi", // spi总线名称
.dev_attrs = spi_dev_attrs,
.match = spi_match_device,
.uevent = spi_uevent,
.suspend = spi_suspend,
.resume = spi_resume,
};
spi总线将在sysfs/bus下显示。
其bus_type 结构表示总线,它的定义在<linux/device.h>中,如下
struct bus_type {
const char * name;
struct module * owner;
struct kset subsys;
struct kset drivers;
struct kset devices;
struct klist klist_devices;
struct klist klist_drivers;
struct blocking_notifier_head bus_notifier;
struct bus_attribute * bus_attrs;
struct device_attribute * dev_attrs;
struct driver_attribute * drv_attrs;
struct bus_attribute drivers_autoprobe_attr;
struct bus_attribute drivers_probe_attr;
int (*match)(struct device * dev, struct device_driver * drv);
int (*uevent)(struct device *dev, char **envp,
int num_envp, char *buffer, int buffer_size);
int (*probe)(struct device * dev);
int (*remove)(struct device * dev);
void (*shutdown)(struct device * dev);
int (*suspend)(struct device * dev, pm_message_t state);
int (*suspend_late)(struct device * dev, pm_message_t state);
int (*resume_early)(struct device * dev);
int (*resume)(struct device * dev);
unsigned int drivers_autoprobe:1;
};
其中,当一个总线上的新设备或者新驱动被添加时,*match 函数会被调用。如果指定的驱动程序能够处理指定的设备,该函数返回非零值。
对于spi总线,我们必须调用bus_register(&spi_bus_type)进行注册。调用如果成功,SPI总线子系统将被添加到系统中,在sysfs的/sys/bus目录下可以看到。然后,我们就可以向这个总线添加设备了。代码见下:
static int __init spi_init(void)
{
int status;
buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
if (!buf) {
status = -ENOMEM;
goto err0;
}
status = bus_register(&spi_bus_type);
if (status < 0)
goto err1;
status = class_register(&spi_master_class);
if (status < 0)
goto err2;
return 0;
err2:
bus_unregister(&spi_bus_type);
err1:
kfree(buf);
buf = NULL;
err0:
return status;
}
设备
spi设备的结构如下:
#spi.h
struct spi_device {
struct device dev;
struct spi_master *master;
u32 max_speed_hz;
u8 chip_select;
u8 mode;
#define SPI_CPHA 0x01 /* clock phase */
#define SPI_CPOL 0x02 /* clock polarity */
#define SPI_MODE_0 (0|0) /* (original MicroWire) */
#define SPI_MODE_1 (0|SPI_CPHA)
#define SPI_MODE_2 (SPI_CPOL|0)
#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)
#define SPI_CS_HIGH 0x04 /* chipselect active high? */
#define SPI_LSB_FIRST 0x08 /* per-word bits-on-wire */
#define SPI_3WIRE 0x10 /* SI/SO signals shared */
#define SPI_LOOP 0x20 /* loopback mode */
u8 bits_per_word;
int irq;
void *controller_state;
void *controller_data;
const char *modalias;
/*
* likely need more hooks for more protocol options affecting how
* the controller talks to each chip, like:
* - memory packing (12 bit samples into low bits, others zeroed)
* - priority
* - drop chipselect after each word
* - chipselect delays
* - ...
*/
};
device结构中包含了设备模型核心用来模拟系统的信息。spidev还有设备的其他信息,因此spi设备结构包含在spidev_data结构里。
struct spidev_data {
struct device dev;
struct spi_device *spi;
struct list_head device_entry;
struct mutex buf_lock;
unsigned users;
u8 *buffer;
};
注册spi设备,
#spidev.c
static int spidev_probe(struct spi_device *spi)
{
…
…
status = device_register(&spidev->dev);
…
…
}
完成这个调用之后,我们就可以在sysfs中看到它了。
SPI设备驱动程序
spi驱动程序结构如下:
struct spi_driver {
int (*probe)(struct spi_device *spi);
int (*remove)(struct spi_device *spi);
void (*shutdown)(struct spi_device *spi);
int (*suspend)(struct spi_device *spi, pm_message_t mesg);
int (*resume)(struct spi_device *spi);
struct device_driver driver;
};
spi驱动程序注册函数如下:
int spi_register_driver(struct spi_driver *sdrv)
{
sdrv->driver.bus = &spi_bus_type;
if (sdrv->probe)
sdrv->driver.probe = spi_drv_probe;
if (sdrv->remove)
sdrv->driver.remove = spi_drv_remove;
if (sdrv->shutdown)
sdrv->driver.shutdown = spi_drv_shutdown;
return driver_register(&sdrv->driver);
}
spidev的驱动名如下:
static struct spi_driver spidev_spi = {
.driver = {
.name = "spidev",
.owner = THIS_MODULE,
},
.probe = spidev_probe,
.remove = __devexit_p(spidev_remove),
};
一个spi_register_driver调用将spidev添加到系统中。一旦初始化完成,就可以在sysfs中看到驱动程序信息。
类
spidev类结构如下:
static struct class spidev_class = {
.name = "spidev",
.owner = THIS_MODULE,
.dev_release = spidev_classdev_release,
};
AT91RM9200 SPIDEV初始化
AT91RM9200的spi驱动,对于EK板,原先的SPI是用于dataflash的。其代码如下:
static struct spi_board_info ek_spi_devices[] = {
{ /* DataFlash chip */
.modalias = "mtd_dataflash",
.chip_select = 0,
.max_speed_hz = 15 * 1000 * 1000,
},
我们需要将.modalias改成我们自己的spi设备名
在spi设备初始化代码中,class_register(&spidev_class)注册类,spi_register_driver(&spidev_spi)注册spidev驱动。
#drivers/spi/spidev.c
static int __init spidev_init(void)
{
int status;
/* Claim our 256 reserved device numbers. Then register a class
* that will key udev/mdev to add/remove /dev nodes. Last, register
* the driver which manages those device numbers.
*/
BUILD_BUG_ON(N_SPI_MINORS > 256);
status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops);
if (status < 0)
return status;
status = class_register(&spidev_class);
if (status < 0) {
unregister_chrdev(SPIDEV_MAJOR, spidev_spi.driver.name);
return status;
}
status = spi_register_driver(&spidev_spi);
if (status < 0) {
class_unregister(&spidev_class);
unregister_chrdev(SPIDEV_MAJOR, spidev_spi.driver.name);
}
return status;
}
挂载/sys
mount –t sysfs sysfs /sys
可以看到有/sys/class/spidev/spidev0.0,表明设备已经挂载在总线上了,同时与驱动联系起来。
使用mdev –s,可以在/dev下看到spidev0.0这个设备了。
自此,spi设备驱动就可以工作了。
测试程序:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
static int verbose;
static void do_read(int fd, int len)
{
unsigned char buf[32], *bp;
int status;
/* read at least 2 bytes, no more than 32 */
if (len < 2)
len = 2;
else if (len > sizeof(buf))
len = sizeof(buf);
memset(buf, 0, sizeof buf);
status = read(fd, buf, len);
if (status < 0) {
perror("read");
return;
}
if (status != len) {
fprintf(stderr, "short read\n");
return;
}
printf("read(%2d, %2d): %02x %02x,", len, status,
buf[0], buf[1]);
status -= 2;
bp = buf + 2;
while (status-- > 0)
printf(" %02x", *bp++);
printf("\n");
}
static void do_msg(int fd, int len)
{
struct spi_ioc_transfer xfer[2];
unsigned char buf[32], *bp;
int status;
memset(xfer, 0, sizeof xfer);
memset(buf, 0, sizeof buf);
if (len > sizeof buf)
len = sizeof buf;
buf[0] = 0xaa;
xfer[0].tx_buf = (__u64) buf;
xfer[0].len = 1;
xfer[1].rx_buf = (__u64) buf;
xfer[1].len = len;
status = ioctl(fd, SPI_IOC_MESSAGE(2), xfer);
if (status < 0) {
perror("SPI_IOC_MESSAGE");
return;
}
printf("response(%2d, %2d): ", len, status);
for (bp = buf; len; len--)
printf(" %02x", *bp++);
printf("\n");
}
static void dumpstat(const char *name, int fd)
{
__u8 mode, lsb, bits;
__u32 speed;
if (ioctl(fd, SPI_IOC_RD_MODE, &mode) < 0) {
perror("SPI rd_mode");
return;
}
if (ioctl(fd, SPI_IOC_RD_LSB_FIRST, &lsb) < 0) {
perror("SPI rd_lsb_fist");
return;
}
if (ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits) < 0) {
perror("SPI bits_per_word");
return;
}
if (ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed) < 0) {
perror("SPI max_speed_hz");
return;
}
printf("%s: spi mode %d, %d bits %sper word, %d Hz max\n",
name, mode, bits, lsb ? "(lsb first) " : "", speed);
}
int main(int argc, char **argv)
{
int c;
int readcount = 0;
int msglen = 0;
int fd;
const char *name;
while ((c = getopt(argc, argv, "hm:r:v")) != EOF) {
switch (c) {
case 'm':
msglen = atoi(optarg);
if (msglen < 0)
goto usage;
continue;
case 'r':
readcount = atoi(optarg);
if (readcount < 0)
goto usage;
continue;
case 'v':
verbose++;
continue;
case 'h':
case '?':
usage:
fprintf(stderr,
"usage: %s [-h] [-m N] [-r N] /dev/spidevB.D\n",
argv[0]);
return 1;
}
}
if ((optind + 1) != argc)
goto usage;
name = argv[optind];
fd = open(name, O_RDWR);
if (fd < 0) {
perror("open");
return 1;
}
dumpstat(name, fd);
if (msglen)
do_msg(fd, msglen);
if (readcount)
do_read(fd, readcount);
close(fd);
return 0;
}
备注:
如果要设置模式,速率等,则可仿照以下语句:
speed =10*1000*1000; //10MHz
if (ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed) < 0) {
perror("SPI max_speed_hz");
return;
}
默认spi_io_transfer时,每个字节之间有延时。在atmel_spi_setup.c文件里去掉该延时语句:
/* TODO: DLYBS and DLYBCT */
//csr |= SPI_BF(DLYBS, 10);
//csr |= SPI_BF(DLYBCT, 10);
这样就可以达到无间隙快速传输批量数据。
标准read(),write()两个函数仅适用于半双工传输,。在传输之间不激活片选。而SPI_IOC_MESSAGE(N)则是全双工传输,并且片选始终激活。
SPI_IOC_MESSAGE传输长度有限制,默认是一页的长度,但是可以更改。
spi_ioc_transfer结构的spi长度 是字节长度,16位传输的时候要注意。
--------基于AT91RM9200分析
Atmel公司的ARM AT系列,其SPI驱动在kernel 2.6.23里已经包含。如果你打了at91-patch补丁的话,则在内核配置时要小心。在Device Drivers---- > Character devices ---- >取消选中SPI Driver(legacy) for at91rm9200 processor 。同时Device Drivers---- >SPI Support ---- > 选中SPI Support ,Atmel SPI Controler,同时选中 User mode SPI device driver support 。
SPI Driver(legacy) for at91rm9200 processor是保留选项,为了兼容以前版本。如果同时选中SPI Driver(legacy) for at91rm9200 processor,则在/sys里无法注册类spidev,也就无法将设备和驱动联系在一起。与现有atmel spi驱动发生冲突。
各选项对应的编译情况如下:
[*]SPI support ---- Config_SPI 开启SPI功能
[*]Debug support for SPI drivers ---- config SPI_DEBUG 开启SPI debug调试
----SPI Master Controller Drivers ---- depends on SPI_MASTER 生成spi.o
<*>Atmel SPI Controller ---- config SPI_ATMEL 生成atmel_spi.o
<*>Bitbanging SPI master ---- config SPI_BITBANG 生成spi_bitbang.o
<*>AT91RM9200 Bitbang SPI Master ---- CONFIG_SPI_AT91 spi_at91_bitbang.o
---- SPI Protocol Masters ---- depends on SPI_MASTER
< >SPI EEPROMs from most vendors ---- config SPI_AT25 生成at25.o
<*>User mode SPI device driver support ---- config SPI_SPIDEV 生成spidev.o
总线
注册SPI总线
#spi.c
struct bus_type spi_bus_type = {
.name = "spi", // spi总线名称
.dev_attrs = spi_dev_attrs,
.match = spi_match_device,
.uevent = spi_uevent,
.suspend = spi_suspend,
.resume = spi_resume,
};
spi总线将在sysfs/bus下显示。
其bus_type 结构表示总线,它的定义在<linux/device.h>中,如下
struct bus_type {
const char * name;
struct module * owner;
struct kset subsys;
struct kset drivers;
struct kset devices;
struct klist klist_devices;
struct klist klist_drivers;
struct blocking_notifier_head bus_notifier;
struct bus_attribute * bus_attrs;
struct device_attribute * dev_attrs;
struct driver_attribute * drv_attrs;
struct bus_attribute drivers_autoprobe_attr;
struct bus_attribute drivers_probe_attr;
int (*match)(struct device * dev, struct device_driver * drv);
int (*uevent)(struct device *dev, char **envp,
int num_envp, char *buffer, int buffer_size);
int (*probe)(struct device * dev);
int (*remove)(struct device * dev);
void (*shutdown)(struct device * dev);
int (*suspend)(struct device * dev, pm_message_t state);
int (*suspend_late)(struct device * dev, pm_message_t state);
int (*resume_early)(struct device * dev);
int (*resume)(struct device * dev);
unsigned int drivers_autoprobe:1;
};
其中,当一个总线上的新设备或者新驱动被添加时,*match 函数会被调用。如果指定的驱动程序能够处理指定的设备,该函数返回非零值。
对于spi总线,我们必须调用bus_register(&spi_bus_type)进行注册。调用如果成功,SPI总线子系统将被添加到系统中,在sysfs的/sys/bus目录下可以看到。然后,我们就可以向这个总线添加设备了。代码见下:
static int __init spi_init(void)
{
int status;
buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
if (!buf) {
status = -ENOMEM;
goto err0;
}
status = bus_register(&spi_bus_type);
if (status < 0)
goto err1;
status = class_register(&spi_master_class);
if (status < 0)
goto err2;
return 0;
err2:
bus_unregister(&spi_bus_type);
err1:
kfree(buf);
buf = NULL;
err0:
return status;
}
设备
spi设备的结构如下:
#spi.h
struct spi_device {
struct device dev;
struct spi_master *master;
u32 max_speed_hz;
u8 chip_select;
u8 mode;
#define SPI_CPHA 0x01 /* clock phase */
#define SPI_CPOL 0x02 /* clock polarity */
#define SPI_MODE_0 (0|0) /* (original MicroWire) */
#define SPI_MODE_1 (0|SPI_CPHA)
#define SPI_MODE_2 (SPI_CPOL|0)
#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)
#define SPI_CS_HIGH 0x04 /* chipselect active high? */
#define SPI_LSB_FIRST 0x08 /* per-word bits-on-wire */
#define SPI_3WIRE 0x10 /* SI/SO signals shared */
#define SPI_LOOP 0x20 /* loopback mode */
u8 bits_per_word;
int irq;
void *controller_state;
void *controller_data;
const char *modalias;
/*
* likely need more hooks for more protocol options affecting how
* the controller talks to each chip, like:
* - memory packing (12 bit samples into low bits, others zeroed)
* - priority
* - drop chipselect after each word
* - chipselect delays
* - ...
*/
};
device结构中包含了设备模型核心用来模拟系统的信息。spidev还有设备的其他信息,因此spi设备结构包含在spidev_data结构里。
struct spidev_data {
struct device dev;
struct spi_device *spi;
struct list_head device_entry;
struct mutex buf_lock;
unsigned users;
u8 *buffer;
};
注册spi设备,
#spidev.c
static int spidev_probe(struct spi_device *spi)
{
…
…
status = device_register(&spidev->dev);
…
…
}
完成这个调用之后,我们就可以在sysfs中看到它了。
SPI设备驱动程序
spi驱动程序结构如下:
struct spi_driver {
int (*probe)(struct spi_device *spi);
int (*remove)(struct spi_device *spi);
void (*shutdown)(struct spi_device *spi);
int (*suspend)(struct spi_device *spi, pm_message_t mesg);
int (*resume)(struct spi_device *spi);
struct device_driver driver;
};
spi驱动程序注册函数如下:
int spi_register_driver(struct spi_driver *sdrv)
{
sdrv->driver.bus = &spi_bus_type;
if (sdrv->probe)
sdrv->driver.probe = spi_drv_probe;
if (sdrv->remove)
sdrv->driver.remove = spi_drv_remove;
if (sdrv->shutdown)
sdrv->driver.shutdown = spi_drv_shutdown;
return driver_register(&sdrv->driver);
}
spidev的驱动名如下:
static struct spi_driver spidev_spi = {
.driver = {
.name = "spidev",
.owner = THIS_MODULE,
},
.probe = spidev_probe,
.remove = __devexit_p(spidev_remove),
};
一个spi_register_driver调用将spidev添加到系统中。一旦初始化完成,就可以在sysfs中看到驱动程序信息。
类
spidev类结构如下:
static struct class spidev_class = {
.name = "spidev",
.owner = THIS_MODULE,
.dev_release = spidev_classdev_release,
};
AT91RM9200 SPIDEV初始化
AT91RM9200的spi驱动,对于EK板,原先的SPI是用于dataflash的。其代码如下:
static struct spi_board_info ek_spi_devices[] = {
{ /* DataFlash chip */
.modalias = "mtd_dataflash",
.chip_select = 0,
.max_speed_hz = 15 * 1000 * 1000,
},
我们需要将.modalias改成我们自己的spi设备名
在spi设备初始化代码中,class_register(&spidev_class)注册类,spi_register_driver(&spidev_spi)注册spidev驱动。
#drivers/spi/spidev.c
static int __init spidev_init(void)
{
int status;
/* Claim our 256 reserved device numbers. Then register a class
* that will key udev/mdev to add/remove /dev nodes. Last, register
* the driver which manages those device numbers.
*/
BUILD_BUG_ON(N_SPI_MINORS > 256);
status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops);
if (status < 0)
return status;
status = class_register(&spidev_class);
if (status < 0) {
unregister_chrdev(SPIDEV_MAJOR, spidev_spi.driver.name);
return status;
}
status = spi_register_driver(&spidev_spi);
if (status < 0) {
class_unregister(&spidev_class);
unregister_chrdev(SPIDEV_MAJOR, spidev_spi.driver.name);
}
return status;
}
挂载/sys
mount –t sysfs sysfs /sys
可以看到有/sys/class/spidev/spidev0.0,表明设备已经挂载在总线上了,同时与驱动联系起来。
使用mdev –s,可以在/dev下看到spidev0.0这个设备了。
自此,spi设备驱动就可以工作了。
测试程序:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
static int verbose;
static void do_read(int fd, int len)
{
unsigned char buf[32], *bp;
int status;
/* read at least 2 bytes, no more than 32 */
if (len < 2)
len = 2;
else if (len > sizeof(buf))
len = sizeof(buf);
memset(buf, 0, sizeof buf);
status = read(fd, buf, len);
if (status < 0) {
perror("read");
return;
}
if (status != len) {
fprintf(stderr, "short read\n");
return;
}
printf("read(%2d, %2d): %02x %02x,", len, status,
buf[0], buf[1]);
status -= 2;
bp = buf + 2;
while (status-- > 0)
printf(" %02x", *bp++);
printf("\n");
}
static void do_msg(int fd, int len)
{
struct spi_ioc_transfer xfer[2];
unsigned char buf[32], *bp;
int status;
memset(xfer, 0, sizeof xfer);
memset(buf, 0, sizeof buf);
if (len > sizeof buf)
len = sizeof buf;
buf[0] = 0xaa;
xfer[0].tx_buf = (__u64) buf;
xfer[0].len = 1;
xfer[1].rx_buf = (__u64) buf;
xfer[1].len = len;
status = ioctl(fd, SPI_IOC_MESSAGE(2), xfer);
if (status < 0) {
perror("SPI_IOC_MESSAGE");
return;
}
printf("response(%2d, %2d): ", len, status);
for (bp = buf; len; len--)
printf(" %02x", *bp++);
printf("\n");
}
static void dumpstat(const char *name, int fd)
{
__u8 mode, lsb, bits;
__u32 speed;
if (ioctl(fd, SPI_IOC_RD_MODE, &mode) < 0) {
perror("SPI rd_mode");
return;
}
if (ioctl(fd, SPI_IOC_RD_LSB_FIRST, &lsb) < 0) {
perror("SPI rd_lsb_fist");
return;
}
if (ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits) < 0) {
perror("SPI bits_per_word");
return;
}
if (ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed) < 0) {
perror("SPI max_speed_hz");
return;
}
printf("%s: spi mode %d, %d bits %sper word, %d Hz max\n",
name, mode, bits, lsb ? "(lsb first) " : "", speed);
}
int main(int argc, char **argv)
{
int c;
int readcount = 0;
int msglen = 0;
int fd;
const char *name;
while ((c = getopt(argc, argv, "hm:r:v")) != EOF) {
switch (c) {
case 'm':
msglen = atoi(optarg);
if (msglen < 0)
goto usage;
continue;
case 'r':
readcount = atoi(optarg);
if (readcount < 0)
goto usage;
continue;
case 'v':
verbose++;
continue;
case 'h':
case '?':
usage:
fprintf(stderr,
"usage: %s [-h] [-m N] [-r N] /dev/spidevB.D\n",
argv[0]);
return 1;
}
}
if ((optind + 1) != argc)
goto usage;
name = argv[optind];
fd = open(name, O_RDWR);
if (fd < 0) {
perror("open");
return 1;
}
dumpstat(name, fd);
if (msglen)
do_msg(fd, msglen);
if (readcount)
do_read(fd, readcount);
close(fd);
return 0;
}
备注:
如果要设置模式,速率等,则可仿照以下语句:
speed =10*1000*1000; //10MHz
if (ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed) < 0) {
perror("SPI max_speed_hz");
return;
}
默认spi_io_transfer时,每个字节之间有延时。在atmel_spi_setup.c文件里去掉该延时语句:
/* TODO: DLYBS and DLYBCT */
//csr |= SPI_BF(DLYBS, 10);
//csr |= SPI_BF(DLYBCT, 10);
这样就可以达到无间隙快速传输批量数据。
标准read(),write()两个函数仅适用于半双工传输,。在传输之间不激活片选。而SPI_IOC_MESSAGE(N)则是全双工传输,并且片选始终激活。
SPI_IOC_MESSAGE传输长度有限制,默认是一页的长度,但是可以更改。
spi_ioc_transfer结构的spi长度 是字节长度,16位传输的时候要注意。
SPI Protocol Introduction(quote)
SPI概述
SPI:高速同步串行口。3~4线接口,收发独立、可同步进行.
SPI,是英语Serial Peripheral interface的缩写,顾名思义就是串行外围设备接口。是Motorola首先在其MC68HCXX系列处理器上定义的。SPI接口主要应用在 EEPROM,FLASH,实时时钟,AD转换器,还有数字信号处理器和数字信号解码器之间。SPI,是一种高速的,全双工,同步的通信总线,并且在芯片 的管脚上只占用四根线,节约了芯片的管脚,同时为PCB的布局上节省空间,提供方便,正是出于这种简单易用的特性,现在越来越多的芯片集成了这种通信协 议,比如AT91RM9200.
SPI总线系统是一种同步串行外设接口,它可以使MCU与各种外围设备以串行方式进行通信以交换信息。外围设置FLASHRAM、网络控制器、LCD显示 驱动器、A/D转换器和MCU等。SPI总线系统可直接与各个厂家生产的多种标准外围器件直接接口,该接口一般使用4条线:串行时钟线(SCK)、主机输 入/从机输出数据线MISO、主机输出/从机输入数据线MOST和低电平有效的从机选择线SS(有的SPI接口芯片带有中断信号线INT或INT、有的 SPI接口芯片没有主机输出/从机输入数据线MOSI)。
SPI的通信原理很简单,它以主从方式工作,这种模式通常有一个主设备和一个或多个从设备,需要至少4根线,事实上3根也可以(单向传输时)。也是所有基于SPI的设备共有的,它们是SDI(数据输入),SDO(数据输出),SCK(时钟),CS(片选)。
(1)SDO – 主设备数据输出,从设备数据输入
(2)SDI – 主设备数据输入,从设备数据输出
(3)SCLK – 时钟信号,由主设备产生
(4)CS – 从设备使能信号,由主设备控制
其中CS是控制芯片是否被选中的,也就是说只有片选信号为预先规定的使能信号时(高电位或低电位),对此芯片的操作才有效。这就允许在同一总线上连接多个SPI设备成为可能。
接下来就负责通讯的3根线了。通讯是通过数据交换完成的,这里先要知道SPI是串行通讯协议,也就是说数据是一位一位的传输的。这就是SCK时钟线存在的 原因,由SCK提供时钟脉冲,SDI,SDO则基于此脉冲完成数据传输。数据输出通过 SDO线,数据在时钟上升沿或下降沿时改变,在紧接着的下降沿或上升沿被读取。完成一位数据传输,输入也使用同样原理。这样,在至少8次时钟信号的改变 (上沿和下沿为一次),就可以完成8位数据的传输。
要注意的是,SCK信号线只由主设备控制,从设备不能控制信号线。同样,在一个基于SPI的设备中,至少有一个主控设备。这样传输的特点:这样的传输方式 有一个优点,与普通的串行通讯不同,普通的串行通讯一次连续传送至少8位数据,而SPI允许数据一位一位的传送,甚至允许暂停,因为SCK时钟线由主控设 备控制,当没有时钟跳变时,从设备不采集或传送数据。也就是说,主设备通过对SCK时钟线的控制可以完成对通讯的控制。SPI还是一个数据交换协议:因为 SPI的数据输入和输出线独立,所以允许同时完成数据的输入和输出。不同的SPI设备的实现方式不尽相同,主要是数据改变和采集的时间不同,在时钟信号上 沿或下沿采集有不同定义,具体请参考相关器件的文档。
在点对点的通信中,SPI接口不需要进行寻址操作,且为全双工通信,显得简单高效。在多个从设备的系统中,每个从设备需要独立的使能信号,硬件上比I2C系统要稍微复杂一些。
最后,SPI接口的一个缺点:没有指定的流控制,没有应答机制确认是否接收到数据。
AT91RM9200的SPI接口主要由4个引脚构成:SPICLK、MOSI、MISO及 /SS,其中SPICLK是整个SPI总线的公用时钟,MOSI、MISO作为主机,从机的输入输出的标志,MOSI是主机的输出,从机的输入,MISO 是主机的输入,从机的输出。/SS是从机的标志管脚,在互相通信的两个SPI总线的器件,/SS管脚的电平低的是从机,相反/SS管脚的电平高的是主机。 在一个SPI通信系统中,必须有主机。SPI总线可以配置成单主单从,单主多从,互为主从。
SPI的片选可以扩充选择16个外设,这时PCS输出=NPCS,说NPCS0~3接4-16译码器,这个译码器是需要外接4-16译码器,译码器的输入为NPCS0~3,输出用于16个外设的选择。
SPI协议举例
SPI是一个环形总线结构,由ss(cs)、sck、sdi、sdo构成,其时序其实很简单,主要是在sck的控制下,两个双向移位寄存器进行数据交换。
假设下面的8位寄存器装的是待发送的数据10101010,上升沿发送、下降沿接收、高位先发送。
那么第一个上升沿来的时候 数据将会是sdo=1;寄存器=0101010x。下降沿到来的时候,sdi上的电平将所存到寄存器中去,那么这时寄存器=0101010sdi,这样在 8个时钟脉冲以后,两个寄存器的内容互相交换一次。这样就完成里一个spi时序。
举例:
假设主机和从机初始化就绪:并且主机的sbuff=0xaa,从机的sbuff=0x55,下面将分步对spi的8个时钟周期的数据情况演示一遍:假设上升沿发送数据
这样就完成了两个寄存器8位的交换,上面的上表示上升沿、下表示下降沿,sdi、sdo相对于主机而言的。其中ss引脚作为主机的时候,从机可以把它拉底 被动选为从机,作为从机的是时候,可以作为片选脚用。根据以上分析,一个完整的传送周期是16位,即两个字节,因为,首先主机要发送命令过去,然后从机根 据主机的命令准备数据,主机在下一个8位时钟周期才把数据读回来。 SPI 总线是Motorola公司推出的三线同步接口,同步串行3线方式进行通信:一条时钟线SCK,一条数据输入线MOSI,一条数据输出线MISO;用于 CPU与各种外围器件进行全双工、同步串行通讯。SPI主要特点有:可以同时发出和接收串行数据;可以当作主机或从机工作;提供频率可编程时钟;发送结束 中断标志;写冲突保护;总线竞争保护等。下图示出SPI总线工作的四种方式,其中使用的最为广泛的是SPI0和SPI3方式 (实线表示):
SPI总线四种工作方式 SPI 模块为了和外设进行数据交换,根据外设工作要求,其输出串行同步时钟极性和相位可以进行配置,时钟极性(CPOL)对传输协议没有重大的影响。如果 CPOL=0,串行同步时钟的空闲状态为低电平;如果CPOL=1,串行同步时钟的空闲状态为高电平。时钟相位(CPHA)能够配置用于选择两种不同的传 输协议之一进行数据传输。如果CPHA=0,在串行同步时钟的第一个跳变沿(上升或下降)数据被采样;如果CPHA=1,在串行同步时钟的第二个跳变沿 (上升或下降)数据被采样。SPI主模块和与之通信的外设备时钟相位和极性应该一致。
SPI总线包括1根串行同步时钟信号线以及2根数据线。
SPI模块为了和外设进行数据交换,根据外设工作要求,其输出串行同步时钟极性和相位可以进行配置,时钟极性(CPOL)对传输协议没有重大的影响。如果 CPOL=0,串行同步时钟的空闲状态为低电平;如果CPOL=1,串行同步时钟的空闲状态为高电平。时钟相位(CPHA)能够配置用于选择两种不同的传 输协议之一进行数据传输。如果CPHA=0,在串行同步时钟的第一个跳变沿(上升或下降)数据被采样;如果CPHA=1,在串行同步时钟的第二个跳变沿 (上升或下降)数据被采样。SPI主模块和与之通信的外设音时钟相位和极性应该一致。SPI接口时序如图3、图4所示。
补充:
上文中最后一句话:SPI主模块和与之通信的外设备时钟相位和极性应该一致。个人理解这句话有2层意思:其一,主设备SPI时钟和极性的配置应该由外设来 决定;其二,二者的配置应该保持一致,即主设备的SDO同从设备的SDO配置一致,主设备的SDI同从设备的SDI配置一致。因为主从设备是在SCLK的 控制下,同时发送和接收数据,并通过2个双向移位寄存器来交换数据。工作原理演示如下图:
上升沿主机SDO发送数据1,同时从设备SDO发送数据0;紧接着在SCLK的下降沿的时候从设备的SDI接收到了主机发送过来的数据1,同时主机也接收到了从设备发送过来的数据0.
SPI协议心得
SPI接口时钟配置心得:
在主设备这边配置SPI接口时钟的时候一定要弄清楚从设备的时钟要求,因为主设备这边的时钟极性和相位都是以从设备为基准的。因此在时钟极性的配置上一定 要搞清楚从设备是在时钟的上升沿还是下降沿接收数据,是在时钟的下降沿还是上升沿输出数据。但要注意的是,由于主设备的SDO连接从设备的SDI,从设备 的SDO连接主设备的SDI,从设备SDI接收的数据是主设备的SDO发送过来的,主设备SDI接收的数据是从设备SDO发送过来的,所以主设备这边 SPI时钟极性的配置(即SDO的配置)跟从设备的SDI接收数据的极性是相反的,跟从设备SDO发送数据的极性是相同的。下面这段话是Sychip Wlan8100 Module Spec上说的,充分说明了时钟极性是如何配置的:
The 81xx module will always input data bits at the rising edge of the clock, and the host will always output data bits on the falling edge of the clock.
意思是:主设备在时钟的下降沿发送数据,从设备在时钟的上升沿接收数据。因此主设备这边SPI时钟极性应该配置为下降沿有效。
又如,下面这段话是摘自LCD Driver IC SSD1289:
SDI is shifted into 8-bit shift register on every rising edge of SCK in the order of data bit 7, data bit 6 …… data bit 0.
意思是:从设备SSD1289在时钟的上升沿接收数据,而且是按照从高位到地位的顺序接收数据的。因此主设备的SPI时钟极性同样应该配置为下降沿有效。
时钟极性和相位配置正确后,数据才能够被准确的发送和接收。因此应该对照从设备的SPI接口时序或者Spec文档说明来正确配置主设备的时钟。
SPI:高速同步串行口。3~4线接口,收发独立、可同步进行.
SPI,是英语Serial Peripheral interface的缩写,顾名思义就是串行外围设备接口。是Motorola首先在其MC68HCXX系列处理器上定义的。SPI接口主要应用在 EEPROM,FLASH,实时时钟,AD转换器,还有数字信号处理器和数字信号解码器之间。SPI,是一种高速的,全双工,同步的通信总线,并且在芯片 的管脚上只占用四根线,节约了芯片的管脚,同时为PCB的布局上节省空间,提供方便,正是出于这种简单易用的特性,现在越来越多的芯片集成了这种通信协 议,比如AT91RM9200.
SPI总线系统是一种同步串行外设接口,它可以使MCU与各种外围设备以串行方式进行通信以交换信息。外围设置FLASHRAM、网络控制器、LCD显示 驱动器、A/D转换器和MCU等。SPI总线系统可直接与各个厂家生产的多种标准外围器件直接接口,该接口一般使用4条线:串行时钟线(SCK)、主机输 入/从机输出数据线MISO、主机输出/从机输入数据线MOST和低电平有效的从机选择线SS(有的SPI接口芯片带有中断信号线INT或INT、有的 SPI接口芯片没有主机输出/从机输入数据线MOSI)。
SPI的通信原理很简单,它以主从方式工作,这种模式通常有一个主设备和一个或多个从设备,需要至少4根线,事实上3根也可以(单向传输时)。也是所有基于SPI的设备共有的,它们是SDI(数据输入),SDO(数据输出),SCK(时钟),CS(片选)。
(1)SDO – 主设备数据输出,从设备数据输入
(2)SDI – 主设备数据输入,从设备数据输出
(3)SCLK – 时钟信号,由主设备产生
(4)CS – 从设备使能信号,由主设备控制
其中CS是控制芯片是否被选中的,也就是说只有片选信号为预先规定的使能信号时(高电位或低电位),对此芯片的操作才有效。这就允许在同一总线上连接多个SPI设备成为可能。
接下来就负责通讯的3根线了。通讯是通过数据交换完成的,这里先要知道SPI是串行通讯协议,也就是说数据是一位一位的传输的。这就是SCK时钟线存在的 原因,由SCK提供时钟脉冲,SDI,SDO则基于此脉冲完成数据传输。数据输出通过 SDO线,数据在时钟上升沿或下降沿时改变,在紧接着的下降沿或上升沿被读取。完成一位数据传输,输入也使用同样原理。这样,在至少8次时钟信号的改变 (上沿和下沿为一次),就可以完成8位数据的传输。
要注意的是,SCK信号线只由主设备控制,从设备不能控制信号线。同样,在一个基于SPI的设备中,至少有一个主控设备。这样传输的特点:这样的传输方式 有一个优点,与普通的串行通讯不同,普通的串行通讯一次连续传送至少8位数据,而SPI允许数据一位一位的传送,甚至允许暂停,因为SCK时钟线由主控设 备控制,当没有时钟跳变时,从设备不采集或传送数据。也就是说,主设备通过对SCK时钟线的控制可以完成对通讯的控制。SPI还是一个数据交换协议:因为 SPI的数据输入和输出线独立,所以允许同时完成数据的输入和输出。不同的SPI设备的实现方式不尽相同,主要是数据改变和采集的时间不同,在时钟信号上 沿或下沿采集有不同定义,具体请参考相关器件的文档。
在点对点的通信中,SPI接口不需要进行寻址操作,且为全双工通信,显得简单高效。在多个从设备的系统中,每个从设备需要独立的使能信号,硬件上比I2C系统要稍微复杂一些。
最后,SPI接口的一个缺点:没有指定的流控制,没有应答机制确认是否接收到数据。
AT91RM9200的SPI接口主要由4个引脚构成:SPICLK、MOSI、MISO及 /SS,其中SPICLK是整个SPI总线的公用时钟,MOSI、MISO作为主机,从机的输入输出的标志,MOSI是主机的输出,从机的输入,MISO 是主机的输入,从机的输出。/SS是从机的标志管脚,在互相通信的两个SPI总线的器件,/SS管脚的电平低的是从机,相反/SS管脚的电平高的是主机。 在一个SPI通信系统中,必须有主机。SPI总线可以配置成单主单从,单主多从,互为主从。
SPI的片选可以扩充选择16个外设,这时PCS输出=NPCS,说NPCS0~3接4-16译码器,这个译码器是需要外接4-16译码器,译码器的输入为NPCS0~3,输出用于16个外设的选择。
SPI协议举例
SPI是一个环形总线结构,由ss(cs)、sck、sdi、sdo构成,其时序其实很简单,主要是在sck的控制下,两个双向移位寄存器进行数据交换。
假设下面的8位寄存器装的是待发送的数据10101010,上升沿发送、下降沿接收、高位先发送。
那么第一个上升沿来的时候 数据将会是sdo=1;寄存器=0101010x。下降沿到来的时候,sdi上的电平将所存到寄存器中去,那么这时寄存器=0101010sdi,这样在 8个时钟脉冲以后,两个寄存器的内容互相交换一次。这样就完成里一个spi时序。
举例:
假设主机和从机初始化就绪:并且主机的sbuff=0xaa,从机的sbuff=0x55,下面将分步对spi的8个时钟周期的数据情况演示一遍:假设上升沿发送数据
这样就完成了两个寄存器8位的交换,上面的上表示上升沿、下表示下降沿,sdi、sdo相对于主机而言的。其中ss引脚作为主机的时候,从机可以把它拉底 被动选为从机,作为从机的是时候,可以作为片选脚用。根据以上分析,一个完整的传送周期是16位,即两个字节,因为,首先主机要发送命令过去,然后从机根 据主机的命令准备数据,主机在下一个8位时钟周期才把数据读回来。 SPI 总线是Motorola公司推出的三线同步接口,同步串行3线方式进行通信:一条时钟线SCK,一条数据输入线MOSI,一条数据输出线MISO;用于 CPU与各种外围器件进行全双工、同步串行通讯。SPI主要特点有:可以同时发出和接收串行数据;可以当作主机或从机工作;提供频率可编程时钟;发送结束 中断标志;写冲突保护;总线竞争保护等。下图示出SPI总线工作的四种方式,其中使用的最为广泛的是SPI0和SPI3方式 (实线表示):
SPI总线四种工作方式 SPI 模块为了和外设进行数据交换,根据外设工作要求,其输出串行同步时钟极性和相位可以进行配置,时钟极性(CPOL)对传输协议没有重大的影响。如果 CPOL=0,串行同步时钟的空闲状态为低电平;如果CPOL=1,串行同步时钟的空闲状态为高电平。时钟相位(CPHA)能够配置用于选择两种不同的传 输协议之一进行数据传输。如果CPHA=0,在串行同步时钟的第一个跳变沿(上升或下降)数据被采样;如果CPHA=1,在串行同步时钟的第二个跳变沿 (上升或下降)数据被采样。SPI主模块和与之通信的外设备时钟相位和极性应该一致。
SPI总线包括1根串行同步时钟信号线以及2根数据线。
SPI模块为了和外设进行数据交换,根据外设工作要求,其输出串行同步时钟极性和相位可以进行配置,时钟极性(CPOL)对传输协议没有重大的影响。如果 CPOL=0,串行同步时钟的空闲状态为低电平;如果CPOL=1,串行同步时钟的空闲状态为高电平。时钟相位(CPHA)能够配置用于选择两种不同的传 输协议之一进行数据传输。如果CPHA=0,在串行同步时钟的第一个跳变沿(上升或下降)数据被采样;如果CPHA=1,在串行同步时钟的第二个跳变沿 (上升或下降)数据被采样。SPI主模块和与之通信的外设音时钟相位和极性应该一致。SPI接口时序如图3、图4所示。
补充:
上文中最后一句话:SPI主模块和与之通信的外设备时钟相位和极性应该一致。个人理解这句话有2层意思:其一,主设备SPI时钟和极性的配置应该由外设来 决定;其二,二者的配置应该保持一致,即主设备的SDO同从设备的SDO配置一致,主设备的SDI同从设备的SDI配置一致。因为主从设备是在SCLK的 控制下,同时发送和接收数据,并通过2个双向移位寄存器来交换数据。工作原理演示如下图:
上升沿主机SDO发送数据1,同时从设备SDO发送数据0;紧接着在SCLK的下降沿的时候从设备的SDI接收到了主机发送过来的数据1,同时主机也接收到了从设备发送过来的数据0.
SPI协议心得
SPI接口时钟配置心得:
在主设备这边配置SPI接口时钟的时候一定要弄清楚从设备的时钟要求,因为主设备这边的时钟极性和相位都是以从设备为基准的。因此在时钟极性的配置上一定 要搞清楚从设备是在时钟的上升沿还是下降沿接收数据,是在时钟的下降沿还是上升沿输出数据。但要注意的是,由于主设备的SDO连接从设备的SDI,从设备 的SDO连接主设备的SDI,从设备SDI接收的数据是主设备的SDO发送过来的,主设备SDI接收的数据是从设备SDO发送过来的,所以主设备这边 SPI时钟极性的配置(即SDO的配置)跟从设备的SDI接收数据的极性是相反的,跟从设备SDO发送数据的极性是相同的。下面这段话是Sychip Wlan8100 Module Spec上说的,充分说明了时钟极性是如何配置的:
The 81xx module will always input data bits at the rising edge of the clock, and the host will always output data bits on the falling edge of the clock.
意思是:主设备在时钟的下降沿发送数据,从设备在时钟的上升沿接收数据。因此主设备这边SPI时钟极性应该配置为下降沿有效。
又如,下面这段话是摘自LCD Driver IC SSD1289:
SDI is shifted into 8-bit shift register on every rising edge of SCK in the order of data bit 7, data bit 6 …… data bit 0.
意思是:从设备SSD1289在时钟的上升沿接收数据,而且是按照从高位到地位的顺序接收数据的。因此主设备的SPI时钟极性同样应该配置为下降沿有效。
时钟极性和相位配置正确后,数据才能够被准确的发送和接收。因此应该对照从设备的SPI接口时序或者Spec文档说明来正确配置主设备的时钟。
Subscribe to:
Posts (Atom)
