专注电子技术学习与研究
当前位置:单片机教程网 >> STM32 >> 浏览文章

STM32的SPI主从机模式

作者:星星and宇   来源:星星and宇的空间   点击数:  更新时间:2014年05月30日   【字体:

 void RCC_Configuration(void)
{
/* PCLK2 = HCLK/2 */
RCC_PCLK2Config(RCC_HCLK_Div2);

/* Enable peripheral clocks --------------------------------------------------*/
/* GPIOA, GPIOB and SPI1 clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB |
RCC_APB2Periph_SPI1, ENABLE);

/* SPI2 Periph clock enable */
// RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
}
注意主从机的GPIO设置不一样 ,GPIO口的NSS一定要设置成开漏输出
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;

/* Configure SPI1 pins: SCK, MISO and MOSI ---------------------------------*/
//主机GPIO口设置
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;//miso
GPIO_Init(GPIOA,&GPIO_InitStructure);


GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;//cs
GPIO_Init(GPIOA,&GPIO_InitStructure);
/* //从机GPIO口设置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5|GPIO_Pin_7;//sck mosi
GPIO_Init(GPIOA,&GPIO_InitStructure);

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;//miso
GPIO_Init(GPIOA,&GPIO_InitStructure);

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;//cs
GPIO_Init(GPIOA,&GPIO_InitStructure);
*/
}

 

接下来就是spi口得设置:

void SPI1_conf(void)
{
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//SPI_Direction_1Line_Rx;//

SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;

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_I2S_ITConfig(SPI1, SPI_I2S_IT_RXNE, ENABLE);


/* Enable SPI_SLAVE */

SPI_Cmd(SPI1, ENABLE);
SPI_I2S_ClearITPendingBit(SPI1, SPI_I2S_IT_RXNE);

}

关闭窗口