10M+ Electronic Components In Stock
ISO Certified
Warranty Included
Fast Delivery
Hard-to-Find Parts?
We Source Them.
Request a Quote

Raspberry Pi PWM Explained: GPIO Control, Applications, and Troubleshooting

de juny 04 2026
Source: Michael Chen
Browse: 2387

Pulse Width Modulation (PWM) is one of the most important techniques used in Raspberry Pi electronics and automation projects. It allows digital GPIO pins to simulate analog-like control by adjusting signal timing instead of output voltage.

Figure 1. Raspberry Pi PWM

Raspberry Pi PWM Overview

Pulse Width Modulation (PWM) is a method that allows Raspberry Pi GPIO pins to control output power by rapidly switching a digital signal ON and OFF. Instead of creating a true analog voltage, PWM changes the amount of time the signal stays HIGH during each cycle. This ON-time percentage is called the duty cycle.

How PWM Works on Raspberry Pi

Figure 2. How PWM Works on Raspberry Pi

A PWM signal repeatedly switches a Raspberry Pi GPIO pin between HIGH and LOW states. The signal remains digital, but connected devices respond to the average effect of the switching.

Two main parameters control PWM operation:

PWM ParameterMeaning
FrequencyHow many times does the signal repeat per second
Duty CycleHow long the signal stays ON during each cycle

On Raspberry Pi GPIO pins, HIGH is approximately 3.3V. A 50% duty cycle means the signal stays HIGH half the time and LOW half the time. This can make an LED appear half-bright or reduce the average power delivered to a motor.

Duty cycle is calculated using:

Duty Cycle = ON Time / Total Period × 100%

Duty CycleSignal BehaviorPractical Effect
0%Always OFFNo output
25%ON for one-quarter of the cycleLow output
50%ON for half of the cycleMedium output
75%ON for three-quarters of the cycleHigh output
100%Always ONFull output

Increasing the duty cycle increases average output, while decreasing the duty cycle lowers it.

PWM frequency is the number of PWM cycles per second. It is measured in hertz (Hz).

Frequency is calculated using:

f=1/T

DeviceTypical PWM Frequency
LEDsHundreds of Hz or higher
DC MotorsHundreds of Hz to several kHz
ServosAround 50 Hz
Audio OutputMuch higher frequencies

The wrong frequency can cause flickering LEDs, noisy motors, unstable servos, or poor audio quality.

Hardware PWM vs Software PWM on Raspberry Pi

Figure 3. Hardware PWM vs Software PWM on Raspberry Pi

TopicHardware PWMSoftware PWM
DefinitionUses dedicated PWM hardware inside the Raspberry Pi processorUses software-controlled GPIO switching to create PWM pulses
Timing ControlControlled by hardwareControlled by software and the Linux operating system
Timing AccuracyHighModerate
Signal StabilityVery stable with less jitterCan jitter, especially under heavy CPU load
CPU UsageLow CPU usageHigher CPU usage
GPIO FlexibilityLimited to selected GPIO pinsCan work on many GPIO pins
Frequency ControlMore accurate and stableDepends on system load
Performance Under LoadMaintains a stable output better during background activityMay become unstable when Linux background tasks interrupt pulse timing
Best ApplicationsServos, motor drivers, fans, audio output, precision control systemsLED dimming, beginner projects, low-speed control, status indicators
Main AdvantageSmooth and accurate PWM outputEasy setup and more GPIO options
Main LimitationAvailable only on selected pinsLess accurate timing
Recommended UseUse when timing accuracy mattersUse for simple projects where small timing errors are acceptable

Raspberry Pi PWM GPIO Pins and Configuration

Figure 4. Raspberry Pi PWM GPIO Pins

GPIO Numbering and Hardware PWM Pins

Raspberry Pi uses multiple GPIO numbering systems. Most modern Python libraries use BCM numbering, while physical numbering refers to the actual pin locations on the header.

Numbering TypeMeaning
BCM NumberingBroadcom GPIO numbering is used internally
Physical Pin NumberingActual header pin positions
WiringPi NumberingOlder deprecated numbering system

Always verify GPIO numbering before wiring hardware.

Common Hardware PWM Pins

BCM GPIOPhysical PinPWM ChannelCommon Use
GPIO12Pin 32PWM0LEDs, motors, servos
GPIO13Pin 33PWM1LEDs, motors, servos
GPIO18Pin 12PWM0Audio, servos, motor control
GPIO19Pin 35PWM1Audio, servos, motor control

