LED: fade

Fade a LED using the PWM peripheral.

Next up, we’re going to do what PWM was actually designed for! Namely, quickly controlling an output so that the average output can be controlled precisely.

Most of it is similar to blinking an LED using the PWM peripheral, but fading needs a little bit more work:

		// Fade the LED in.
		for percentOn := 0; percentOn <= 100; percentOn++ {
			pwm.Set(ch, pwm.Top()*uint32(percentOn)/100)
			time.Sleep(time.Second / 100)
		}

Here we fade the LED in. This loop loops 101 times (from 0 to 100 inclusive), setting the output to a percentage of the input. The code pwm.Top()*uint32(percentOn)/100 is essentially the integer variant of the following formula:

$$\frac{T}{100} * P$$

Where \(T\) is the top value (pwm.Top()) and \(P\) is the percentage (percentOn).

Fading out is very similar. It’s almost identical, except it loops from 100 to 0 (inclusive):

		// Fade the LED out.
		for percentOn := 100; percentOn >= 0; percentOn-- {
			pwm.Set(ch, pwm.Top()*uint32(percentOn)/100)
			time.Sleep(time.Second / 100)
		}
Last modified May 1, 2025: Add PWM tour (af9cc3a)
Loading...

Note: these numbers are estimates, based on datasheets and measurements. They don't include everything and may be wrong.

Loading...