软件模拟spi c语言实现

2021-03-14 16:36

阅读:386

标签:cti   ret   语言   i++   color   adr   sda   说明   rgba   

//spi数据写入驱动
void SPI_SEND_BYTE(uint8_t data)
{
    uint8_t i = 0;
    uint8_t tmp = data;
    for (i = 0; i 8; i++)
    {
        SIMU_SPI_SCK_L();
        sleep_us(1);
        if (tmp & 0x80)
        {
            SIMU_SPI_SDA_H();
        }
        else
        {
            SIMU_SPI_SDA_L();
        }
        sleep_us(1);
        SIMU_SPI_SCK_H();
        sleep_us(1);
        tmp 1;
        sleep_us(1);
    }
}

//spi数据读取驱动
uint16_t SPI_RECV_BYTE(void)
{
    uint16_t data = 0;
    uint8_t i = 0;

    SIMU_SPI_SDA_INPUT();
    SIMU_SPI_SCK_L();
    for (i = 0; i 16; i++)
    {
        sleep_us(1);
        data 1;
        sleep_us(1);
        SIMU_SPI_SCK_H();
        sleep_us(1);
        if (IS_SIMU_SPI_SDA_H())
        {
            data |= 0x01;
        }
        sleep_us(1);
        SIMU_SPI_SCK_L();
    }
    SIMU_SPI_SDA_OUTPUT();
    return data;
}

//写寄存器数据
void WriteReg_shell(uint8_t addr, uint16_t word)
{
    SIMU_SPI_SDA_OUTPUT();
    SIMU_SPI_SCK_L();
    SPI_NSS_ACTIVE();
  
    uint16_t temp = word >> 8;
    SPI_SEND_BYTE(addr);
    SPI_SEND_BYTE((temp)&0xFF);
    SPI_SEND_BYTE((word)&0xFF);
    SPI_NSS_INACTIVE();
}

//读寄存器数据
uint16_t ReadReg_shell(uint8_t addr)
{
    uint16_t word;
    SIMU_SPI_SDA_OUTPUT();
    SIMU_SPI_SCK_L();
    SPI_NSS_ACTIVE();
  
    uint8_t tmp_addr = (addr | 0x80);
    SPI_SEND_BYTE(tmp_addr);
    sleep_us(2);
    word = SPI_RECV_BYTE();
    SPI_NSS_INACTIVE();

    return word;
}
代码说明:
前面两个函数是读取/写入的时序
后面两个函数是读取设备寄存器的demo代码


其中需要注册进去的接口


一、设置spi clk引脚高低
SIMU_SPI_SCK_H(); 
SIMU_SPI_SCK_L();
二、设置spi data引脚高低
SIMU_SPI_SDA_H();
SIMU_SPI_SDA_L();
三、设置spi data引脚输入输出模式
SIMU_SPI_SDA_OUTPUT();
SIMU_SPI_SDA_INPUT();
四、设置spi NSS引脚高低(spi使能)
SPI_NSS_ACTIVE();//拉低开启使能
SPI_NSS_INACTIVE();//拉高关闭使能

 
 

软件模拟spi c语言实现

标签:cti   ret   语言   i++   color   adr   sda   说明   rgba   

原文地址:https://www.cnblogs.com/bliss-/p/14024507.html


评论


亲,登录后才可以留言!