本帖最后由 coshi 于 2021-9-1 09:57 编辑
三、读一个字节上海贝岭BL25CMIA是一个128kB的EEPROM,其容量超过了16位寻址的上限(65536字节)。该芯片采用24位寻址,所以SPI发送地址时需要从低到高发送三个字节,其中高字节中只有第0位有效,该字节的其它位芯片does not care。
- 开片选
- 读EEPROM 的状态寄存器
#define E2PROM_READ_STATUS_REGESITER (0x05U)
/**
* @brief SPI EEPROM Read Status
*
* @param [in] None
*
* @retval uint8_t
*/
static uint8_t E2PROM_Read_Status(void)
{
uint8_t EE_Status;
SPI_NSS_LOW();
/* send "Read Status Register" instruction */
Spi_E2PROM_WriteReadByte(E2PROM_READ_STATUS_REGESITER);
/* send a dummy byte to generate the clock needed by the EEPROM
and put the value of the status register in EE_Status variable */
EE_Status = Spi_E2PROM_WriteReadByte(0xff);
/* deselect the EEPROM */
SPI_NSS_HIGH();
/* return the status register value */
return EE_Status;
}
第一个字节发指令,第二个字节随便发一个用于都回状态。
用于发送字节的函数为:
/**
* @brief SPI flash write byte function
*
* @param [in] u8Data SPI write data to EE
*
* @retval uint8_t SPI receive data from EE
*/
static uint8_t Spi_E2PROM_WriteReadByte(uint8_t u8Data)
{
uint8_t u8Byte;
/* Wait tx buffer empty */
while (Reset == SPI_GetStatus(SPI_UNIT, SPI_FLAG_TX_BUFFER_EMPTY))
{
}
/* Send data */
SPI_WriteDataReg(SPI_UNIT, (uint32_t)u8Data);
/* Wait rx buffer full */
while (Reset == SPI_GetStatus(SPI_UNIT, SPI_FLAG_RX_BUFFER_FULL))
{
}
/* Receive data */
u8Byte = (uint8_t)SPI_ReadDataReg(SPI_UNIT);
return u8Byte;
}
读取存储空间中指定地址内的存储值。最后关闭片选
#define E2PROM_READ_MEMORY (0x03U)
/**
* @brief SPI EEPROM Read a Byte
*
* @param [in] 1.unsigned int
*
* @retval uint8_t
*/
uint8_t E2PROM_Read_Byte(unsigned int address, uint8_t high_or_low64)
{
uint8_t data;
while((E2PROM_Read_Status()&0x01) == 0x01); //091119
SPI_NSS_LOW();
uint8_t addr0_7;
uint8_t addr8_15;
uint8_t addr16_23 = high_or_low64;
addr0_7 = address & 0xff;
addr8_15 = (address & 0xff00)>>8;
/* send "Read Status Register" instruction */
Spi_E2PROM_WriteReadByte(E2PROM_READ_MEMORY);
Spi_E2PROM_WriteReadByte(addr16_23);
Spi_E2PROM_WriteReadByte(addr8_15);
Spi_E2PROM_WriteReadByte(addr0_7);
data = Spi_E2PROM_WriteReadByte(0xff);
/* deselect the EEPROM */
SPI_NSS_HIGH();
/* return the status register value */
return data;
}
#define E2PROM_READ_MEMORY (0x03U)
/**
* @brief SPI EEPROM Read a Byte
*
* @param [in] 1.unsigned int
*
* @retval uint8_t
*/
uint8_t E2PROM_Read_Byte(unsigned int address, uint8_t high_or_low64)
{
uint8_t data;
while((E2PROM_Read_Status()&0x01) == 0x01); //091119
SPI_NSS_LOW();
uint8_t addr0_7;
uint8_t addr8_15;
uint8_t addr16_23 = high_or_low64;
addr0_7 = address & 0xff;
addr8_15 = (address & 0xff00)>>8;
/* send "Read Status Register" instruction */
Spi_E2PROM_WriteReadByte(E2PROM_READ_MEMORY);
Spi_E2PROM_WriteReadByte(addr16_23);
Spi_E2PROM_WriteReadByte(addr8_15);
Spi_E2PROM_WriteReadByte(addr0_7);
data = Spi_E2PROM_WriteReadByte(0xff);
/* deselect the EEPROM */
SPI_NSS_HIGH();
/* return the status register value */
return data;
}
如果要读地址连续的多个字节,只需要继续发dummy字节就可以了。
|