嵌入式开发中模拟SPI的驱动

这里贴一下自己的模拟SPI驱动,移植的话需要实现SPI管脚的定义和初始化。

一、管脚初始化

  • MOSI_PIN:设置MOSI为输出模式
  • SCK_PIN:设置SCK为输出模式
  • CSN_PIN:设置CSN为输出模式
  • MISO_PIN:设置MISO为输入模式
  • MOSI_PIN_HIGH:设置MOSI为高电平
  • MOSI_PIN_LOW:设置MOSI为低电平
  • SCK_PIN_HIGH:设置SCK为高电平
  • SCK_PIN_LOW:设置SCK为低电平
  • CSN_PIN_HIGH:设置CSN为高电平
  • CSN_PIN_LOW:设置CSN为低电平

二、模拟SPI时序

模拟时序的时钟设置为500kHz,即时钟拉高1us,拉低1us。

/*!
 * \brief   Simulate SPI read-timing method, base-read driver
 * \para    none
 * \retval  read_val:uint8_t
 */
static uint8_t SPI_Read_OneByte(void)
{
    uint8_t i;
    uint8_t read_val = 0;
    for(i=0; i < 8; i++)
    {
        val <<= 1;
        SCK_PIN_HIGH;         
        if(MISO_PIN == 1)
            read_val |= 0x01;
        else
            read_val &= ~0x01;
        delay_us(1);//500KHz SPI
        SCK_PIN_LOW;
        delay_us(1);//500kHz SPI
    }
    return read_val;
}
/*!
 * \brief   Simulate SPI write-timing method, base-write driver
 * \para    write_val:uint8_t
 * \retval  none
 */
static void SPI_Write_OneByte(uint8_t write_val)
{
    uint8_t i;
    for(i=0; i < 8; i++)
    {
        if(write_val & 0x80)
            MOSI_PIN_HIGH;
        else
            MOSI_PIN_LOW;

        SCK_PIN_HIGH;
        write_val <<= 1;
        delay_us(1);//500KHz SPI
        SCK_PIN_LOW;
        delay_us(1);//500KHz SPI
    }
}

三、SPI对外接口API

使用SPI_WriteData和SPI_ReadData操作SPI设备和外设。

/*!
 * \brief   SPI write buff method, api driver
 * \para    addr:uint8_t,reg addr
 			dataptr:uint8_t *,pointer of SPI write buff
 			length:uint16_t, size of buff
 * \retval  none
 */
void SPI_WriteData(uint8_t addr, uint8_t *dataptr, uint16_t length )
{
    int i;
    CSN_PIN_LOW;
    SPI_Write_OneByte(addr|WR_CMD); 
    for(i = 0; i < length, i++)
        SPI_Write_OneByte(dataptr[i]);
    CSN_PIN_HIGH; 
}
/*!
 * \brief   SPI read buff method, api driver
 * \para    addr:uint8_t,reg addr
 			dataptr:uint8_t *,pointer of SPI read buff
 			length:uint16_t, size of buff
 * \retval  none
 */
void SPI_ReadData(uint_t addr, uint8_t *dataptr, uint16_t length )
{
    uint8_t value;
    int i;
    CSN_PIN_LOW; 
    SPI_Write_OneByte(addr|RR_CMD);
    for(i = 0; i < length, i++)
        dataptr[i] = SPI_Read_OneByte();  
    CSN_PIN_HIGH;
}

 

你可能感兴趣的:(嵌入式,模拟SPI)