標(biāo)題: 請(qǐng)教C語言代碼架構(gòu)問題 [打印本頁]

作者: jindizhiwa    時(shí)間: 2018-11-29 22:33
標(biāo)題: 請(qǐng)教C語言代碼架構(gòu)問題

使用STM32F103做MCU,在項(xiàng)目中用到6個(gè)稱重模塊,除了IO引腳不同,程序的其它是完全相同的。
現(xiàn)在是用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個(gè)



void Init_HX711pin(void)
{
        GPIO_InitTypeDef GPIO_InitStructure;
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);         //使能端口時(shí)鐘

        //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);                                         //根據(jù)設(shè)定參數(shù)初始化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);                                        //初始化設(shè)置為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);
}


有沒有辦法能用統(tǒng)一的函數(shù)來實(shí)現(xiàn)功能,把IO口的定義當(dāng)做參數(shù)傳進(jìn)去?這樣就可以避免寫6個(gè)相似Init和read的代碼了。



作者: 萬物互聯(lián)    時(shí)間: 2018-11-29 23:33
可以啊。GPIO_SetBits(GPIOD,GPIO_Pin_0);這個(gè)函數(shù)本身就是傳入組別和pin端口號(hào)的,你從init函數(shù)和read函數(shù)把這兩個(gè)參數(shù)傳進(jìn)來就好了。
作者: mjjiang    時(shí)間: 2018-11-30 03:18
直接傳參數(shù)就行了
作者: jindizhiwa    時(shí)間: 2018-11-30 08:55
read函數(shù)這樣命名:unsigned long HX711Read(void(*set)(),void(*reset)()),代碼中的怎么置位,復(fù)位和讀取怎么寫呢?
作者: 蒼穹之夜    時(shí)間: 2018-11-30 09:29
這程序可以,很優(yōu)秀
作者: jindizhiwa    時(shí)間: 2018-11-30 09:48

直接傳參數(shù)就行了,怎么傳?




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1