如何从char*切换到const char*[beaglebone中的pwm]?
我正在和Beaglebone合作一个四架直升机项目 我需要通过C程序在Beaglebone上使用pwm的帮助 我已附上以下代码如何从char*切换到const char*[beaglebone中的pwm]?,c,embedded-linux,fopen,popen,beagleboneblack,C,Embedded Linux,Fopen,Popen,Beagleboneblack,我正在和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,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;
}
我尝试了修改后的代码,但当它试图写入周期值时,它会输出“分段错误”
我意识到fopen()
需要const char
,而pwmi.period
只是char
。另一个问题是popen()
和sprint()
与const char
不兼容
那么,有没有办法解决转换问题
还有,C/C++程序中使用popen()
的频率有多高
附言:
我不是一个专业的程序员,也不是计算机科学背景。我在逐步学习
同样,该代码与
popen()
完美结合。但是我对C语言中的文件处理很熟悉,所以我个人更喜欢fopen()
而不是popen()
。此外,我觉得在C中使用popen()
是没有意义的。也可以使用shell脚本进行pwm。暂时把char*
与const char*
的问题放在一边(因为char*
无论如何都可以传递给任何使用const char*
的函数)
您是否已检查fopen
的返回值是否为非空
请注意,使用r+
调用fopen
时,文件必须存在。否则,fopen
将返回NULL,生成segfault
由于文件仅被写入,未被读取,请考虑使用
fp = fopen(pwmi.period,"w");
如果一个文件不存在,它将创建一个新文件。您可以将
char*
传递给请求const char*
的参数,而无需显式转换,但无法执行相反的操作。标准的fopen()
不会接受const char
。我意识到了这一点。但是有没有一种从char*到const char*的转换方法呢?这是一种隐式转换<代码>字符*ptr;常量字符*cptr=ptr代码>工作正常。
fp = fopen(pwmi.period,"w");