初始化模块的时候,经常会用到SPI通信,整理了一下SPI通信的代码;移植后修改宏定义就可使用;
第一种规格,地址和数据先整合为short类型,之后连续发送16bits
使用时:
devices_spi_write_byte(addr, data);
#define SPI_IO_SDA (GPIO_0)
#define SPI_IO_SCL (GPIO_1)
#define SPI_IO_CS (GPIO_2)
#define SPI_SCL_OUT gpio_setDir(SPI_IO_SCL, GPIO_DIR_OUTPUT)
#define SPI_SCL_IN gpio_setDir(SPI_IO_SCL, GPIO_DIR_INPUT)
#define SPI_SCL_HIGH gpio_setPin(SPI_IO_SCL)
#define SPI_SCL_LOW gpio_clearPin(SPI_IO_SCL)
#define SPI_SDA_OUT gpio_setDir(SPI_IO_SDA, GPIO_DIR_OUTPUT)
#define SPI_SDA_IN gpio_setDir(SPI_IO_SDA, GPIO_DIR_INPUT)
#define SPI_SDA_HIGH gpio_setPin(SPI_IO_SDA)
#define SPI_SDA_LOW gpio_clearPin(SPI_IO_SDA)
#define SPI_SDA_DETECT gpio_getPin(SPI_IO_SDA)
#define SPI_CS_OUT gpio_setDir(SPI_IO_CS, GPIO_DIR_OUTPUT)
#define SPI_CS_IN gpio_setDir(SPI_IO_CS, GPIO_DIR_INPUT)
#define SPI_CS_HIGH gpio_setPin(SPI_IO_CS)
#define SPI_CS_LOW gpio_clearPin(SPI_IO_CS)
#define SPI_DELAY_US(x) Delay_DelayUs(x)
void devices_spi_write_byte(unsigned char addr, unsigned char value)
{
unsigned char j;
unsigned int commond;
SPI_SCL_OUT;
SPI_SDA_OUT;
SPI_CS_OUT;
SPI_CS_HIGH;
SPI_SCL_HIGH;
SPI_SDA_HIGH;
commond = addr;
commond = commond << 8;
commond |= value;
SPI_DELAY_US(500);
SPI_CS_LOW;
for(j = 16; j > 0; j--)
{
if(((commond >> (j - 1)) & 0x01))
SPI_SDA_HIGH;
else
SPI_SDA_LOW;
SPI_DELAY_US(100);
SPI_SCL_LOW;
SPI_DELAY_US(200);
SPI_SCL_HIGH;
SPI_DELAY_US(100);
}
SPI_DELAY_US(500);
SPI_CS_HIGH;
}
第二种规则,地址和数据分开发送,使用时一般需:
devices_spi_write_byte(addr);
devices_spi_write_byte(data);
#define SPI_IO_SDA (GPIO_0)
#define SPI_IO_SCL (GPIO_1)
#define SPI_IO_CS (GPIO_2)
#define SPI_SCL_OUT gpio_setDir(SPI_IO_SCL, GPIO_DIR_OUTPUT)
#define SPI_SCL_IN gpio_setDir(SPI_IO_SCL, GPIO_DIR_INPUT)
#define SPI_SCL_HIGH gpio_setPin(SPI_IO_SCL)
#define SPI_SCL_LOW gpio_clearPin(SPI_IO_SCL)
#define SPI_SDA_OUT gpio_setDir(SPI_IO_SDA, GPIO_DIR_OUTPUT)
#define SPI_SDA_IN gpio_setDir(SPI_IO_SDA, GPIO_DIR_INPUT)
#define SPI_SDA_HIGH gpio_setPin(SPI_IO_SDA)
#define SPI_SDA_LOW gpio_clearPin(SPI_IO_SDA)
#define SPI_SDA_DETECT gpio_getPin(SPI_IO_SDA)
#define SPI_CS_OUT gpio_setDir(SPI_IO_CS, GPIO_DIR_OUTPUT)
#define SPI_CS_IN gpio_setDir(SPI_IO_CS, GPIO_DIR_INPUT)
#define SPI_CS_HIGH gpio_setPin(SPI_IO_CS)
#define SPI_CS_LOW gpio_clearPin(SPI_IO_CS)
#define SPI_DELAY_US(x) Delay_DelayUs(x)
void devices_spi_write_byte(unsigned char value)
{
unsigned char j;
SPI_SCL_OUT;
SPI_SDA_OUT;
SPI_CS_OUT;
SPI_CS_HIGH;
SPI_SCL_HIGH;
SPI_SDA_HIGH;
SPI_DELAY_US(500);
SPI_CS_LOW;
for(j = 8; j > 0; j--)
{
if(((value >> (j - 1)) & 0x01))
SPI_SDA_HIGH;
else
SPI_SDA_LOW;
SPI_DELAY_US(100);
SPI_SCL_LOW;
SPI_DELAY_US(200);
SPI_SCL_HIGH;
SPI_DELAY_US(100);
}
SPI_DELAY_US(500);
SPI_CS_HIGH;
}