A Pulse Width Modulation (PWM) signal is basically a square wave which is switched between on (high) and off (low) state. The duty cycle and frequency of a PWM signal are used to determine the behavior of what the PWM signal is controlling
The Duty Cycle of the PWM signal refers to the ratio of the time that the signal is in a high (on) state over the total time it takes to complete one cycle. It is commonly expressed as a percentage or a ratio.
A 50% duty cycle means that the high state takes half of the time and the low state takes the other half of the time. This is the same as an ideal square wave. If this ratio is greater than 50%, the logic high signal takes up more time in the cycle than logic low, and vice versa. Thus, a 100% duty cycle means the signal is always on (full-scale), and the 0% duty cycle means the signal is always off(grounding).
PWM can be easily implemented in various ways on Arduino. The Seeeduino board is a good learning and evaluation board. It is an Arduino-compatible board, which is based on ATmega328P MCU
On this board, there are 6 pins(i.e. pin 3, 5, 6, 9, 10, 11) which can output a PWM wave with analogWrite() function. Calling the analogWrite() function allows a stable square wave with a specified duty cycle to be generated on the PWM pins. Generally, the frequency of these pins are about 490Hz, and the pin 5 and 6 of Seeeduino or its similar boards have the frequency of 980Hz.
The output voltage from Arduino pins are 5V, and different duty cycles output different voltage levels as stated below:
Duty Cycle | Output Voltage Levels |
---|---|
0% | 0V |
25% | 1.25V |
50% | 2.5V |
75% | 3.75V |
100% | 5V |
An Example - Adjust the Brightness of LED
To control the brightness of an LED with Arduino with the PWM technique as an example.
Hardware Connection
Software
analogWrite() Function Syntax:
analogWrite ( pin , value ) ;
The value representing the duty cycle, and the number is between 0(off) and 255(on).
int ledPin = 9; // LED connected to digital pin 9
void setup() {
pinMode(ledPin, OUTPUT); // sets the pin as output
}
void loop() {
analogWrite(ledPin, 255); //set duty cycle to always on
}
You can change ‘255’ to any number between 0~255 for different outputs, or you can modify the code to change the value continuously.