STM32F0(8)SPI初始化
// SPI引腳初始化
void W25X_SPI_Init(void)
{
RCC->APB1ENR |= RCC_APB1ENR_SPI2EN; // 打開(kāi)SPI2的時(shí)鐘
RCC->AHBENR |= RCC_AHBENR_GPIOBEN; // 打開(kāi)SPI2對(duì)應(yīng)引腳的時(shí)鐘
GPIOB->AFR[1] &= ~0xfff00000; // 開(kāi)引腳復(fù)用功能對(duì)應(yīng)的功能
// 配置GPIO
// cs口為通用輸出口,手動(dòng)控制cs
GPIOB->MODER &= ~GPIO_MODER_MODER12_1;
GPIOB->MODER |= GPIO_MODER_MODER12_0;
SPI_CS_H;
// 其它引腳為復(fù)用功能
GPIOB->MODER |= (GPIO_MODER_MODER13_1 | GPIO_MODER_MODER14_1 | GPIO_MODER_MODER15_1);
GPIOB->MODER &= ~(GPIO_MODER_MODER13_0 | GPIO_MODER_MODER14_0 | GPIO_MODER_MODER15_0);
GPIOB->PUPDR &= ~(GPIO_PUPDR_PUPDR14_1);
GPIOB->PUPDR |= (GPIO_PUPDR_PUPDR14_0);
GPIOB->OSPEEDR |= (GPIO_OSPEEDER_OSPEEDR12 | GPIO_OSPEEDER_OSPEEDR13 | GPIO_OSPEEDER_OSPEEDR14 | GPIO_OSPEEDER_OSPEEDR15);
// SPI2配置
SPI2->CR2 |= (SPI_CR2_DS_0 | SPI_CR2_DS_1 | SPI_CR2_DS_2 | SPI_CR2_FRXTH); // 8位數(shù)據(jù)模式
SPI2->CR1 |= (SPI_CR1_CPOL | SPI_CR1_CPHA | SPI_CR1_MSTR | SPI_CR1_SSM | SPI_CR1_SSI); // 主機(jī)模式。clk默認(rèn)高電平,第二邊沿驅(qū)動(dòng)(上升沿)
SPI2->CR1 |= SPI_CR1_SPE; // SPI使能
}
// SPI在發(fā)送數(shù)據(jù)的8個(gè)條邊沿的時(shí)間內(nèi),也接受了8位數(shù)據(jù)
// SPI可以發(fā)送和接受在同一個(gè)8段跳邊沿之內(nèi)
unsigned char W25X_Write_And_Read_Dat(unsigned char write_dat_temp)
{
unsigned char read_dat_temp;
while(!(SPI2->SR & SPI_SR_TXE));
*(__IO uint8_t *)((uint32_t)SPI2+0x0c) = write_dat_temp; // 發(fā)送8位數(shù)據(jù)
while(!(SPI2->SR & SPI_SR_RXNE));
read_dat_temp = *(__IO uint8_t *)((uint32_t)SPI2+0x0c); // 接受8位數(shù)據(jù)
return read_dat_temp;
}