其他分享
首页 > 其他分享> > 单片机驱动-软件模拟SPI

单片机驱动-软件模拟SPI

作者:互联网

一、软件模拟SPI程序

#define GD25Q256DF_CS_DIR            MKL25Z4_GPIO_DDR_OUTPUT(MKL_PORTA, 19)
#define GD25Q256DF_CS_LOW            MKL25Z4_GPIO_CLR(MKL_PORTA, 19)
#define GD25Q256DF_CS_HIGH            MKL25Z4_GPIO_SET(MKL_PORTA, 19)

#define SPI_SCLK_DIR                MKL25Z4_GPIO_DDR_OUTPUT(MKL_PORTA, 18)
#define SPI_SCLK_CLR                MKL25Z4_GPIO_CLR(MKL_PORTA, 18)
#define SPI_SCLK_SET                MKL25Z4_GPIO_SET(MKL_PORTA, 18)


#define SPI_DOUT_DIR                MKL25Z4_GPIO_DDR_OUTPUT(MKL_PORTD, 7)
#define SPI_DOUT_CLR                MKL25Z4_GPIO_CLR(MKL_PORTD, 7)
#define SPI_DOUT_SET                MKL25Z4_GPIO_SET(MKL_PORTD, 7)


#define SPI_DIN_DIR                    MKL25Z4_GPIO_DDR_INPUT(MKL_PORTA, 4)
#define SPI_DIN_PIN                    MKL25Z4_GPIO_GET_VALUE(MKL_PORTA, 4)

 

 

/* 
 *@brief spi软件延时
 *@param 延时时长
 *@retval none
 *@author Mr.W
 *@date 2020-8-4
 */
static void spi_delay(volatile uint32_t us)
{
    volatile uint32_t i, j;
    
    for(i = 0; i < us; i++)
    {
        for(j = 0; j < 16; j++);
    }
}

/* 
 *@brief spi引脚初始化
 *@param 延时时长
 *@retval none
 *@author Mr.W
 *@date 2020-8-4
 */
static void spi_init()
{
    GD25Q256DF_CS_DIR;
    SPI_SCLK_DIR;
    SPI_DOUT_DIR;
    SPI_DIN_DIR;
}

/* 
 *@brief spi写一个字节
 *@param 要写的数据
 *@retval none
 *@author Mr.W
 *@date 2020-8-4
 */
static void spi_send_byte(uint8_t data)
{
    uint8_t i;
    
    for(i = 0; i < 8; i++)
    {
        SPI_SCLK_CLR;
        spi_delay(10);
        if(data & 0x80)
            SPI_DOUT_SET;
        else
            SPI_DOUT_CLR;
        SPI_SCLK_SET;
        spi_delay(10);
        data <<= 1;
    }
}

/* 
 *@brief spi读一个字节
 *@retval 读到的数据
 *@author Mr.W
 *@date 2020-8-4
 */
static uint8_t spi_receive_byte(void)
{
    uint8_t i;
    uint8_t data = 0;
    
    for(i = 0; i < 8; i++)
    {
        SPI_SCLK_CLR;
        spi_delay(10);
        data <<= 1;
        if(SPI_DIN_PIN)
        {
            data |= 0x01;
        }
        SPI_SCLK_SET;
        spi_delay(10);
    }
    return data;
}

 

#end

标签:MKL25Z4,SPI,MKL,spi,单片机,GPIO,模拟,define
来源: https://www.cnblogs.com/wenhao-Web/p/13546951.html