Controlling the brightness of an LED or blinking it continually by passing various delays with PWM(Pulse Width Modulation) it might be your first Raspberry Pi 4 learning experience. In this article, we perform three activities which are
- Turning On & Off LED.
- Blinking it using PWM at different frequencies.
- Controlling the brightness of the LED.
- Raspberry Pi 4 controller.
- And other connecting wires such as (Ethernet Cable, HDMI Cable, & Powering cable for both Raspberry Pi and Monitor, etc.)
- LED of any color.
- Jumper Wire.
- Resistor 100 Ohm.
Now we will proceed further with our first activity i.e. Turning On & Off LED.
Circuit Connection for controlling the brightness of LED using Raspberry pi:
The circuit diagram remains the same for all 3 activities there is no change in the circuit diagram only we have to change the code for all activities to blink it and to control its brightness from 0 to 100 by applying PWM signal via Board pin 11(in raspberry pi there are two different types of pin numbering available, you can use anyone out of these two there is a slight change in the code by which you can switch these pin numbering configuration). The 2 pin configurations are GPIO pin configuration and the second one is Board Pin configuration. further, I’ll tell you what is the change required in the code to switch between available pin configurations.
As you can see that in the above figure the positive terminal of LED is connected to the board pin 11 and on which we will apply 5V to turn ON&OFF LED. Now we have done with the circuit diagram, now think! how to power the LED with raspberry pi? to answer this let us move to the coding part.
Code to turn On & Off:
import RPi.GPIO as GPIO //Importing GPIO library as object GPIO
GPIO.setmode(GPIO.Board) //If you are using board pin numbering ||or||
GPIO.setmode(GPIO.BCM) //If you are using GPIO pin numbering you can use either one
GPIO.setup(11, GPIO.OUT) //Board pin 11 set as output pin.
GPIO.output(11, True) //To turn on LED pin 11 supplied with logic 1 and by switching this you can turn on and off LED.
Code to blink LED:
import RPi.GPIO as GPIO
import time //Imported time library
Code for controlling the brightness of LED using Raspberry pi:
import RPI.GPIO as GPIO
p = GPIO.PWM(11, 100) //11 is pin number and 100 is max range of PWM.
p.start(0) //Starting point of PWM signal you can select any value between 0 to 100.
for x in range (0, 100, 1): //Increasing brightness of LED from 0 to 100
for x in range (100, 0, -1): //fading brightness of LED from 100 to 0
To download the code click on the link.