|
发表于 2021-5-27 15:19:39
|
显示全部楼层
void Spi_Init(void)//上电后, CS必须从高电平转换为低电平,然后才能接受新指令。
{
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);//SPI时钟使能
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 ; //PB12-PB15 NSS,SCK,MISO,MOSI
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
/* Push-pill output, it can be other output types */
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13|GPIO_Pin_14 | GPIO_Pin_15; //PB12-PB15 NSS,SCK,MISO,MOSI
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
/* Push-pill output, it can be other output types */
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// GPIO_InitStructure.GPIO_Pin =GPIO_Pin_14 | GPIO_Pin_15; //PB12-PB15 NSS,SCK,MISO,MOSI
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
// /* Push-pill output, it can be other output types */
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
// GPIO_Init(GPIOB, &GPIO_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_High; //空闲为高
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //数据采样从第二个时钟边沿开始
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //nss软件选择
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; //分频
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //发送数据高位在前
SPI_InitStructure.SPI_CRCPolynomial = 7; //CRC的7位校验码
SPI_Init(SPI2,&SPI_InitStructure);
SPI_Cmd(SPI2,ENABLE);
SPI_I2S_SendData(SPI2,0xff);
SPI_CS_H;
}
u8 SPI_Write(u8 data)//接收发送函数 环形总线
{
u8 RECV;
while(!SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_TXE));//等待发送寄存器为空
SPI_I2S_SendData(SPI2,data);
while(!SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_RXNE));
RECV = SPI_I2S_ReceiveData(SPI2);
return RECV;
}
我之前找到的是这个,也是网上的。是没问题的 |
|