#include #define pin PA8 #define maxSamples 1 #define PWM_OVERFLOW 18000 char sinetable [32]; uint16_t buffer[maxSamples]; uint8_t count = 0; uint8_t pins = 7; void isr(void); uint8_t sine_wave[16] = { 0x80,0xb0,0xda,0xf5,0xff,0xf5,0xda,0xb0, 0x80,0x4f,0x25,0x0a,0x00,0x0a,0x25,0x4f }; // Automatically retrieve TIM instance and channel associated to pin // This is used to be compatible with all STM32 series automatically. TIM_TypeDef *Instance = (TIM_TypeDef *)pinmap_peripheral(digitalPinToPinName(pin), PinMap_PWM); uint32_t channel = STM_PIN_CHANNEL(pinmap_function(digitalPinToPinName(pin), PinMap_PWM)); // Instantiate HardwareTimer object. Thanks to 'new' instantiation, HardwareTimer is not destructed when setup() function is finished. HardwareTimer *MyTim = new HardwareTimer(Instance); void setup() { MyTim->pause(); MyTim->setPrescaleFactor(1); // Timer PreScale Factor 1 MyTim->setOverflow(PWM_OVERFLOW); // 72000000 / PWM OVERFLOW = 40Khz MyTim->setMode(4, TIMER_OUTPUT_COMPARE); MyTim->setCaptureCompare(4, PWM_OVERFLOW); MyTim->attachInterrupt(4, isr); // Configure and start PWM MyTim->refresh(); MyTim->resume(); MyTim->setPWM(channel, pin, 4000, 50); pinMode(PC13, OUTPUT); // LED out pinMode(PA9, OUTPUT); // LED out digitalWrite(PA9, HIGH); } void loop() { /* Nothing to do all is done by hardware. Even no interrupt required. */ digitalWrite(PC13, HIGH); delay(1000); digitalWrite(PC13, LOW); delay(1000); } void isr(void) { // convert frequency to Pulse Width Modulation Duty Cycle Using DMA // center on PWM_OVERFLOW //uint16_t pDuty = (uint16_t)map(buffer[0],0,4095,0,PWM_OVERFLOW/2-1); //pwmWrite(PWM_OUT,PWM_OVERFLOW/2+pDuty); // alternate modulation #2 - louder but worse quality //uint16_t pDuty = (uint16_t)map(buffer[0],0,4095,0,PWM_OVERFLOW); //pwmWrite(PWM_OUT,pDuty-1); // alternate #3 //pwmWrite(PWM_OUT,(((PWM_OVERFLOW-2) * buffer[0]/4096))+1); // sine wave test int16_t pDuty = sine_wave[count++]*100/128; MyTim->pause(); MyTim->setPWM(channel, pin, 4000, pDuty); MyTim->refresh(); MyTim->resume(); if(count >= 15) count = 0; }