STM32之SPI主机例程
#include "stm32f10x.h"
/* RCC时钟配置 */
void RCC_config(void)
{
ErrorStatus HSEStartUpStatus;
/* RCC寄存器设置为默认配置 */
RCC_DeInit();
/* 打开外部高速时钟 */
RCC_HSEConfig(RCC_HSE_ON);
/* 等待外部高速时钟稳定 */
HSEStartUpStatus = RCC_WaitForHSEStartUp();
if(HSEStartUpStatus == SUCCESS)
{
/* 设置HCLK = SYSCLK */
RCC_HCLKConfig(RCC_SYSCLK_Div1);
/* 设置PCLK2 = HCLK */
RCC_PCLK2Config(RCC_HCLK_Div1);
/* 设置PCLK1 = HCLK / 2 */
RCC_PCLK1Config(RCC_HCLK_Div2);
// /* 设置FLASH代码延时 */
// FLASH_SetLatency(FLASH_Latency_2);
// /* 使能预取址缓存 */
// FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
/* 设置PLL时钟源为HSE倍频9 72MHz */
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
/* 使能PLL */
RCC_PLLCmd(ENABLE);
/* 等待PLL稳定 */
while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
/* 设置PLL为系统时钟源 */
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
/* 等待系统时钟源切换到PLL */
while(RCC_GetSYSCLKSource() != 0x08);}
}
/* GPIO配置 */
void GPIO_config(void)
{GPIO_InitTypeDef GPIO_InitStructure;/* 时钟配置 */RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);/* MISO配置为浮空输入 */GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;GPIO_Init(GPIOA, &GPIO_InitStructure);/* SCK和MOSI配置为复用推挽输出 */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);/* NSS配置为推挽输出 */GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;GPIO_Init(GPIOA, &GPIO_InitStructure);
}
/* SPI配置 */
void SPI_config(void)
{SPI_InitTypeDef SPI_InitStructure;/* 时钟配置 */RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_SPI1, ENABLE);
/* 配置SPI模式 */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_1Edge;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);/* 打开SPI1 */SPI_Cmd(SPI1, ENABLE);
}
/* 毫秒延时函数 */
void delay_ms(uint16_t time)
{ uint16_t i = 0; while(time--){i = 12000;while(i--); }
}
/* SPI发送一个数据 */
uint8_t SPI_SendByte(uint8_t data)
{while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_TXE) == RESET);SPI_I2S_SendData(SPI1, data);while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);return SPI_I2S_ReceiveData(SPI1);
}
/* 主函数 */
int main(void)
{volatile uint8_t i = 0, j;/* RCC时钟配置 */RCC_config();/* GPIO配置 */GPIO_config();
/* SPI配置 */SPI_config();
while(1){GPIO_ResetBits(GPIOA, GPIO_Pin_4);j = SPI_SendByte(i++);GPIO_SetBits(GPIOA, GPIO_Pin_4);/* 1秒延时 */delay_ms(500);}
}
原文:https://blog.csdn.net/lushoumin/article/details/78927253