I wanted to create a programme that when you press button A the LEDs brightness increases and that when you press b decreseases.
I created the following code:
and I don’t understand what is wrong with it. Any ideas?
It may just be that changing by 20 at a time is too much. I re-created your code and it worked ok on a microbit v1.5, but I was only able to see about 3-4 levels of brightness. Here’s a variation that counts by 2. Try it and hold down B to watch it dim: https://makecode.microbit.org/_Rf1ikuC2p97V (or A to watch it get brighter).
I think brightness is controlled by “pulse width modulation” (PWM). Basically, PWM is blinking the power off and on really fast. If it’s on all the time, it’s maximum brightness. If it’s off all the time, it’s off (minimum brightness). If it’s off half the time and on half the time, it’s somewhere in between because it’s blinking really really fast and the light you see is averaged. Unfortunately this doesn’t mean the eye perceives it as 50% of maximum brightness. AllAboutCircuits.com has a discussion of the concept that may be worth looking at: https://forum.allaboutcircuits.com/threads/led-brightness-vs-pwm.83957/
Here’s a slightly different approach to diming that requires individual button presses: https://makecode.microbit.org/_TtF1XrDxzYAz . You’ll notice that you have to press “B” many times for it to get noticeably dimmer.
I hope that helps,
Thank you so much Bill. It works now.