Introduction
A potentiometer is a knob that provides a variable resistance. It can be used to read an analog input value from the user. In your everyday projects, you could use a potentiometer to change the brightness of a dimmer led or adjust the volume of an amplifier.
In this post, you’ll learn how to use a potentiometer with both Arduino and Raspberry PI boards with different programming languages. Keep in mind that, in a real project, you will use a specific board and a specific language depending on what is the project’s goal: do not be limited by your fear of exploring new hardware and software technologies.
Common Software Setup
To avoid repeating myself later on, let’s describe the different environments you’ll need to set up to get everything up and running.
Software Setup for Arduino
Arduino IDE is the best choice to program the Arduino board within its C-like language. If are skilled enough, you could also use the powerful command line interface Arduino CLI.
Please refer to the official Getting Started guide to install the IDE on the OS you prefer. Here below I’ll show you how to install it on Linux:
- Download the archive file from the download page
The archive name will be something like
arduino-[version]-[hardware-type].tar
.
At the time I’m writing this article, the file is namedarduino-1.8.16-linux64.tar
d - Extract the package using the File Explorer or by running this command:
# navigate to the right folder
cd Downloads
# tar -xf [archive-name].tar
tar -xf arduino-1.8.16-linux64.tar
The uncompressed archive will be called arduino-[version]
(in my case arduino-1.8.16
)
3. Run the installation script:
# navigate to the right folder
cd Downloads/arduino-1.8.16
# run the script with super user permissions
sudo ./install.sh
- Get the permission to read and write on the serial port:
When you upload a sketch (after you’re selected your board and the serial port), you could get an error likeError opening serial port
.
So solve this problem, open a Terminal and type:
# add the logged-in user to the 'dialout' group
sudo usermod -a -G dialout $USER
Please Note: You will need to log out and log in again for this change to take effect.
Software Setup for Python
One of the best environments for Python programming (and definitely my favorite) is PyCharm by JetBrains. However, PyCharm is not really suitable for running python scripts from the Raspberry Pi board, since it’s very resource-consuming.
Some light-weight IDEs are:
- Visual Studio Code which is also available for Raspberry PI by following this guide
- Thonny which is installed by default on Raspberry Pi OS
- Mu
Arduino
Hardware requirements & setup
- Arduino Uno board or any Arduino-like board
- Potentiometer (I use a 10k ohm)
- Hook-up wires of different colors
- Breadboard
The potentiometer has tree pin, those on the side are ground and 5V while the once in the middle is the analog input. Connect the potentiometer as shown below:
Code
C
The Arduino boards are usually programmed in the standard C-like language, whose files have the .ino
extension and must be placed inside a folder with the same name of the sketch.
Into the arduino website, you can find a very well-made language reference.
The code is shown below:
// select the input pin for the potentiometer
int sensorPin = A0;
// variable to store the value coming from the sensor
int sensorValue = 0;
void setup() {
// initialize the serial communication
Serial.begin(9600);
}
void loop() {
// read the value from the sensor
sensorValue = analogRead(sensorPin);
// print out the value on the Serial Monitor
Serial.println(sensorValue);
// wait for half a second
delay(500);
}
A similar example can be found at File
> Examples
> 03.Analog
> AnalogInput
.
Hit Ctrl
+ U
to upload the code. Open the Serial Monitor by hitting Ctrl
+ Shift
+ M
.
Python
The processor on the board can only process Arduino code, so you need to “translate” your Python code into C-like code. StandardFirmata
sketch will translate it for you and let you write the code in the language you prefer to.
First, you need to load StandardFirmata
inside the board to allow Python code to be executed.
From the Arduino IDE, let’s load StandardFirmata
sketch:
- Press on
File
Examples
Firmata
StandardFirmata
Hit Ctrl
+ U
to upload the code.
Open your favorite Python IDE and configure a virtual environment: it’s a common practice to have a requirements.txt
file in the root of the project to list all the needed packages. To avoid introducing too many topics, we will talk about it in another article.
Add the pyfirmata
library with the following line on the Terminal:
pip install pyfirmata
Create a new Python file called potentiometer.py
and copy the content below:
from pyfirmata import util, Arduino
import time
def potentiometer():
board = Arduino('/dev/ttyACM0')
it = util.Iterator(board)
it.start()
analog_input = board.get_pin('a:0:i')
while True:
analog_value = analog_input.read()
print(analog_value)
time.sleep(0.1)
if __name__ == '__main__':
potentiometer()
Please Note: a:0:i
stands for:
- analog
- pin
A0
- taken as input
Be aware of respecting tabs and spaces since Python is sometime a bit tricky!
To run the script, open a Terminal and type:
python _potentiometer.py
Raspberry PI
Raspberry Pi boards are ARM-based micro-computers. You can install almost any operating systems on them but the most popular is of course Raspberry Pi OS (which was once called Raspbian).
Hardware requirements & setup
In order to connect the potentiometer to the board, you first need to know the GPIO pin layout. Open a Terminal in your Raspberry board and run:
pinouts
However, the pin layout is shown in the image below:
The wiring diagram is quote simple since you only need to use a MCP3008 analog converter and other flew wires:
- pin 2 (or pin 4) to carry out the
5V
power - pin 6 for
Ground
(you can also use pins 9, 14, 20, 25, 30, 34, 39)
You must pay a lot of attention with the pin numbering: GPIO pins numbering is different from the physical numbering of the board pins.
Code
Python
Python is the default language with which you program on the Raspberry Pi board. You’ll use the GPIO Zero library, in particular the section 2.28 Potentiometer, to write the on below:
# raspberry-pi-potentiometer.py
from gpiozero import MCP3008
pot = MCP3008(channel=0)
while True:
print(pot.value)
Save the code in a file named raspberry-pi-potentiometer.py
. To run the code open a Terminal and type:
python raspberry-pi-_potentiometer.py
Conclusion
The act itself of getting the value from a potentiometer is not such an amazing project, but even the most complex IoT project of the world is made up by simple tasks like this. The aim of this tutorial is to start a journey of learning: you’re at the very beginning but don’t worry: everything starts from here!
Documentation
- Arduino
- Arduino Official Documentation
- pyFirmata - Python library to communicate with Arduino pins.
- Raspberry Pi
- Raspberry Pi Official Documentation
- GPIO Zero - Python library to communicate with RPI’s GPIO pins.
- onoff library - Node.js library to communicate with RPI’s GPIO pins.