完整的代码如下: #include"stm32f10x_lib.h" void SPI_Configuration(void) { //SPI_1串口参数部分定义,SPI_1参数为时钟平时为高,上升沿采样 SPI_InitTypeDef SPI_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI2,ENABLE);//使能SPI_2时钟 //配置SPI1的MISO(PA6)为浮空输入 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_MODE = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA,&GPIO_InitStructure); //配置SPI1的MOSI(PA7)和SPI1的CLK(PA5)为复用推免输出 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5|GPIO_Pin_7; GPIO_InitSturcture.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA,&GPIO_InitStructure); //配置SPI1的NSS(PA4)为推免输出 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; GPIO_InitSturcture.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOA,&GPIO_InitSturcture); //SPI1同步参数初始化定义 SPI_InitTypeDef SPI_InitStructure; SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_Fullduplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI1,&SPI_InitStructure); SPI_Cmd(SPI1,ENABLE); } //通过SPI1口发送一个数据,同时接受一个数据 unsigned char SPI_SendByte(unsigned char Byte) { //如果发送寄存器数据没有发送完,循环等待 while(SPI_T1S_GetFlagStatus(SPI1,SPI_T1S_FLAG_TXE) == RESET); //往发送寄存器写入要发送的数据 SPI_T1S_SendData(SPI2,Byte); //如果接受寄存器没有收到数据,循环 while(SPI_T1S_GetFlagStatus(SPI1,SPI_T1S_FLAG_RXNE) == RESET); return SPI_T1S_ReceiveData(SPI1); }
|