使用STM32F103做MCU,在项目中用到6个称重模块,除了IO引脚不同,程序的其它是完全相同的。
现在是用define定义的
//////////////称重传感器IO口定义///////////////////
#define HX711R1CC RCC_APB2Periph_GPIOD
#define HX711_PORT1 GPIOD
#define PSCK1 PDout(1)
#define DOUT1 PDin(0)
#define HX711R2CC RCC_APB2Periph_GPIOA
#define HX711_PORT2 GPIOA
#define HX711R3CC RCC_APB2Periph_GPIOC
#define HX711_PORT3 GPIOC
#define HX711R4CC RCC_APB2Periph_GPIOD
#define HX711_PORT24 GPIOD
代码写了相似的6个
void Init_HX711pin(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); //使能端口时钟
//PSCK1
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; // 端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; //IO口速度为2MHz
GPIO_Init(GPIOD, &GPIO_InitStructure); //根据设定参数初始化GPIOB
//DOUT1
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_SetBits(GPIOD,GPIO_Pin_0); //初始化设置为0
}
//****************************************************
//读取HX711
//****************************************************
unsigned long HX711_Read(void)
{
unsigned long count;
unsigned char i;
DOUT1=1;
delay_us(1);
PSCK1=0;
count=0;
while(DOUT1);
for(i=0;i<24;i++)
{
PSCK1=1;
count=count<<1;
delay_us(1);
PSCK1=0;
if(DOUT1)
count++;
delay_us(1);
}
PSCK1=1;
delay_us(1);
PSCK1=0;
delay_us(1);
PSCK1=1;
delay_us(1);
PSCK1=0;
delay_us(1);
PSCK1=1;
count=count^0x800000;
delay_us(1);
PSCK1=0;
return(count);
}
有没有办法能用统一的函数来实现功能,把IO口的定义当做参数传进去?这样就可以避免写6个相似Init和read的代码了。
|