How to Create Breathing LEDs
Overview
One of the simplest ways to dim LEDs is to use Pulse Width Modulation (PWM). With PWM, the duty cycle (on time) is modulated faster than the human eye can see to create the illusion of brightness. The breathing LED technique uses PWM to increase then decrease the brightness cyclically.
Verilog Code for “up_down_PWM” and “counter3” Module
input CLK, pulse;
output out0, out1, out2;
reg [2:0] count;
reg direction; // 1 = count down, 0 = count up
assign out0 = count[0];
assign out1 = count[1];
assign out2 = count[2];
// Direction Control
always @(posedge CLK) begin
if (count == 7)
direction <= 1;
else if (count == 0)
direction <= 0;
end
// Up-down Counter
always @(posedge CLK) begin
if (pulse == 1) begin
if (direction == 0)
count <= count + 1;
else
count <= count - 1;
end
end
endmodule
input CLK;
output out0, out1, out2;
reg [2:0] count;
assign out0 = count[0];
assign out1 = count[1];
assign out2 = count[2];
always @(posedge CLK) begin
count <= count + 1;
end
endmodule
Requirements
- CLB Peripheral w/hardware 2-bit timer
- Find a Part - Microcontroller and Processor Products page
Procedure
Create the necessary up_down_PWM and counter3 verilog files in the CLB tool. Refer to the Verilog Code for “up_down_PWM” and “counter3” module sections for the verilog code needed.
Implement the CLB Logic
Configure the CLB to implement the breathing LED logic. Refer to Figure 1 for guidance.
Select a Clock Source for the CLB
The clock source is important in this example as it is used to derive the frequency of the PWM and the speed of the breathing effect.
Clock settings:
- Clock Source: LFINTOSC
- Clock Divider: 32x
Configure the Look-Up Tables (LUTs)
Click on each LUT and look at properties.
At the bottom of the table, there is a text field for entering a hexadecimal number corresponding to the truth table:
- LSB Compare – 8CEF
- MSB Compare – 00B2
- Clock Pre-Scaler – 007F
Assign the CLB output to the pin where the LED is connected to produce the breathing effect.
Results
In the logic capture in Figure 3, the changing duty cycle is visible in the trace. To reduce the frequency of the breathing effect further, another counter is needed to pre-scale the clock source beyond 16x. If using an external signal or clock source, watch out for synchronization, as the source has to be slower than the base clock of the CLB, or the logic will not function correctly.
A demonstration highlighting the LED's breathing effect and dynamic duty cycle changes is available for reference: