1

我正在同时启用多个 PWM,我不想复制粘贴代码 6 次,但我无法启用 6 个不同的 PWM,有效的代码是:

    void pwmPinChoices(void){

    pwm_channel_disable(PWM, PWM_CHANNEL_7);
    pwm_pin6_instance.ul_prescaler = PWM_CMR_CPRE_CLKA;
    pwm_pin6_instance.ul_period = 100;
    pwm_pin6_instance.ul_duty = 50;
    pwm_pin6_instance.channel = PWM_CHANNEL_7;
    pwm_channel_init(PWM, &pwm_pin6_instance);
    pio_set_peripheral(PIOC, PIO_PERIPH_B, PIO_PC24B_PWML7);
    pwm_channel_enable(PWM, PWM_CHANNEL_7);
}

我希望能够更改 pwm_pinx_instance 和 pwm_channel_x,我尝试使用数组但它不起作用..

我试过的代码是:

    void pwmChoices(void){
    char ChlArr = [0, 1, 4, 5, 6, 7];
    char PinArr = [34, 36, 6, 7, 8, 9];

    for(int i = 0; i < 6; i++){
    pwm_channel_disable(PWM, PWM_CHANNEL_ChlArr[i]);
    pwm_PinArr[i]_instance.ul_prescaler = PWM_CMR_CPRE_CLKA;
    pwm_PinArr[i]_instance.ul_period = 100;
    pwm_PinArr[i]_instance.ul_duty = 50;
    pwm_PinArr[i]_instance.channel = PWM_CHANNEL_ChlArr[i];
    pwm_channel_init(PWM, &pwm_PinArr[i]_instance);
    pio_set_peripheral(PIOC, PIO_PERIPH_B, PIO_PC24B_PWMLChlArr[i]);
    pwm_channel_enable(PWM, PWM_CHANNEL_ChlArr[i]);
}

但是使用这段代码我得到了很多函数未声明的错误..

4

2 回答 2

1

如果你的函数看起来像这样

void pwm_pin6_instance ( void )

然后你可以声明一个数组

void (*pwm_PinArr_instance[7]) (void);

并初始化它:(和号是可选的)

pwm_PinArr_instance[0] = &pwm_pin0_instance;
pwm_PinArr_instance[1] = &pwm_pin1_instance;
pwm_PinArr_instance[2] = &pwm_pin2_instance;
pwm_PinArr_instance[3] = &pwm_pin3_instance;
pwm_PinArr_instance[4] = &pwm_pin4_instance;
pwm_PinArr_instance[5] = &pwm_pin5_instance;
pwm_PinArr_instance[6] = &pwm_pin6_instance;

然后你可以使用数组

 pwm_channel_init(PWM, pwm_PinArr_instance[i]);

编辑

深入研究您的代码,我认为您必须了解有关数组的一些知识。我猜你在想PWM_CHANNEL_ChlArr[i]will 的翻译是, for i=0, PWM_CHANNEL_0.

数组值在编译时不能替代变量名。

花时间研究数组并学习如何使用它们。

于 2015-05-13T12:41:00.697 回答
1

它是

char ChlArr[] = {0, 1, 4, 5, 6, 7}
char PinArr[] = {34, 36, 6, 7, 8, 9};

并不是

char ChlArr = [0, 1, 4, 5, 6, 7];
char PinArr = [34, 36, 6, 7, 8, 9];
于 2015-05-13T12:42:17.183 回答