自發自收沒有問題,但兩個樹莓派之間spi收發資料無法成功,我懷疑是否是linux默認為主設備,兩個主設備無法通信???但從原理分析應該可以收到資料才對,即一個發,一個收,應可以收到才對,但依然不行,代碼如下:
#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();
}
uj5u.com熱心網友回復:
從設備不能主動發送,只能一個做主一個做從,代碼上設定上有區別的uj5u.com熱心網友回復:
spi默認一般做主,uj5u.com熱心網友回復:
SPI是主從的哦,可以一主多從,但是不能兩個都是主轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/12818.html
標籤:驅動程序開發區
