写一个MM32F0144C6的读取SPI_Flash ID的完整代码
时间: 2024-03-08 21:47:47 浏览: 166
以下是一个简单的MM32F0144C6读取SPI Flash ID的示例代码:
```c
#include "MM32F0144.h"
#define SPI_FLASH_CS_LOW() GPIO_ResetBits(GPIOC, GPIO_Pin_4)
#define SPI_FLASH_CS_HIGH() GPIO_SetBits(GPIOC, GPIO_Pin_4)
#define SPI_FLASH_CMD_READ_ID 0x9F
void SPI_Flash_Init(void);
uint8_t SPI_Flash_SendByte(uint8_t byte);
uint8_t SPI_Flash_ReadByte(void);
void SPI_Flash_ReadID(uint8_t *pManufacturerID, uint8_t *pDeviceID);
int main(void)
{
uint8_t manufacturer_id = 0;
uint8_t device_id = 0;
SPI_Flash_Init();
SPI_Flash_ReadID(&manufacturer_id, &device_id);
while(1);
}
void SPI_Flash_Init(void)
{
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
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_256;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI2, &SPI_InitStructure);
SPI_Cmd(SPI2, ENABLE);
}
uint8_t SPI_Flash_SendByte(uint8_t byte)
{
while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
SPI_I2S_SendData(SPI2, byte);
while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET);
return SPI_I2S_ReceiveData(SPI2);
}
uint8_t SPI_Flash_ReadByte(void)
{
return SPI_Flash_SendByte(0xFF);
}
void SPI_Flash_ReadID(uint8_t *pManufacturerID, uint8_t *pDeviceID)
{
SPI_FLASH_CS_LOW();
SPI_Flash_SendByte(SPI_FLASH_CMD_READ_ID);
*pManufacturerID = SPI_Flash_ReadByte();
*pDeviceID = SPI_Flash_ReadByte();
SPI_FLASH_CS_HIGH();
}
```
在上面的示例代码中,我们使用了MM32F0144C6的SPI2接口来与SPI Flash通信。我们使用了GPIOC的第4个引脚作为SPI Flash的片选引脚。在初始化SPI接口后,我们可以通过SPI_Flash_SendByte()函数发送字节数据,通过SPI_Flash_ReadByte()函数读取字节数据。在SPI_Flash_ReadID()函数中,我们发送了0x9F命令,读取SPI Flash的制造商ID和设备ID。最后,我们打印出了制造商ID和设备ID。
阅读全文