之前用GPIO模拟SPI速度有点慢,加上直接发送字节的方式实现SPI。
1. IO的定义
如果不使用模拟的方式,则SCK,MOSI,MISO必须固定。通过这3个IO判断是哪种模式
if(spi[port].sck != 0 || spi[port].mosi_io0 != 1 || spi[port].miso_io1 != 2)
{
//GPIO模拟的方式
}
else
{
}
2. 模式的限制
似乎只支持模式0,虽然文档上写的命令应该支持0或3。
3. 实现
之前8位数据是通过IO分8次发送出去,这里是采用0x31或0x39发送。
else
{
uint8_t *pwrDat;
if(wrBuf == NULL)
{
pwrDat = malloc(len);
for(int i = 0; i < len; i++)
pwrDat[i] = 0xff;
}
else
pwrDat = wrBuf;
switch(spi[port].mode)
{
case SPI_MODE0:
if(spi[port].msb == true)
spi[port].pCommand[spi[port].iCommand++] = 0x31;
else
spi[port].pCommand[spi[port].iCommand++] = 0x39;
spi[port].pCommand[spi[port].iCommand++] = (uint8_t)((len - 1) & 0xff);
spi[port].pCommand[spi[port].iCommand++] = (uint8_t)(((len - 1) >> 8) & 0xff);
for(int i = 0; i < len; i++)
{
spi[port].pCommand[spi[port].iCommand++] = pwrDat[i];
}
break;
case SPI_MODE3:
if(spi[port].msb == true)
spi[port].pCommand[spi[port].iCommand++] = 0x31;
else
spi[port].pCommand[spi[port].iCommand++] = 0x39;
spi[port].pCommand[spi[port].iCommand++] = (uint8_t)((len - 1) & 0xff);
spi[port].pCommand[spi[port].iCommand++] = (uint8_t)(((len - 1) >> 8) & 0xff);
for(int i = 0; i < len; i++)
{
spi[port].pCommand[spi[port].iCommand++] = pwrDat[i];
}
break;
default:
printf("no support mode:%d\n", spi[port].mode);
break;
}
}
读数据也不需要读入len * 8个字节了
if(spi[port].sck != 0 || spi[port].mosi_io0 != 1 || spi[port].miso_io1 != 2)
rdLen = len * 8;
else
rdLen = len;
读入的数据也不需要按位组合位字节。
else
{
for(int i = 0; i < rdLen; i++)
{
rdBuf[i] = pReadBuf[i];
}
}
4. 验证
将IO的定义改成
spiSetting.sck = 0;
spiSetting.mosi_io0 = 1;
spiSetting.miso_io1 = 2;
同样基于nor flash读写1MB的数据
sflash id is:ef4018
Erase Chip Finish
erase time:41027ms
write time:14672ms
read time:3537ms
sflash test finish
速度是1M / 0.3537 = 2.83MB/s