GPIO Python Guide

Posted on January 13, 2024


Required Software

First install the required Python software. If running DietPi then it's recommended to follow the steps in the video using the GUI. Alternatively you can install the software with these commands:

sudo apt update

sudo apt install python3-dev python3-venv python3-pip

sudo apt install python3-RPi.GPIO

Next you'll need to give your user permission to access the GPIO.

sudo adduser $LOGNAME gpio

Now reboot before continuing.

sudo reboot

Test Code

This simple program will toggle an output pin on and off. Create a new file and name it test.py:

nano test.py

Now copy and paste the following code:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)

while True:
    GPIO.output(8, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(8, GPIO.LOW)
    time.sleep(1)

Press ctrl-x to exit and select yes to save the file. Now run the program:

python3 test.py

This will output a signal on pin 8 and will turn on and off every second. Press ctrl-c to exit the program. If you're interested in learning how to design circuits to control components such as lights and motors, see my video series titled Practical Electronics 101: Practical Electronics & Circuits 101 – Intro to Transistors

More info about this GPIO library along with examples and documentation can be found here: raspberry-gpio-python Wiki

Remote GPIO

The Raspberry Pi's GPIO pins can also be controlled by remote computers connected to your network. The steps covered in the video guide can be found here: Configuring Remote GPIO

Pinout


Conclusion

Stay tuned for DIY projects which utilize the steps covered today. I'll also be showing how to set pins as inputs in future projects.



Have a question or business inquiry? Get in touch!