void pwmout_init(pwmout_t* obj, PinName pin) { uint32_t peripheral; u32 pwm_idx; u32 pin_sel; // Get the peripheral name from the pin and assign it to the object peripheral = pinmap_peripheral(pin, PinMap_PWM); if ( peripheral == NC ) { return; } pwm_idx = RTL_GET_PERI_IDX(peripheral); pin_sel = RTL_GET_PERI_SEL(peripheral); obj->pwm_idx = pwm_idx; obj->pin_sel = pin_sel; obj->period = 0; obj->pulse = 0; HAL_Pwm_Init(pwm_idx, pin_sel); obj->period = 20000; HAL_Pwm_SetDuty(obj->pwm_idx, obj->period, obj->pulse); HAL_Pwm_Enable(pwm_idx); }
void pwmout_write(pwmout_t* obj, float value) { if (value < (float)0.0) { value = 0.0; } else if (value > (float)1.0) { value = 1.0; } obj->pulse = (uint32_t)((float)obj->period * value); HAL_Pwm_SetDuty(&obj->pwm_hal_adp, obj->period, obj->pulse); }
// Right now, PWM output only works on the pins with // hardware support. These are defined in the appropriate // pins_*.c file. For the rest of the pins, we default // to digital output. void analogWrite(uint32_t ulPin, uint32_t ulValue) { pwmout_t *pObj; if ( ulPin < 0 || ulPin > 13 ) return; /* Handle */ if ( g_APinDescription[ulPin].ulPinType != PIO_PWM ) { pwmout_init(&pwm_pins[ulPin], g_APinDescription[ulPin].pinname); g_APinDescription[ulPin].ulPinType = PIO_PWM; } pObj = &pwm_pins[ulPin]; pObj->pulse = pObj->period * ulValue / 256; HAL_Pwm_SetDuty(pObj->pwm_idx, pObj->period, pObj->pulse); }