|
我使用的是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。是代碼問題嗎?
|
|