SPI总线的传输速度比IIC速度快,故通常追求速度常常采用硬件SPI进行传输数据。下面记录了利用stm32cubeMx配置硬件SPI1,外设是W25x16,这次主要是实现对该芯片的ID读取。
1.硬件环境
主控单片机:stm32f103vet6
外设:w25x16
接线图:
2.利用MX配置相关参数,生成代码
spi1 的配置
spi1 -CS 配置
3.系统生成代码说明
IO配置已经将PC13配置,SPI1也配置好了。
4.添加读取w25x16-ID代码
头文件
#include "main.h"
#define SPI_FLASH_CS_0 HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_RESET)
#define SPI_FLASH_CS_1 HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_SET)
#define W25Q80 0XEF13
#define W25Q16 0XEF14
#define W25Q32 0XEF15
#define W25Q64 0XEF16
//读取芯片ID W25X16的ID:0XEF14
extern u16 SPI_Flash_ReadID(void);
C文件
#include "w25x16.h"
#include "main.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"
static char SPI1_ReadWriteByte(uint8_t txdata)
{
uint8_t rxdata=00;
HAL_SPI_TransmitReceive(&hspi1,&txdata,&rxdata,1,3);
return rxdata;
}
//读取芯片ID W25X16的ID:0XEF14
u16 SPI_Flash_ReadID(void)
{
u16 Temp = 0;
SPI_FLASH_CS_0;
SPI1_ReadWriteByte(0x90);//发送读取ID命令
SPI1_ReadWriteByte(0x00);
SPI1_ReadWriteByte(0x00);
SPI1_ReadWriteByte(0x00);
Temp|=SPI1_ReadWriteByte(0xFF)<<8;
Temp|=SPI1_ReadWriteByte(0xFF);
SPI_FLASH_CS_1;
return Temp;
}
main函数
程序主要实现了如果正确读取到ID值,那么串口输出提示信息。
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"
#include "stdio.h"
#include "w25x16.h"
/* USER CODE END Includes */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#define LED1_PIN GPIO_PIN_1
#define LED1_GPIO_PORT GPIOA
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_SPI1_Init();
/* USER CODE BEGIN 2 */
//==============init===============================
uint16_t ticks=0;
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
//===============running app======================
HAL_Delay(2000);
if(W25Q16==SPI_Flash_ReadID())
{
printf("SPI_Flash_ReadID is Ok! \r\n");
}
}
/* USER CODE END 3 */
}