2.3驱动代码
以stm32f1为例,以“spi抽象/硬件spi”中的spi封装代码为基础,驱动mcp3202。
#include "spi_core.h"
#include "spi_hw.h"
static struct spi_dev_device mcp3202_spi_dev;
static struct spi_bus_device spi_bus0;
static void spi0_cs(unsigned char state)
{
if (state)
GPIO_SetBits(GPIOC, GPIO_Pin_4);
else
GPIO_ResetBits(GPIOC, GPIO_Pin_4);
}
void mcp3202_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//spi cs
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC ,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_SetBits(GPIOC, GPIO_Pin_4);
//device init
stm32f1xx_spi_init(&spi_bus0,8,0,0);
mcp3202_spi_dev.spi_cs = spi0_cs;
mcp3202_spi_dev.spi_bus = &spi_bus0;
}
u16 mcp3202_read(u8 mode)
{
u8 send_buff[3],recv_buff[3];
send_buff[0] = 0x01;
send_buff[1] = mode;
send_buff[2] = 0x00;
spi_send_recv(&mcp3202_spi_dev,send_buff,recv_buff,3);
return (((recv_buff[1] << 8) | recv_buff[2])&0x0fff);
}
|