pxt-microbit
pxt-microbit copied to clipboard
Default PWM frequency is very low, resulting flickering and noisy motor control
Describe the bug The default PWM frequency on the pin outputs is very low, resulting flickering and noisy motor operation when using analog write.
To Reproduce In makecode: basic.forever(function () { pins.analogWritePin(AnalogPin.P0, 300) })
Expected behavior Led flickering can be seen with the bare eye. You can also see it as a "trail" when the led moves.
When using motor control via a FET transistor, the operation will become very noisy. Video: https://youtu.be/Fer2_VP-BQo
micro:bit version (please complete the following information): V1 and V2
Additional context Why not make default PWM 200 instead of 20000?
I have tested the following code with a cheap servo to see if the servo will get affected after changing the pwm frequency, and the servo still works like before.
pins.analogWritePin(AnalogPin.P1, 0) pins.analogSetPeriod(AnalogPin.P1, 200) basic.forever(function () { pins.servoWritePin(AnalogPin.P1, 45) basic.pause(1000) pins.servoWritePin(AnalogPin.P1, 135) basic.pause(1000) })
@carlosperate any thoughts in this bug? Should we change the default for this?
@carlosperate ?
The 20ms period was likely picked to match the period of servos by default.
The servo functions does set the period to 20ms as well, so code like this pins.analogSetPeriod(AnalogPin.P1, 200); pins.servoWritePin(AnalogPin.P1, 45) would have changed the period to 20 ms automatically inside servoWritePin().
My concern to change the default period would be that perhaps some projects or extensions might be depending on that period being the default in their PWM output. For finer motor control the period can always be set to something smaller, either by an extension or provided instructions.
@gomakekit I assume the main advantage of changing the default might be to have smaller programmes for the user? Or is there any other reason this might be useful? Does it clash with other analog write functionality?
So the reason we are so found of analog write is that instead of making a library for each product, is that user can simply use the analog write to control the motor speed or led brightness in one block (typically bubble machine motor speed). However the set period isnt that easy to grasp, also there is the drawback having to make an analog write before you can set the period, hard to explain to users. We (MakeKit) are teaching the universal function of analog write instead of "hovercraft speed" or similar. The only possible drawback for a pwm frequency is limited to transistor timing and recovery. I have found that the cheapest low power (fet) transistors can handle at least 1 mhz, typically much more. With a timing of 200 microseconds, we are only at 5000 hz, so we are on the safe side. Another way of looking at this is that old led dimmers flicker, while the new ones don't. Please consider changing the default period. Thanks!