Pulse-width modulation (PWM)
Pulse-width modulation fakes an analog level using only a digital pin that can be just on or off. The trick is speed and proportion: switch the pin on and off thousands of times per second, and vary the fraction of time it stays on — the duty cycle. At 25% duty cycle the pin is high one-quarter of the time, and a lamp or motor that can't react fast enough just feels the average, behaving as if it got a quarter of full voltage. It's like dimming a light by flicking it on and off faster than your eye can follow: spend more of each flicker 'on' and it looks brighter.
Because the switch is either fully on (no voltage drop) or fully off (no current), almost no power is wasted as heat — which is why PWM dims LEDs, controls motor speed, and regulates power supplies far more efficiently than a dimming resistor would. MCUs generate it almost for free using a hardware timer that counts up and compares against a threshold, so the CPU isn't busy toggling the pin. Choose the frequency to suit the load: a few hundred Hz for an LED (any faster is fine), ~20 kHz for a motor to push the switching whine above hearing. Smooth a PWM signal with an RC low-pass filter and you've built a cheap DAC.
Duty cycle and frequency are independent knobs and people mix them up. Duty cycle sets the average level (brightness, speed); frequency sets how fast the on/off cycle repeats — pick it high enough that the load and your ears can't follow the individual pulses.