/** * @brief Read SPI flash memory. * @param spi is the base address of SPI module. * @param u32StartAddress is the start address. * @param au8DataBuffer is the pointer of destination buffer. * @param u32ByteCount is the total data count. * @return None. * @note Before calling this function, the transaction length (data width) must be configured as 8 bits. */ void SpiFlash_ReadData(SPI_T *spi, uint32_t u32StartAddress, uint8_t *au8DataBuffer, uint32_t u32ByteCount) { uint32_t u32RxCounter; /* /CS: active */ SPI_SET_SS_LOW(spi); /* Send command 0x03: Read data */ SPI_WRITE_TX0(spi, 0x03); /* Trigger SPI transfer */ SPI_TRIGGER(spi); /* Check busy state */ while(SPI_IS_BUSY(spi)); /* Send 24-bit start address */ /* Send the first 8 address bits */ SPI_WRITE_TX0(spi, (u32StartAddress >> 16) & 0xFF); /* Trigger SPI transfer */ SPI_TRIGGER(spi); /* Check busy state */ while(SPI_IS_BUSY(spi)); /* Send the second 8 address bits */ SPI_WRITE_TX0(spi, (u32StartAddress >> 8) & 0xFF); /* Trigger SPI transfer */ SPI_TRIGGER(spi); /* Check busy state */ while(SPI_IS_BUSY(spi)); /* Send the third 8 address bits */ SPI_WRITE_TX0(spi, u32StartAddress & 0xFF); /* Trigger SPI transfer */ SPI_TRIGGER(spi); /* Check busy state */ while(SPI_IS_BUSY(spi)); /* Reset RX data counter */ u32RxCounter = 0; while(u32RxCounter < u32ByteCount) { /* Send SPI bus clock to get data from SPI flash */ SPI_WRITE_TX0(spi, 0x00); /* Trigger SPI transfer */ SPI_TRIGGER(spi); /* Check busy state */ while(SPI_IS_BUSY(spi)); /* Read data */ au8DataBuffer[u32RxCounter++] = SPI_READ_RX0(spi); } /* /CS: inactive */ SPI_SET_SS_HIGH(spi); }
int spi_read_packet(SPI_T *spi, uint8_t *data, int len) { int timeout, i; for(i=0; len != 0; i++, len--) { timeout = SPI_TIMEOUT; SPI_WRITE_TX0(spi, 0); SPI_TRIGGER(spi); while(SPI_IS_BUSY(spi)) { if(!timeout--) { printf("spi_read_packet timeout (len = %d)\n",len); return(-1); } } data[i] = SPI_READ_RX0(spi); } return(0); }