江协科技stm32————11-5 硬件SPI读写W25Q64

一、开启时钟,开启SPI和GPIO的时钟

二、初始化GPIO口,其中SCK和MOSI是由硬件外设控制的输出信号,配置为复用推挽输出

MISO是硬件外设的输入信号,配置为上拉输入,SS是软件控制的输出信号,配置为通用推挽输出

三、配置SPI外设,使用结构体调用SPI_Init

四、开关控制,调用SPI_Cmd,使能

江协科技stm32————11-5 硬件SPI读写W25Q64_第1张图片 void SPI_I2S_SendData(SPI_TypeDef* SPIx, uint16_t Data);//写DR数据寄存器

uint16_t SPI_I2S_ReceiveData(SPI_TypeDef* SPIx);//读DR

步骤

一、等待TXE为1,发送寄存器为空

二、软件写入数据置SPI_DR

三、等待RENE为1

四、读取DR 

MySPI.c

#include "stm32f10x.h"                  // Device header

void MySPI_W_SS(uint8_t BitValue)	//ss = cs
{
	GPIO_WriteBit(GPIOA , GPIO_Pin_4, (BitAction)BitValue);
}
	


void MySPI_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	SPI_InitTypeDef SPI_InitStructure;
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;	//指定为主机
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;	//双线全双工
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;	//8位数据帧
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;	//高位先行
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128;
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;	//第一个边沿开始采样CPHA=0
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
	SPI_InitStructure.SPI_CRCPolynomial = 7;
	SPI_Init(SPI1, &SPI_InitStructure);
	
	SPI_Cmd(SPI1 , ENABLE);
	
	MySPI_W_SS(1);
}

void MySPI_Start(void)
{
	MySPI_W_SS(0);
}

void MySPI_Stop(void)
{
	MySPI_W_SS(1);
}

uint8_t MySPI_SwapByte(uint8_t ByteSend)	//交换字节
{
	while (SPI_I2S_GetFlagStatus(SPI1 , SPI_I2S_FLAG_TXE) != SET);
	
	SPI_I2S_SendData(SPI1 , ByteSend);
	
	while (SPI_I2S_GetFlagStatus(SPI1 , SPI_I2S_FLAG_RXNE) != SET);
	
	return SPI_I2S_ReceiveData(SPI1);
}

你可能感兴趣的:(科技,stm32,嵌入式硬件)