We use potentiometer in our daily life such as controlling fan speed, controlling volume of radio, controlling brightness of light etc. concept is same in every application. In potentiometer there is adjustable knob, by adjusting that knob we are changing resistance and hence change in current. In this tutorial we are going to use potentiometer with raspberry pi.
For doing this project you will need,
- Raspberry pi 4,
- Dual Fan Heat Sink aluminium Armor Case. (Optional)
- Potentiometer 10K or 5K,
- 220 ohms Resistor,
- Jumper Wire.
Reading Analog signals with Raspberry Pi:
Raspberry pi GPIOs can only read digital signal, either HIGH (3.3V) or LOW (0V). It can’t give values in between for example 1V, 1.5V, 2V etc. so we need to covert analog signal into digital with analog to digital converter chip (MCP3008). Then creating imitation analog signal using plus width modulation (PWM).
Analog to Digital Converter (ADC) MCP3008:
This chip has 16 pins, 8 pins are for analog inputs, where we can connect analog device and 8 pins are for raspberry pi GPIOs. When connecting wires to GPIOs and power supply make sure which side is for what. Look for half circle on chip.
Writing the Script:
make sure you enable SPI.
For enabling this go to MENU > Preferences > Raspberry pi configuration > Enable SPI
1) Control brightness of LED.
2) Take potentiometer values via MCP3008 and give to PWM GPIO to control LED.
Circuit for controlling Brightness of LED with Raspberry Pi 4:
Python Script for Controlling Brightness of LED:
from gpiozero import PWMLED, MCP3008 from time import sleep pot = MCP3008(0) led = PWMLED(17) while True: if (pot.value < 0.002): led.value = 0 else: led.value = pot.value print(pot.value) sleep(0.1)
First we will import PWMLED and MCP3008 from gpiozero library. We are using analog to digital converter chip MCP3008 and controlling LED with plus width modulation (PWM).
from gpiozero import PWMLED, MCP3008
Now we are importing sleep from time. We are importing this because whenever we want to pause or hold process for particular amount of time, we can use this.
from time import sleep
creating an object called pot that refer to MCP3008 channel 0, i.e Pin 1 in MCP3008
pot = MCP3008(0)
Creating a PWMLED object called led that refer to GPIO 17.
led = PWMLED(17)
Script will run in loop forever.
pot.value will access the current reading of potentiometer, if it is less than 0.002 it will turn OFF LED. You can change this value much lower. But some manufacturing defects or electrical defects are also there, which can’t let it completely zero.
if (pot.value < 0.002): led.value = 0
else it will change brightness of LED according to potentiometer value.
else: led.value = pot.value
Print the potentiometer value in every 0.1 seconds.
I hope you enjoyed my tutorial.
Till then keep learning keep making.