GD32F470 SPI中断接收数据
时间: 2023-09-29 17:02:57 浏览: 195
GD32F470搭载W5500,SPI通信有线网口带网线 此版本为固定IP,该工程为实际项目工程,内含电路图 有不懂的可以私信我
以下是GD32F470 SPI中断接收数据的示例代码:
```c
#include "gd32f4xx.h"
#define SPI_SLAVE_SELECT_PIN GPIO_PIN_4
#define SPI_SLAVE_SELECT_PORT GPIOB
uint8_t rx_buffer[10];
uint8_t tx_buffer[10] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A};
void spi_slave_select(void)
{
GPIO_ResetBits(SPI_SLAVE_SELECT_PORT, SPI_SLAVE_SELECT_PIN);
}
void spi_slave_deselect(void)
{
GPIO_SetBits(SPI_SLAVE_SELECT_PORT, SPI_SLAVE_SELECT_PIN);
}
void spi_init(void)
{
rcu_periph_clock_enable(RCU_GPIOB);
rcu_periph_clock_enable(RCU_SPI1);
gpio_init(SPI_SLAVE_SELECT_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, SPI_SLAVE_SELECT_PIN);
gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5);
spi_parameter_struct spi_init_struct;
spi_struct_para_init(&spi_init_struct);
spi_init_struct.device_mode = SPI_SLAVE;
spi_init_struct.trans_mode = SPI_TRANSMODE_RECEIVEONLY;
spi_init_struct.frame_size = SPI_FRAMESIZE_8BIT;
spi_init_struct.clock_polarity_phase = SPI_CK_PL_HIGH_PH_2EDGE;
spi_init_struct.nss = SPI_NSS_SOFT;
spi_init_struct.prescale = SPI_PSC_2;
spi_init(SPI1, &spi_init_struct);
spi_enable(SPI1);
}
void spi_receive_interrupt_enable(void)
{
spi_i2s_interrupt_enable(SPI1, SPI_I2S_INT_RBNE);
eclic_irq_enable(SPI1_IRQn, 1, 0);
}
void SPI1_IRQHandler(void)
{
if (RESET != spi_i2s_interrupt_flag_get(SPI1, SPI_I2S_INT_RBNE))
{
uint8_t data = spi_i2s_data_receive(SPI1);
// Do something with received data
}
}
int main(void)
{
spi_init();
spi_slave_select();
spi_receive_interrupt_enable();
while (1)
{
spi_slave_deselect();
spi_slave_select();
for (uint8_t i = 0; i < 10; i++)
{
spi_i2s_data_transmit(SPI1, tx_buffer[i]);
while(RESET == spi_i2s_flag_get(SPI1, SPI_FLAG_TBE));
while(RESET == spi_i2s_flag_get(SPI1, SPI_FLAG_RBNE));
rx_buffer[i] = spi_i2s_data_receive(SPI1);
}
spi_slave_deselect();
}
}
```
在该示例中,SPI1被配置为从设备模式,仅接收模式,帧大小为8位,时钟极性为高电平,时钟相位为第二个边沿,NSS信号由软件控制,预分频器值为2。SPI从设备的NSS引脚由GPIOB的第4个引脚控制。
spi_init()函数初始化SPI1和相关GPIO。spi_slave_select()和spi_slave_deselect()函数用于控制NSS引脚。spi_receive_interrupt_enable()函数启用SPI1接收中断和相应的中断处理程序SPI1_IRQHandler()。
在main()函数中,首先初始化SPI并启用接收中断。然后,在无限循环中,将NSS引脚拉低以准备接收数据。然后,用循环将tx_buffer中的数据逐个发送,并等待接收到相应的数据。接收到的数据存储在rx_buffer数组中,并在每次发送和接收之间拉高和拉低NSS引脚。
阅读全文