I'm trying to run PWM at 2kHz on Arduino Due pin 21.
It's PB13, PWMH1 (Channel 1) on SAM3x8e.
The sketch below contains the PWM configuration.
#define FWD 3
#define REV 4
#define CPRD_Value 42000 // PWM frequency 84Mhz/2kHz = 42000
void setup() {
pinMode(FWD, OUTPUT);
pinMode(REV, OUTPUT);
PMC->PMC_PCER1 |= PMC_PCER1_PID36; // Enable PWM on PMC
REG_PIOB_ABSR |= PIO_ABSR_P13; // Set PWM pin perhipheral type
REG_PIOB_PDR |= PIO_PDR_P13; // Set PWM pin to an output (disable PIO and enable perhipheral control)
REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1); // Set the PWM clock rate to 84MHz (84MHz/1)
REG_PWM_CMR1 = PWM_CMR_CPRE_CLKA; // The period is lef aligned and set clock source as CLKA
REG_PWM_CPRD1 = CPRD_Value; // Set PWM frequency 84Mhz/2kHz = 42000
REG_PWM_CDTY1 = 0; // Defines the waveform duty-cycle. 0%.
// This value must be defined between 0 and CPRD (PWM_CPRx)
// x%= (CDTY/ CPRD) * 100 %
REG_PWM_ENA = PWM_ENA_CHID1; // Enable the PWM channel
}
void loop() {
// Turn on motor for 300ms
digitalWrite(FWD,LOW);
digitalWrite(REV,LOW);
digitalWrite(REV,HIGH);
REG_PWM_CDTYUPD1 = 0; // duty cycle = 0%, the engine should not start
delay(300);
// Turn off motor
digitalWrite(FWD,LOW);
digitalWrite(REV,LOW);
REG_PWM_CDTYUPD1 = 0;
while(true){
delay(100);
}
}
I use REG_PWM_CDTYUPD1 = 0; to update duty cycle, but no matter what value I use in the register, PWM always starts the motor at full speed.
I've already consulted the datasheet and other topics, but I can't see the error. The code looks right.
Do you have any idea what it might be? maybe I should try another PWM channel?