公司买了一块 原子 stm32 mimi板 进行练习spi 但是读出来的数据 总是不对。本来是20的读出来就变成10了。
stm32->spi->93c56A
读写出来的效果如下 通过串口显示调试信息
代码如下:
void SPI_CSEnable()
{
SPI_FLASH_CS=1;
}
void SPI_CSDisable()
{
SPI_FLASH_CS=0;
}
void WriteEECmd(u8 cmd)
{
SPI_CSEnable() ;
SPIx_ReadWriteByte(cmd);//eeprom 命令
SPIx_ReadWriteByte(0xff);//
SPI_CSDisable();
delay_ms(100);
}
void spi_Write(u8 adr,u8 data)
{
//写数据
SPI_CSEnable() ;
SPIx_ReadWriteByte(0x05);//写命令
SPIx_ReadWriteByte(adr);//写地址
SPIx_ReadWriteByte(data>>8);//高位数据
SPIx_ReadWriteByte(data&0xff);//地位数据
printf("wite adrr [%d] data [%d]\n",adr,data);
SPI_CSDisable();
delay_ms(100);
}
void spi_Read(u8 adrr)
{
u16 Temp = 0;
//读数据
SPI_CSEnable() ;
SPIx_ReadWriteByte(0x06);//读命令
SPIx_ReadWriteByte(adrr);//读地址
Temp|=SPIx_ReadWriteByte(0xFF)>>8;
Temp|=SPIx_ReadWriteByte(0xFF);
printf("read adrr [%d] data [%d]\n",adrr,Temp);
SPI_CSDisable();
}
int main()
{
u8 i=0;
SystemInit();
delay_init(72); //延时初始化
uart_init(9600); //设置串口打印输出 printf
SPIx_Init(); //SPI 初始化
WriteEECmd(0x98);//eeprom使能
WriteEECmd(0x90);//eeprom擦除
for(i=0;i<10;i++)
spi_Write(i,i+20);
printf("--------------------------------\n");
for(i=0;i<20;i++)
spi_Read(i);
return 1;
}
void SPIx_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOC,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; //SPI CS
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //通用推挽输出
GPIO_Init(GPIOC, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOC|RCC_APB2Periph_SPI1, ENABLE ); //打开gpioa 和spi1 端口
// GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_5|GPIO_Pin_7);
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// GPIO_SetBits(GPIOC,GPIO_Pin_6);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //设置SPI单向或者双向的数据模式:SPI设置为双线双向全双工
SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //设置SPI工作模式:设置为主SPI
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //设置SPI的数据大小:SPI发送接收8位帧结构
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; //选择了串行时钟的稳态:时钟悬空高
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; //数据捕获于第1个时钟沿
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //NSS信号由硬件(NSS管脚)还是软件(使用SSI位)管理:内部NSS信号有SSI位控制
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128; //定义波特率预分频的值:波特率预分频值为256
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //指定数据传输从MSB位还是LSB位开始:数据传输从MSB位开始
SPI_InitStructure.SPI_CRCPolynomial = 7; //CRC值计算的多项式
SPI_Init(SPI1, &SPI_InitStructure); //根据SPI_InitStruct中指定的参数初始化外设SPIx寄存器
SPI_Cmd(SPI1, ENABLE); //使能SPI外设
SPIx_ReadWriteByte(0xff);//启动传输
}
就大神指点。不知道我的问题出在哪里。小弟感激不尽!
|