|
- // 硬件連接:
- // STM32(作為從設(shè)備) 外部設(shè)備
- // PB12-SPI2-NSS------------> CS
- // PB13-SPI2-SCK------------->CLK
- // PB14-SPI2-MISO----NC
- // PB15_SPI2-MOSI----------->data
- // STM32作為從設(shè)備的時(shí)候,獲取數(shù)據(jù)的接口為MOSI(PB15),STM32只需要從SPI接口獲取數(shù)據(jù),不需要發(fā)送數(shù)據(jù),因此MISO(PB14)懸空。
- //SPI2作為從機(jī)接口配置
- 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;//只接收,不發(fā)送,這個(gè)地方是重點(diǎn),如果設(shè)置為單工通信是不能實(shí)現(xiàn)數(shù)據(jù)采集的。
- SPI_InitStructure.SPI_Mode = SPI_Mode_Slave; //從機(jī)模式
- SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //數(shù)據(jù)位為8
- SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //不發(fā)送數(shù)據(jù)時(shí),時(shí)鐘線為高
- SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //在第二個(gè)沿進(jìn)行采樣
- SPI_InitStructure.SPI_NSS = SPI_NSS_Hard; //硬NSS
- SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
- SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //MSB優(yōu)先
- SPI_InitStructure.SPI_CRCPolynomial = 7;
- SPI_Init(SPI2, &SPI_InitStructure);
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); //使用中斷進(jìn)行接收,因此設(shè)置NVIC的優(yōu)先機(jī)組,1表示1bit搶占優(yōu)先級(jí)
- 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); //先不啟動(dòng)SPI,在收到特定命令的時(shí)候再啟動(dòng)
- }
- //中斷服務(wù)程序
- void SPI2_IRQHandler(void)
- {
- //接收數(shù)據(jù)
- //printf("SPI_IRQ %d\n",RxIdx);
- SPI2_Buffer_Rx[RxIdx++] = SPI_I2S_ReceiveData(SPI2);
- }
- int main(void)
- {
- int i;
- SystemInit(); /* 配置系統(tǒng)時(shí)鐘為 72M */
- LEDKEY_GPIOInit();
- USART_GPIOInit();
- SysTick_Configuration();
- USART_Configuration(USART1, 9600);
- SPI_slave();
- LED1_ON;
- while (1)
- {
- if(RxIdx==50)//接收數(shù)據(jù)滿,對(duì)數(shù)據(jù)進(jìn)行處理
- {
- SPI_Cmd(SPI2, DISABLE);
- RxIdx=0;
- printf("rcv full\n");
- for(i=0;i<49;i++)
- printf("0x%02X\n ",SPI2_Buffer_Rx);//串口輸出獲取的數(shù)據(jù)
- }
- if(GetKey()==1)
- {
- LED1_ON;
- SPI_Cmd(SPI2, ENABLE);//按鍵按下后,使能SPI2,然后在中斷中接收數(shù)據(jù)
- RxIdx=0;//接收數(shù)據(jù)下標(biāo)清零
- printf("key1\n");
- }
- if(GetKey()==2)
- {
- LED1_OFF;
- }
- }
- }
復(fù)制代碼
|
|