- // 硬件连接:
- // STM32(作为从设备) 外部设备
- // PB12-SPI2-NSS------------> CS
- // PB13-SPI2-SCK------------->CLK
- // PB14-SPI2-MISO----NC
- // PB15_SPI2-MOSI----------->data
- // STM32作为从设备的时候,获取数据的接口为MOSI(PB15),STM32只需要从SPI接口获取数据,不需要发送数据,因此MISO(PB14)悬空。
- //SPI2作为从机接口配置
- void SPI_slave(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- SPI_InitTypeDef SPI_InitStructure;
- NVIC_InitTypeDef NVIC_InitStructure;
- //Enable SPI2 clock and GPIO clock for SPI2 and SPI
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE);
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
- //IO初始化
- //Configure SPI2 pins: SCK, MISO and MOSI
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
- GPIO_Init(GPIOB, &GPIO_InitStructure);
- //1st phase: SPI2 slave
- //SPI1 Config
- SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_RxOnly;//只接收,不发送,这个地方是重点,如果设置为单工通信是不能实现数据采集的。
- SPI_InitStructure.SPI_Mode = SPI_Mode_Slave; //从机模式
- SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //数据位为8
- SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //不发送数据时,时钟线为高
- SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //在第二个沿进行采样
- SPI_InitStructure.SPI_NSS = SPI_NSS_Hard; //硬NSS
- SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
- SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //MSB优先
- SPI_InitStructure.SPI_CRCPolynomial = 7;
- SPI_Init(SPI2, &SPI_InitStructure);
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); //使用中断进行接收,因此设置NVIC的优先机组,1表示1bit抢占优先级
- NVIC_InitStructure.NVIC_IRQChannel = SPI2_IRQn;
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
- NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
- NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
- NVIC_Init(&NVIC_InitStructure);
- /* Enable SPI2 RXNE interrupt */
- SPI_I2S_ITConfig(SPI2,SPI_I2S_IT_RXNE,ENABLE);
- //Enable SPI2
- //SPI_Cmd(SPI2, ENABLE); //先不启动SPI,在收到特定命令的时候再启动
- }
- //中断服务程序
- void SPI2_IRQHandler(void)
- {
- //接收数据
- //printf("SPI_IRQ %d\n",RxIdx);
- SPI2_Buffer_Rx[RxIdx++] = SPI_I2S_ReceiveData(SPI2);
- }
- int main(void)
- {
- int i;
- SystemInit(); /* 配置系统时钟为 72M */
- LEDKEY_GPIOInit();
- USART_GPIOInit();
- SysTick_Configuration();
- USART_Configuration(USART1, 9600);
- SPI_slave();
- LED1_ON;
- while (1)
- {
- if(RxIdx==50)//接收数据满,对数据进行处理
- {
- SPI_Cmd(SPI2, DISABLE);
- RxIdx=0;
- printf("rcv full\n");
- for(i=0;i<49;i++)
- printf("0x%02X\n ",SPI2_Buffer_Rx);//串口输出获取的数据
- }
- if(GetKey()==1)
- {
- LED1_ON;
- SPI_Cmd(SPI2, ENABLE);//按键按下后,使能SPI2,然后在中断中接收数据
- RxIdx=0;//接收数据下标清零
- printf("key1\n");
- }
- if(GetKey()==2)
- {
- LED1_OFF;
- }
- }
- }
复制代码
|