- // 硬件連接:
- // 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;
- }
- }
- }
復制代碼
|