初识SPI,遇到问题,发帖请教。(已解决)

2019-10-16 02:21发布

u8 SPIx_ReadWriteByte(u8 TxData)
{
    u8 retry=0;
    while((SPI1->SR&1<<1)==0)//等待发送区空
    {
        retry++;
        if(retry>200)return 0;
    }
    SPI1->DR=TxData; //发送一个byte
    retry=0;
    while((SPI1->SR&1<<0)==0) //等待接收完一个byte
    {
        retry++;
        if(retry>200)return 0;
    }
r    eturn SPI1->DR; //返回收到的数据
}
今天学习到SPI实验了,看到SPI读写函数有点不解,为什么读和写能写在一个函数中啊?
当我读数据的时候要先发送一个数据么?
当我写完数据还要读一个数据么?

请大家指点下。谢谢
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
33条回答
wolfdong7
2019-10-16 07:34
static u8 SPI_Read_Byte(void)
{  
  //等待发送信号寄存器为非空,然后发送一个字节到spi总线上
  while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);
  SPI_I2S_SendData(SPI1, 0x00);

  //等待接收信号寄存器为非空,然后从spi总线上接收一个字节
  while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET)  /* Wait to receive a byte */;
  return SPI_I2S_ReceiveData(SPI1)  /* Return the byte read from the SPI bus */;
}

//spi 写一个字节
static void SPI_Write_Byte(u8 byte)
{  
  //时序同发生字节一样,只是不返回读取的字节
  while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET)  /* Loop while DR register in not emplty */;
  SPI_I2S_SendData(SPI1, byte)/* Send byte through the SPI2 peripheral */;

  while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET)  /* Wait to receive a byte */;
  SPI_I2S_ReceiveData(SPI1)  /* Return the byte read from the SPI bus */;
}

一周热门 更多>