PyRaspBeta

← All practice problems

Raspberry Pi practice problem · LEDs & PWM

Sawtooth

MediumBudget $2Python · gpiozero

A breathing light goes up and down. A sawtooth only climbs, then drops straight back.

Using RPi.GPIO, run PWM at 500 Hz on GPIO18 (LED on that pin). Every second, the duty rises evenly from 0 % to 100 % and then jumps back to 0 % exactly on the second (at 1 s, 2 s, … 4 s).

The test checks the frequency, about 25 % at 0.25 s, 50 % at 0.5 s and 2.5 s, 75 % at 0.75 s, above 85 % just before 1 s and 4 s, and below 10 % just after them.

Watch out for drift: every pass through a loop costs a little time on top of its sleep(), so a loop of fixed sleeps slowly falls behind the clock. Work out the duty from the elapsed time instead: t = time.monotonic() - start, then the duty is (t % 1) * 100.

More in LEDs & PWM