1、打开spi设备文件
2、配置模数、速度、位数等
3、读写操作
4、关闭
spi.c
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
static int fd = 0;
int spi_init(char *spi_dev,int mode,int nits,int speed)
{
fd = open(spi_dev, O_RDWR);
if (fd < 0)
{
printf("[%s]:[%d] open spi file error\r\n", __FUNCTION__, __LINE__);
return -1;
}
//设置模式
ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
if (ret == -1)
pabort("can't set spi mode");
ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
if (ret == -1)
pabort("can't get spi mode");
//设置一次多少位
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't set bits per word");
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't get bits per word");
//设置最大速度
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't set max speed hz");
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't get max speed hz");
printf("spi mode: %d\n", mode);
printf("bits per word: %d\n", bits);
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
return 0;
}
int spi_readwrte(unsigned char *txbuf, unsigned char *rxbuf, int len)
{
struct spi_ioc_transfer tr =
{
.tx_buf = (unsigned long *)txbuf, //发送缓存区
.rx_buf = (unsigned long *)rxbuf, //接收缓存区
.len = len/4,
.delay_usecs = delay, //发送时间间隔
.speed_hz = speed, //总线速率
.bits_per_word = bits, //收发的一个字的二进制位数
};
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
pabort("can't send spi message");
for (ret = 0; ret < len/4; ret++)
{
if (!(ret % 6))
puts("");
printf("%.2X ", rx[ret]);
}
return 0;
}
int spi_close()
{
close(fd);
return 0;
}
main.c
int main()
{
unsigned char txbuf[] = "hello",rxbuf[50] = {
0};
spi_init("/dev/spi1.0",SPI_CPHA|SPI_CPOL,int nits,short long speed);
spi_readwrte(txbuf, rxbuf,5);
printf("spi rcv %x%x%x%x%x\n",rxbuf[0],rxbuf[1],rxbuf[2],rxbuf[3],rxbuf[4]);
spi_close();
return 0;
}