我的SPI读写函数是分开的,如下
[mw_shl_code=c,true]void SPIWriteByte(u8 dat)
{
SPI_I2S_SendData(SPI1,dat);
while(!SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_TXE));
}
u8 SPIReadByte(void)
{
u8 readDat;
readDat = SPI_I2S_ReceiveData(SPI1);
return readDat;
}[/mw_shl_code]
读取ID函数
[mw_shl_code=c,true]//读取芯片ID W25X16的ID:0XEF14
u16 SPI_Flash_ReadID(void)
{
u16 Temp = 0;
FLASH_CS_ENABLE();
SPIWriteByte(0x90);//发送读取ID命令
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0xff);
Temp |= SPIReadByte()<<8;
SPIWriteByte(0xff);
Temp |= SPIReadByte();
return Temp;
}[/mw_shl_code]
返回ID错误
后面我加多条打印观察情况
[mw_shl_code=c,true]//读取芯片ID W25X16的ID:0XEF14
u16 SPI_Flash_ReadID(void)
{
u16 Temp = 0;
FLASH_CS_ENABLE();
SPIWriteByte(0x90);//发送读取ID命令
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp1:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp2:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp3:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp4:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp5:%x\r\n",Temp);
return Temp;
}[/mw_shl_code]
结果如下,
也就是第一个字节读取错误,我怀疑是不是有一条0xff没有发出去,导致第一个字节错误,遂把程序更为
[mw_shl_code=c,true]//读取芯片ID W25X16的ID:0XEF14
u16 SPI_Flash_ReadID(void)
{
u16 Temp = 0;
FLASH_CS_ENABLE();
SPIWriteByte(0x90);//发送读取ID命令
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0xff);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp1:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp2:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp3:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp4:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp5:%x\r\n",Temp);
return Temp;
}[/mw_shl_code]
结果如下,
对比上面可以发现,其实,0xff发送是成功的,接收寄存器里面上面一次本应该是0xef,这次本应该是0x16,不知道问题出在哪里?
后面把程序更为下面
[mw_shl_code=c,true]//读取芯片ID W25X16的ID:0XEF14
u16 SPI_Flash_ReadID(void)
{
u16 Temp = 0;
FLASH_CS_ENABLE();
SPIWriteByte(0x90);//发送读取ID命令
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIWriteByte(0x00);
SPIReadByte();
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp1:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp2:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp3:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp4:%x\r\n",Temp);
SPIWriteByte(0xff);
Temp = SPIReadByte();
printf("temp5:%x\r\n",Temp);
return Temp;
}[/mw_shl_code]
读取成功!
这让人有点无法理解,我们都知道主从SPI设备的寄存器其实是构成了一个环形,最后一个0x00发送完毕后,接收寄存器里面的应该是0xff,这个没错,但当我们再次发送一个0xff时,即使上次接收寄存器里面的数据不读出,新的数据(0xef)也应该把它挤掉啊,为什么命令发送结束后只要不读取,无论发送多少次0xff,接收寄存器里面的值都是0xff呢?
之前做8051设备的时候就不是这样的啊 |