ARM40-A5D27应用程序——SPI的用户态驱动(1)
2020.4.16
SPI的用户态驱动有两种方式,read/write 或者 ioctl().
read/write方式在同一时间只能read或write。如果要同时read和write,则需要用ioctl(Input Output Control).
本文是一个 read/write的例子。
一、例1
(1)SPI应用程序的C语言源码
文件名为 test_spi0.c,代码见附录(1)。
(2)交叉编译
arm-none-linux-gnueabi-gcc -o test_spi0 test_spi0.c
(3)执行程序与测试
将交叉编译得到的 test_spi0 文件拷贝到ARM40-A5D27板中,执行程序:
./test_spi0
二、例2
(1)SPI应用程序的C语言源码
文件名文件名为 test_spi0ad7193.c,代码见附录(2)。
(2)交叉编译
arm-none-linux-gnueabi-gcc -o test_spi0ad7193 test_spi0ad7193.c
(3)执行程序与测试
将交叉编译得到的 test_spi0ad7193 文件拷贝到ARM40-A5D27板中,执行程序:
./test_spi0ad7193.c
打印为:
root@A5D27:/home# ./test_spi0ad7193
STATUS: 0x00
MODE: 0x08 0x00 0x60
CONFIGURATION: 0x00 0x01 0x16
ID: 0xa2
对AD7193的手册对比:
参考文章:
Documentation/spi/spidev_test.c
《Linux Device Drivers Development: Develop customized drivers for embedded Linux》
荟聚计划:共商 共建 共享 Grant
附:
(1)test_spi0.c 的代码
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int i, fd;
char wr_buf[] = {0xff, 0x00, 0x1f, 0x0f};
char rd_buf[10];
fd = open("/dev/spi0.0", O_RDWR);
if(fd <= 0) {
printf("Failed to open SPI device");
exit(1);
}
if(write(fd, wr_buf, sizeof(wr_buf)) != sizeof(wr_buf))
perror("Write Error");
if(read(fd, rd_buf, sizeof(rd_buf)) != sizeof(rd_buf))
perror("Read Error");
else
for(i = 0; i < sizeof(rd_buf); i++)
printf("0x%02x ", rd_buf[i]);
close(fd);
return 0;
}
(2)test_spi0ad7193.c 的代码
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int fd;
char wr_buf[4];
char rd_buf[4];
fd = open("/dev/spidev0.0", O_RDWR);
if(fd <= 0) {
printf("Failed to open SPI device");
exit(1);
}
wr_buf[0] = 0xff; //software reset
wr_buf[1] = 0xff;
wr_buf[2] = 0xff;
wr_buf[3] = 0xff;
if(write(fd, wr_buf, 4) != 4)
perror("Write Error");
wr_buf[0] = 0x40; //communications: read STATUS
if(write(fd, wr_buf, 1) != 1)
perror("Write Error");
if(read(fd, rd_buf, 1) != 1)
perror("Read Error");
else
printf("STATUS: 0x%02x\n", rd_buf[0]);
wr_buf[0] = 0x48; //communications: read MODE
if(write(fd, wr_buf, 1) != 1)
perror("Write Error");
if(read(fd, rd_buf, 3) != 3)
perror("Read Error");
else
printf("MODE: 0x%02x 0x%02x 0x%02x\n", rd_buf[0], rd_buf[1], rd_buf[2]);
wr_buf[0] = 0x50; //communications: read CONFIGURATION
if(write(fd, wr_buf, 1) != 1)
perror("Write Error");
if(read(fd, rd_buf, 3) != 3)
perror("Read Error");
else
printf("CONFIGURATION: 0x%02x 0x%02x 0x%02x\n", rd_buf[0], rd_buf[1], rd_buf[2]);
wr_buf[0] = 0x60; //communications: read ID
if(write(fd, wr_buf, 1) != 1)
perror("Write Error");
if(read(fd, rd_buf, 1) != 1)
perror("Read Error");
else
printf("ID: 0x%02x\n", rd_buf[0]);
close(fd);
return 0;
}