Affordable and flexible platform to ease prototyping using a STM32F303K8T6 microcontroller.

Strange PWM problem

04 Sep 2019

I’m using the F303K8 to output 4x PWM waveforms, which are fed to 4x MOSFETS for dimming LED circuits.

I quite happily wrote some code to loop a fade through Red-Yel-Grn-Cyn-Blu-Mag and repeat, which works just fine…

RYGCBM code:

  1. include "mbed.h"

PwmOut redpwm(PA_8); PwmOut grnpwm(PA_9); PwmOut blupwm(PA_10); PwmOut whtpwm(PA_11);

int a; int b; float z=0.01;

int main() {

redpwm.period_us(1000); Set Red PWM period to 1ms grnpwm.period_us(1000); Set Green PWM period to 1ms blupwm.period_us(1000); Set Blue PWM period to 1ms whtpwm.period_us(1000); Set White PWM period to 1ms

z=0.05; Set wait value

whtpwm.pulsewidth_us(0);

while(1){

for(a=0; a<=1000; a++) { b=1000-a; blupwm.pulsewidth_us(b); redpwm.pulsewidth_us(a); wait(z); }

for(a=0; a<=1000; a++) { b=1000-a; redpwm.pulsewidth_us(b); grnpwm.pulsewidth_us(a); wait(z); }

for(a=0; a<=1000; a++) { b=1000-a; grnpwm.pulsewidth_us(b); blupwm.pulsewidth_us(a); wait(z); } } }

Then I decided to write a different bit of code to randomise a colour, hold it for a second, then fade to another random colour. I haven’t written the fade bit yet as I’ve discovered a very annoying problem. The red channel on PA_8 does not work when running this code, whereas it works just fine with the RYGCBM code above. I noticed the pins were floating a bit so have put pull-down resistors on each output but this hasn’t solved the problem – PA_8 is still dead while PA_9, PA_10 and PA_11 are fine.

Random colour code:

  1. include "mbed.h"

PwmOut redpwm(PA_8); PwmOut grnpwm(PA_9); PwmOut blupwm(PA_10); PwmOut whtpwm(PA_11);

int a; float z;

int redval; int bluval; int grnval; int whtval;

Serial pc(SERIAL_TX, SERIAL_RX);

int main() {

redpwm.period_us(1000); Set Red PWM period to 1ms grnpwm.period_us(1000); Set Green PWM period to 1ms blupwm.period_us(1000); Set Blue PWM period to 1ms whtpwm.period_us(1000); Set White PWM period to 1ms

z=1; Set wait value

while(1){

redval = rand()%1001; bluval = rand()%1001; grnval = rand()%1001; whtval = rand()%1001;

redpwm.pulsewidth_us(redval); grnpwm.pulsewidth_us(grnval); blupwm.pulsewidth_us(bluval); whtpwm.pulsewidth_us(whtval);

pc.printf("R%d G%d B%d W%d ",redval,grnval,bluval,whtval);

wait(z); } }

I put the pc.printf command in there to output the colour values to a hyperterminal, so I could check that was working OK – it is.

I have even changed the original code into the second bit of code, line by line, in an attempt to find the problem. In that instance, I found PA_8 stops working when I remove the for loops?!?!?! Very confusing! I've also tried moving the PWM from PA_8 to PA_12 and I still encounter the same problem.

Can anyone help? This is driving me nuts!!

04 Sep 2019

Not sure why the code formatting went all funny - Sorry about that!