GPIO18 is commonly used because it supports hardware PWM and is widely supported in PWM tutorials and libraries.

PWM Libraries and Configuration

Common Raspberry Pi PWM Libraries

LibraryMain PurposeNotes
RPi.GPIOBasic GPIO and PWM controlBeginner-friendly
gpiozeroSimplified device controlHigh-level interface
pigpioPrecise timing and advanced PWMSupports DMA timing
lgpioModern GPIO controlLower-level access

Typical PWM Configuration Parameters

ParameterDescription
FrequencyPWM switching speed
Duty CyclePercentage of ON time
GPIO PinSelected PWM output pin
PWM ModeHardware PWM or software PWM

PWM Limitations and Wiring Safety

Raspberry Pi hardware PWM has several limitations that become important in robotics, motor control, audio systems, and industrial applications.

LimitationExplanation
Limited PWM channelsOnly a small number of hardware PWM outputs are available
Shared functionsSome GPIO pins share peripherals
Audio conflictsPWM may conflict with onboard audio
Pin restrictionsNot all GPIO pins support hardware PWM
Frequency sharingSome PWM channels share clock sources
DMA dependencyAdvanced PWM methods may use DMA resources

Many PWM problems are caused by wiring mistakes rather than software issues.

Wiring MistakeWhy It Matters
Mixing BCM and physical numberingControls the wrong GPIO pin
Connecting motors directly to GPIOMay damage Raspberry Pi
Missing common groundCauses unstable signals
Exceeding GPIO current limitsCan permanently damage the GPIO pins
Missing flyback diodeVoltage spikes may damage components
Wrong voltage connectionGPIO pins support only 3.3V logic
Loose jumper wiresCauses unstable PWM signals

Recommended Protection Components

ComponentPurpose
MOSFETSafely switches higher-current loads
H-Bridge DriverControls motor speed and direction
Flyback DiodeProtects against inductive voltage spikes
External Power SupplyPowers motors safely
OptocouplerProvides electrical isolation

Raspberry Pi PWM Applications

LED Dimming Systems

Figure 5. LED Dimming Systems

PWM is widely used in Raspberry Pi LED projects because it can control brightness without requiring a true analog output pin. By changing the duty cycle, LEDs can appear dimmer or brighter. This is useful for LED brightness control, RGB color mixing, decorative lighting, adaptive brightness systems, and status indicators. A high enough PWM frequency should be used to prevent visible flicker.

Motor Speed Control

Figure 6. Motor Speed Control

PWM is commonly used to control DC motor speed in robot wheels, pumps, fans, conveyor systems, and automation actuators. Instead of changing the supply voltage directly, PWM adjusts the average power delivered to the motor. Higher duty cycles generally increase motor speed, while lower duty cycles reduce it. External motor drivers are required because Raspberry Pi GPIO pins cannot safely drive motors directly.\

Servo Position Control

Figure 7. Servo Position Control

Servo motors use repeating control pulses where pulse width determines position in robotic arms, pan-tilt camera systems, RC vehicles, and automation systems. Small timing errors may cause shaking, buzzing, or unstable movement, so stable PWM timing is important for reliable servo control.

Audio Signal Generation

Figure 8. Audio Signal Generation

Raspberry Pi PWM can generate simple tones, alarms, buzzers, and basic audio signals by switching GPIO pins at audible frequencies. PWM is useful for simple embedded sound output, but it cannot fully replace a dedicated DAC for high-quality audio applications.

Industrial and IoT Applications

Figure 9. Industrial and IoT Applications

PWM is useful in Raspberry Pi industrial and IoT systems because it can control adjustable hardware outputs. Common applications include smart agriculture, environmental monitoring, HVAC systems, industrial automation, and IoT control systems. PWM frequently controls fans, pumps, valves, lighting systems, and actuators.

Raspberry Pi vs Arduino for PWM

Figure 10. Raspberry Pi vs Arduino for PWM

