终于成功收到了数据,两个SPI分别产生了独立的数据,且经过多次读取,基本没有丢失问题。不过为了保证可靠性,还是需要设计一下通信协议,做一下基本的校验。
[RT SPI] Open
[RT SPI] Open
/dev/spidev0.0: 0x10 0x0F 0x0E 0x0D 0x0C 0x0B 0x0A 0x09 0x08 0x07 0x06 0x05 0x04 0x03 0x02 0x01
/dev/spidev0.1: 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F
主函数还是很简单,改成了两个spi顺序发送数据,代码如下:
int main()
{
spi_open(spi_1_fd, name1);
spi_open(spi_2_fd, name2);
uint8_t tx[16];
uint8_t rx_1[16];
uint8_t rx_2[16];
for (int i = 0; i < 16; ++i)
{
tx[i] = i;
}
int rv = transfer(spi_1_fd, tx, rx_1, 16);
(void)rv;
auto str = hex2str(rx_1, 16);
std::cout << name1 << ": "<< str << std::endl;
rv = transfer(spi_2_fd, tx, rx_2, 16);
(void)rv;
auto str = hex2str(rx_2, 16);
std::cout << name2 << ": "<< str << std::endl;
spi_close(spi_1_fd);
spi_close(spi_2_fd);
return 0;
}
而STM32的代码主要改动在于使用CS触发的中断来读取数据,并且在读取完数据后清空DR寄存器,来避免后续产生问题:
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_CAN1_Init();
MX_CAN2_Init();
MX_SPI1_Init();
MX_USART2_UART_Init();
/* USER CODE BEGIN 2 */
for(int i = 0; i < 16; ++i)
{
tx[i] = 16 - i;
}
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
//HAL_SPI_TransmitReceive(&hspi1, tx, rx, 16, 10000);
//HAL_UART_Transmit(&huart2, "hello", 6, 10000);
HAL_Delay(1000);
}
/* USER CODE END 3 */
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if(GPIO_Pin == SPI_CS_Pin)
{
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
HAL_SPI_TransmitReceive(&hspi1, tx, rx, 16, 10000);
hspi1.Instance->DR = 0x00;
}
}