2015-10-31 17 views
-1

我正在與Beaglebone合作開發四軸飛行器項目。如何從char *切換到const char * [pwm in beaglebone]?

我需要幫助通過C程序在Beaglebone上使用pwm。

我附上下面的代碼,

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 

struct pwm 
{ 
    char period[100]; 
    char duty[100]; 
    char polarity[100]; 
    char run[100]; 
}pwm1,pwm2,pwm3,pwm4; 

char pwm_1[]="P9_21"; 
char pwm_2[]="P9_14"; 
char pwm_3[]="P8_13"; 
char pwm_4[]="P9_42"; 

int initialize(struct pwm &pwmi, char pwm_i[]) 
{ 
    sprintf(path,"echo \"bone_pwm_%s\" >> /sys/devices/bone_capemgr.9/slots",pwm_i); 
    fp = popen(path,"r"); 
    fflush(fp); 
    usleep(1000); 
    sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/period",pwm_i); 
    fp = popen(path,"r"); 
    while(fgets(path,100,fp)!=NULL) 
     strcpy(pwmi.period,path); 
    fflush(fp); 
    sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/duty",pwm_i); 
    fp = popen(path,"r"); 
    while(fgets(path,100,fp)!=NULL) 
     strcpy(pwmi.duty,path); 
    fflush(fp); 
    sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/polarity",pwm_i); 
    fp = popen(path,"r"); 
    while(fgets(path,100,fp)!=NULL) 
     strcpy(pwmi.polarity,path); 
    fflush(fp); 
    sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/run",pwm_i); 
    fp = popen(path,"r"); 
    while(fgets(path,100,fp)!=NULL) 
     strcpy(pwmi.run,path); 
    fflush(fp); 
    pclose(fp); 
    return 0; 
    printf("%s%s%s%s",pwmi.period,pwmi.duty,pwmi.polarity,pwmi.run) 
} 

int pwmperiod(struct pwm &pwmi, unsigned int period) 
{ 
    sprintf(path,"echo %d > %s", period, pwm.period); 
    fp = popen(path,"r"); 
    usleep(1000); 
    pclose(fp); 
    return 0; 
} 

int main() 
{ 
    unsigned int period = 200000; 
    initialize(pwm1,pwm_1); 
    initialize(pwm2,pwm_2); 
    initialize(pwm3,pwm_3); 
    initialize(pwm4,pwm_4); 
    pwmperiod(pwm1,period); 
    return 0; 
} 

現在上面的代碼工作完全正常。但我想使用pwmperiod()函數有點不同。我一直想用fopen()fprintf()作爲函數pwmperiod(),而不是使用popen()。這樣的事情,

int pwmperiod(struct pwm &pwmi, unsigned int period) 
{ 
    fp = fopen(pwmi.period,"r+"); 
    fseek(fp,0,SEEK_SET); 
    fprintf(fp,"%d",period); 
    fclose(fp); 
    return 0; 
} 

我試圖修改後的代碼,但是當它試圖寫入週期值時,輸出「分段錯誤」。

我意識到fopen()需要const charpwmi.period只是char。另一個問題popen()sprint()const char不兼容。

那麼有沒有辦法來解決轉換?

popen()在C/C++程序中使用的頻率又如何?

PS: 不是專家編碼器,我不是來自計算機科學背景。我正在逐步學習。

此外,代碼完美地與popen()一起使用。但後來我對C中的文件處理感到滿意。所以我寧願個人更喜歡fopen()而不是popen()。此外,我覺得在C中使用popen()毫無意義,也可以使用pwm的shell腳本。

+0

您可以在沒有顯式轉換的情況下將'char *'傳遞給請求'const char *'的參數,但不能做相反的事情。 – MikeCAT

+0

標準'fopen()'不會帶'const char'。 – MikeCAT

+0

我意識到這一點。但有沒有辦法從char *轉換爲const char * – eurekaman7

回答

0

暫時擱置char*const char*的問題(因爲char*無論如何可以傳遞給任何函數,採取const char*)。

您是否檢查過fopen的返回值是否爲非NULL?

請注意,當fopenr+一起被調用時,該文件必須存在。如果沒有,fopen將返回NULL,生成段錯誤。

由於文件只被寫,讀不懂,可以考慮使用

fp = fopen(pwmi.period,"w"); 

如果確實,這將創建一個新的文件不存在。