CategoryRaspberry PiArduino
Operating SystemRuns Linux OSRuns simple firmware
Processing PowerHigher processing power for advanced applicationsLower processing power but optimized for control tasks
PWM TimingLess predictable due to multitasking OSMore predictable real-time PWM behavior
LatencyModerate latencyLower latency with faster hardware response
Hardware ControlIndirect hardware access through OS and librariesDirect hardware access
PWM StabilityGood for general-purpose PWMBetter for stable motor control and control loops
NetworkingExcellent networking and IoT supportLimited networking without extra modules
MultitaskingCan run servers, scripts, databases, and multiple applicationsLimited multitasking capability
ProgrammingEasy high-level programming with PythonSimple low-level programming with Arduino IDE
Beginner ElectronicsGood for software-focused beginnersExcellent for electronics beginners
Smart AutomationExcellent for connected smart automation systemsGood for standalone automation
Real-Time Motor ControlModerate performanceExcellent performance
Precision TimingModerate timing accuracyExcellent timing accuracy
Best Use CasesIoT systems, smart automation, remote monitoring, Linux-based projectsMotors, servos, robotics, embedded control, real-time PWM
Main AdvantageCombines PWM with advanced software and networkingProvides precise and stable real-time PWM control

Raspberry Pi PWM Troubleshooting

ProblemPossible CauseRecommended Fix
Signal not workingWrong GPIO numberingCheck whether the code uses BCM, physical, or another numbering system.
Signal not workingIncorrect wiringRecheck GPIO connections, resistor placement, and shared ground.
Signal not workingUnsupported pinConfirm whether the selected pin supports hardware or software PWM.
Signal not workingLibrary or permission issueVerify the GPIO library installation, permissions, and setup commands.
Servo jitterWeak power supplyUse a separate power supply for the servo.
Servo jitterMissing common groundConnect the Raspberry Pi ground to the servo power supply ground.
Servo jitterSoftware PWM instabilityUse hardware PWM or a more stable library such as pigpio.
Servo jitterElectrical noiseShorten wires and improve power filtering or wiring layout.
LED flickeringFrequency too lowIncrease the PWM frequency until flicker is no longer visible.
LED flickeringPoor wiringCheck resistor values, loose connections, and wiring quality.
Motor noise or instabilityWeak power supplyUse an external motor power supply instead of powering the motor from GPIO.
Motor noise or instabilityMissing protection componentsUse a proper motor driver and add protection components such as a flyback diode when needed.
Motor noise or instabilityIncorrect frequencyAdjust the PWM frequency to suit the motor and driver circuit.
pigpio errorsDaemon not runningStart or restart the pigpio daemon.
pigpio errorsGPIO conflictsCheck whether another program is already using the same GPIO pin.

Frequently Asked Questions [FAQ]

Why is PWM important on Raspberry Pi even though GPIO pins are digital-only?

PWM allows Raspberry Pi GPIO pins to simulate analog-like control by rapidly switching signals between HIGH and LOW states. Instead of changing voltage directly, PWM changes the duty cycle to control average power delivery. This makes it possible to dim LEDs, adjust motor speed, control servo position, and manage fans using standard digital GPIO pins.

When should hardware PWM be used instead of software PWM on Raspberry Pi?

Hardware PWM is better for applications that require stable timing and accurate pulse generation, such as servos, motor drivers, audio output, and robotics. Because dedicated hardware controls the signal, it produces less jitter and uses fewer CPU resources. Software PWM is usually sufficient for simpler tasks like LED dimming or status indicators, where small timing errors are less noticeable.

Why can an incorrect PWM frequency cause problems in Raspberry Pi projects?

Different devices respond best to different PWM frequencies. If the frequency is too low, LEDs may visibly flicker, motors can produce noise or rough movement, and servos may become unstable. Very high frequencies may also reduce PWM resolution or increase processing demands. Choosing the correct frequency improves performance, smoothness, and reliability.

Why should motors and servos never connect directly to Raspberry Pi GPIO pins?

Raspberry Pi GPIO pins support only low-current 3.3V logic signals and cannot safely power motors or servos directly. High-current devices may damage GPIO pins, create voltage spikes, or cause unstable operation. External drivers, MOSFETs, H-bridge circuits, flyback diodes, and separate power supplies help protect the Raspberry Pi and improve PWM reliability.

Why is Arduino often better for precise PWM control than Raspberry Pi?

Arduino boards are designed for real-time hardware control and run simple firmware without a multitasking operating system. This allows more predictable PWM timing, lower latency, and better stability for motors, servos, and control loops. Raspberry Pi is stronger in networking, Linux applications, IoT systems, and smart automation, but Linux background activity can affect PWM timing accuracy.