STM32
直播中

绝代双骄

11年用户 1052经验值
私信 关注
[问答]

如何对STM32F407 SPI模块进行配置

STM32F407硬件SPI口的初始化过程是怎样的?
如何对STM32F407 SPI模块进行配置?

回帖(1)

王桂香

2021-10-15 17:37:36
  void SPI1_init(void) //SPI1口初始化
  {
  GPIO_InitTypeDef GPIO_InitStructure;
  SPI_InitTypeDef SPI_InitStructure;
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); //使能GPIOA时钟
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE); //使能SPI1时钟
  //Configure SPI1 pins: SCK, MISO and MOSI
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; //管脚SPI复用 (《STM32F4为》PA5:SPI1_SCK,PA6:SPI1_MISO,PA7:SPI1_MOSI)
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽输出
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure); //配置到管脚
  GPIO_PinAFConfig(GPIOA,5,GPIO_AF_SPI1);
  GPIO_PinAFConfig(GPIOA,6,GPIO_AF_SPI1);
  GPIO_PinAFConfig(GPIOA,7,GPIO_AF_SPI1);
  //SPI模块配置
  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //SPI设置为双线双向全双工
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //设置为主SPI
  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_Soft; //NSS 信号由硬件(NSS管脚)还是软件(使用 SSI位)管理:内部NSS信号由SSI位控制
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256; //波特率预分频值为256
  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //数据传输从MSB位开始
  SPI_InitStructure.SPI_CRCPolynomial = 7; //CRC计算的多项式
  SPI_Init(SPI1, &SPI_InitStructure); //配置到SPIx寄存器
  SPI_Cmd(SPI1, ENABLE); //使能SPI外设
  }
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  unsigned char SPI1_TransmitByte(unsigned char TxData)
  {
  while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);//等待发送区空
  SPI_I2S_SendData(SPI1, TxData); //SPIx发送一个byte 数据
  while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET); //等待接收完一个byte
  return SPI_I2S_ReceiveData(SPI1); //返回接收的数据
  }
举报

更多回帖

发帖
×
20
完善资料,
赚取积分