You are on page 1of 14

Python for Raspberry Pi

Quickie in less than 5 minutes


Install Python and GPIO support library
• See if Python is already installed.
$ python –version
$ python3 –version
• On Debian derivatives such as Ubuntu, use apt.
$ sudo apt-get install python3
$ sudo apt-get update
$ sudo apt-get upgrade
• To use the GPIO pins on a Raspberry Pi we need the GPIO library.
$ sudo apt-get install rpi.gpio
IDLE
• Most Raspberry Pi OSes come pre-
installed with Python. If, not you can
install it.
• Once installed you can open the IDLE
from the Programming section in
Menu.
• Programming in IDLE.
Basic Python usage
• Hello World in python

• Indentation
Basic Python usage
Contd.
• Variables

• Comments: are ignored in the program but there for you to leave
notes, and are denoted by the hash # symbol. Multi-line comments
use triple quotes.
• Lists
Basic Python usage
Contd.
• Iteration

• Range

• Length
Basic Python usage
Contd.
• If statements
Basic Python usage
Contd.
• Python files have an extension of “.py”
• You can use default editor to
open/edit/save python files.
• You can use nano terminal editor
function to open/edit/save python files.
$ nano <filename>
Python (RPi.GPIO) API
• To use the GPIO pins on a Raspberry Pi we need the GPIO library.
$ sudo apt-get install rpi.gpio
• Import GPIO library to interface with the pins
import RPi.GPIO as GPIO
• Pin Numbering Declaration
• GPIO.setmode(<pin-numbering scheme>)
• GPIO.BOARD - Board numbering scheme
• GPIO.BCM - Broadcom chip-specific pin numbers
• Setting a Pin Mode
• GPIO. setup([pin], [GPIO.IN, GPIO.OUT])
Python (RPi.GPIO) API
Contd.
• Outputs
• Digital Output
• GPIO.output([pin], [GPIO.LOW, GPIO.HIGH])
• GPIO.output([pin], [0, 1])
• GPIO.output([pin], [FALSE, TRUE])
• Analog Output
• pwm = GPIO.PWM([pin], [frequency]) – initializing the pin
• pwm.start([duty cycle]) – set initial value
• pwm.ChangeDutyCycle([duty cycle]) – to change duty cycle
• pwm.stop() – stop the PWM
• Inputs
• GPIO.input([pin])
Python (RPi.GPIO) API
Contd.
• Additionals
gpio readall
Python (Paho-MQTT) API
• Establishing Connection
import paho.mqtt.client as mqtt
broker_address = “<hostname/ipaddress>"
broker_portno = 1883
client = mqtt.Client()
client.connect(broker_address, broker_portno)
• Publishing a Message
client.publish(topic, payload = None, qos = 0, retain = False)
• Subscribing to Topics
client.subscibe(topic, qos = 0)
Python (Paho-MQTT) API
Contd.
• The Loop Functions
client.loop_forever()
client.loop_start()/client.loop_stop()
Client.loop()
• Callbacks
on_connect
on_disconnect
on_message
on_publish
on_subscribe()/on_unsubscribe()
References
• https://www.raspberrypi.org/documentation/usage/python/
• https://www.raspberrypi.org/documentation/usage/gpio/python/RE
ADME.md
• https://gpiozero.readthedocs.io/en/stable/
• https://learn.sparkfun.com/tutorials/raspberry-gpio/python-rpigpio-
api

You might also like