主要是写寄存器的时候.CS拉低后没加延迟,还有CS拉高结束之前要加入延迟.
虽然手册上写得是5ns左右.按道理说,没加也没事.
我觉得用GPIO拉低CS线,速度比较慢.而SPI发送数据比较快.所以造成片选延迟不够.
下面是我写的程序
/* 库文件驱动说明
*/
/* 意法lis3lv02qd传感器的CS片选 */
#define Lis_Cs_High GPIO_SetBits(GPIOB,GPIO_Pin_7)
#define Lis_Cs_Low GPIO_ResetBits(GPIOB,GPIO_Pin_7)
/*************** SPI0 写命令************************/
void SPI_Write(uint16_t address,uint16_t dat)
{
Lis_Cs_Low;
Delay(5);
SPI2->DR=address;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); //等待发送缓存空标志
SPI2->DR=dat;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); //等待发送缓存空标志
Delay(10);
Lis_Cs_High;
}
/************* SPI读两字节命令 ****************/
int16_t SPI_Read(int16_t address)
{
int16_t dat=0;
Lis_Cs_Low; //片选拉低
Delay(1);
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
SPI2->DR=address;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
SPI2->DR=0xff;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
dat= SPI2->DR;
SPI2->DR=0xff;
dat<<=8;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
dat|=SPI2->DR;
Delay(2);
Lis_Cs_High; //片选拉高
return dat; //返回dat
}
/* lis3lv02qd SPI初始化函数 */
void SPI_Lis3_Init()
{
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
/* 使能SPI2 GPIOB 的时钟 */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
/* Configure SPI1 pins: SCK, MISO and MOSI */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 |GPIO_Pin_15 ; //Pin_5是SCK时钟 Pin7是MOSI输出信号
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //设成复用推挽
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14 ; //MISO ; //Pin_5是SCK时钟 Pin7是MOSI输出信号,设成复用推挽
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; // lis3 的片选脚
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction =SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low ;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI2, &SPI_InitStructure);
SPI_Cmd(SPI2,ENABLE);
SPI_SSOutputCmd(SPI2,DISABLE);
}
void Lis3_Init()
{
SPI_Lis3_Init(); //初始化SPI设置
//Delay(1000);
SPI_Write(0x20,0xD7); //CTRL_REG1
SPI_Write(0x21,0x15); //CTRL_REG2 15四线模式,17三线模式
}