1,318
社区成员
发帖
与我相关
我的任务
分享
#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>
#include <string.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
static void transfer(int fd);
static void pabort(const char *s);
static const char *device = "/dev/spidev0.0";
static uint8_t mode;
static uint8_t bits = 8;
static uint32_t speed = 80000;
static uint16_t delay;
static uint8_t cs = 1;
//缓存区
char tx[10]= "1234";
//uint8_t tx[1800]= {100,101,102,103,104};
char rx[ARRAY_SIZE(tx)] = {};
int spi_init()
{
int ret = 0;
int fd;
// mode = mode | SPI_MODE_0 | SPI_CS_HIGH | SPI_LSB_FIRST | SPI_LOOP;
//parse_opts(argc, argv);
//step 1 open
fd = open(device, O_RDWR);
if (fd < 0)
pabort("can't open device");
//step 2 ioctl cmd
/*
* spi mode
*/
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");
/*设置或获取SPI读写数据位数
* bits per word
*/
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");
/*
* max speed hz
*/
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");
return fd;
}
int main(int argc, char *argv[])
{
int fd = spi_init();
int flag = 0;
printf("spi fd:%d\n",fd);
printf("spi mode: %d\n", mode);
printf("bits per word: %d\n", bits);
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
//step 3 read and write
while(1){
if(getchar() == '1'){
flag = 1;strcpy(tx,"1234");
}
else if(getchar()=='2'){
flag = 1;strcpy(tx,"2345");
}
if(flag)
transfer(fd);
if(strlen(rx)>0)
{
printf("Recv:%s , len %d\n",rx,strlen(rx));
// printf("recv:%d,%d,%d,%d,%d",rx[0],rx[1],rx[2],rx[3],rx[4]);
}
printf("--");
//printf("recv:%d,%d,%d,%d,%d",rx[0],rx[1],rx[2],rx[3],rx[4]);
}
//step 4 close
close(fd);
return 0;
}
//传输函数
static void transfer(int fd)
{
int ret;
//全双工传输数据
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
// .len = ARRAY_SIZE(tx),
.len = 5,
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits,
.cs_change = cs
};
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr); // SPI_IOC_MESSAGE(n) 表示传输n个数据包
if(ret < 1)
pabort("can't send spi message");
}
static void pabort(const char *s)
{
perror(s);
abort();
}