STM32F103/302 SPI3 接口使用例程

最近在用STM MCU 的SPI3,把一些使用时的注意点给大家记录一下,该注意的几点都注意了:

1,开GPIO时种

2,开SPI3时钟

3,GPIO引脚功能设定

4,如果有引脚复用的或与JTAG口有共用的引脚要对GPIO进行remap等

代码如下:

void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);  

// NSS
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;         
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);

// SPI
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4 |GPIO_Pin_5;         
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);

GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable,ENABLE);

}

void SPI3_Configuration(void)
{
SPI_InitTypeDef SPI_InitStructure;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI3, ENABLE);
RCC_PCLK1Config(RCC_HCLK_Div2);  // 36M

SPI_I2S_DeInit(SPI3);
  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b;
  SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
  SPI_InitStructure.SPI_NSS = SPI_NSS_Hard;  // SPI_NSS_Soft
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI3,&SPI_InitStructure);

SPI_SSOutputCmd(SPI3, ENABLE);


SPI_Cmd(SPI3, ENABLE);



}

int main(void)
{
RCC_Configuration();
GPIO_Configuration();
SPI3_Configuration();
delay_init(72);

while(1)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_15);
SPI_I2S_SendData(SPI3,0xAA55);
while( SPI_I2S_GetFlagStatus(SPI3, SPI_I2S_FLAG_BSY));
SPI_I2S_ReceiveData(SPI3);
        GPIO_SetBits(GPIOA,GPIO_Pin_15);
delay_ms(1);
}
}

//仿真观看SPI3寄存器状态 -- 正常

STM32F103/302 SPI3 接口使用例程_第1张图片


成功输出信号波形

STM32F103/302 SPI3 接口使用例程_第2张图片

你可能感兴趣的:(嵌入式软件)