Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

PWM is a form of signal modulation that allows digital output to approximate an analog signal. Use this for questions about using the PWM pins (marked with ~).

A Pulse Width Modulation (PWM) signal is a series of digital pulses. Each pulse makes the signal go high (on) for a short period, and it then drops back to low (off) for a short period before the next pulse. The result can be referred to as a square or rectangular wave, because of its appearance if it is graphed as voltage over time.

There are two important attributes which describe a PWM signal. Firstly, the frequency determines how often the pulses happen. Frequency is expressed in Hertz (Hz), which is the number of pulses per second. PWM signals generated by the Arduino usually have a frequency of 490 Hz (or 980 Hz in some cases).

The second attribute of a PWM signal is the duty cycle. For human-readable purposes, it is often expressed as a percentage. This determines how long a pulse lasts compared to the space between pulses. For example, a pulse could last 5 milliseconds, and be followed by a 15 millisecond gap before the next pulse. This is a 25% duty cycle, because the pulse is high for a quarter of the total time. A 10ms pulse followed by a 10ms gap would be a 50% duty cycle, and so on.

PWM is very useful for controlling the speed of a DC motor. Raising or lowing the duty cycle will cause the motor to speed up or slow down. A conventional analog approach to motor control would raise or lower the voltage instead, which can result in poorer performance.

Similarly, a PWM signal can effectively control the brightness of an LED. Raising and lowering the duty cycle will increase and decrease the apparent brightness of the light.

The most common way to produce a PWM signal on the Arduino is using the analogWrite() function. The frequency is fixed, but it allows specification of the duty cycle in the range 0 to 255 (where 255 represents 100%).

The tone() function also allows a PWM output to be generated. It has a fixed 50% duty cycle, but allows specification of the frequency in Hz. It is primarily intended for generating simple sounds on a speaker, but could be used for other purposes as well.

history | excerpt history