|
我使用的是STM32F103C8T6和PCAP01来做SPI1通讯。在使用的过程中发现,SPI1有的时候使用没有问题,通讯正常,有的时候通信失败,SPI1用不了。如果是代码或者硬件有问题,那应该不能通讯,为什么有的时候好用,有的时候不好用。想问问大家,有没有遇到这种情况的?
这是我的代码:
unsigned char Send_24Bit_Opcode(unsigned char command, unsigned short address, unsigned char data)
{
unsigned char Result_read = 0;
// x >> y, mean x is shifted by y bit-positions to the right
unsigned char Byte_0 = data;
unsigned char Byte_1 = address;
unsigned char Byte_2 = address>>8 | command;
// SPIx BUS_TYPE -------------------------------------------------------------
// Deactivating Reset SPIx
GPIO_WriteBit(GPIOA, GPIO_Pin_4, Bit_RESET);
// GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE)==0) {}
SPI_I2S_SendData(SPI1, Byte_2); // send byte 2
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE)==0) {}
SPI_I2S_SendData(SPI1, Byte_1); // send byte 1
if (command==0x90) // write command
{
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE)==0) {}
SPI_I2S_SendData(SPI1, Byte_0); // send byte 0
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE)==0) {}
Simple_delay_43ns((void*)10); // important delay (16) at SPI freq.=750kHz
}
if (command==0x10) // read command
{
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE)==RESET) {};
Simple_delay_43ns((void*)10); // important delay (16) at SPI freq.=750kHz
//Compulsory reads to DR and SR to clear OVR,
//so that next incoming data is saved
SPI_I2S_ReceiveData(SPI1); // To clear OVR
SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE); // To clear OVR
//Reading byte1
SPI_I2S_SendData(SPI1, 0xFF); // DUMMY WRITE
// Wait until RX buffer is not empty, then read the received data
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE)==0) {}
Result_read = SPI_I2S_ReceiveData(SPI1); // Read
}
// Reset to device SPIx
GPIO_WriteBit(GPIOA, GPIO_Pin_4, Bit_SET);
//GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_SET);
return Result_read;
}
Send_24Bit_Opcode(0x90,1,0x55);//0x90 写
err = Send_24Bit_Opcode(0x10,1,0xff);//err = 0x55 0x10读
读不回0x55 每次都是0xFF。是代码问题吗?
|
|