Python + Raspberry Pi Tutorial

This is a condensed tutorial for the Raspberry Pi material taught in the Robotics Club. It’s recommended to read the first Python tutorial before reading this one.

Intro to the Raspberry Pi

Python + Raspberry Pi Tutorial

The Raspberry Pi is a miniature computer that is compatible with many devices, such as mouses, televisions, and keyboards. Despite its small size, the Pi is able to replicate many of the things a desktop computer can do, such as browsing the internet, running programs, and interacting with hardware.

The Raspberry Pi’s compact size makes it incredibly mobile. Combined with its myriad of capabilities, this makes it a very flexible asset to have for computer engineers. For our purposes, the Raspberry Pi can read our Python code, and then use it to move physical parts attached to the board such as motors.

To use the Pi, we will also be using a breadboard. The breadboard is the primary place you will be building circuits. The horizontal and vertical rows of the breadboard, as shown below, carry electricity through thin metal connectors under the plastic with holes. Below is a diagram describing how the breadboard works:

Python + Raspberry Pi Tutorial

Connecting the Pi to the Computer

To connect your Pi to a computer, you will first need the Pi’s IP address. Once you have it, type ssh [email protected][ip address]. If it asks you if you want to continue, answer yes. It should ask you for a password – the default password is raspberry. Once you do all of that, the Pi should be connected.

First Project: Blinking an LED

The first thing this tutorial will go over is how to program an LED blinking. The first thing to do is wire up the circuit needed for this.

A Raspberry Pi has many pins along one side, which should be labeled on the Pi’s instruction manual. Some are GPIO (general purpose input-output) pins used for inputs and outputs, some supply power, and some are ground pins. Remember that a complete circuit must be closed, so it must have one end connected to power and another connected to ground somehow.

An LED has two pins, and one should be shorter than the other. The longer one is called a cathode, and is the negative electrode of the LED. The other is the anode, or positive terminal. The LED can be plugged in anywhere on the board.

A wire from one of the Pi’s GPIO pins should be connected to the LED’s cathode, and a resistor should be connected from the anode to the ground rail on the breadboard. A wire should also be connected from the resistor to a ground pin on the Pi in order to complete the circuit.

As for the code itself, the first thing that must be done is to initialize a few things.

  • The LED must be “imported” from the gpiozero library. To do this, we put from gpiozero import LED at the top of the code. This effectively tells the code that we will be using an LED. Many of the devices used in this tutorial must be imported from the gpiozero library, which means you can usually just substitute LED for the name of the device.
  • Then, we have to add from time import sleep. This imports the sleep function, which tells other functions how long to run for. This is extremely important – chances are that almost all programs you build using Python and the Pi together will need it.
  • Finally, we have to initialize the LED. Come up with a name for the LED – simply “led” works fine for this case, but if you’re using multiple LEDs, you need a different name for each one. Then, type “[ledName] = LED(pin #)” at the top of the code to initialize the LED, where ledName is the name you want to call the LED.

In the code itself, we use the functions [ledName] .on and [ledName].off to operate the LED. These commands turn the LED on and off, respectively. After turning it on or off, remember to put a sleep command under it – this tells it how long to stay on or off for. The sleep command is written as sleep(time), where time is the number of seconds you want it to last.

Remember: if you want the code to keep running, you need to put it inside of a forever loop. If you don’t remember how to do that, you type while True: into Nano, put all of the code you want repeated under it, and indent said code to make it “inside” the while block.

Making Functions

Functions are used to organize chunks of code that do a specific task. That block of code only runs when the function is called. Functions are great because they minimize code repetition and help organize your program. Functions can use parameters, variables that can be passed into them and used, and they can also return values.

Below is a code used to declare a sample function.

def my_function(a,b):       #function declaration – a and b are parameters

   print(‘This is my function’)      #this is what the function does

   z = a + b

   return z      #value to be returned by the function

number = my_function(age, height)       #how you would call the function

Using a Button as an Input

A button is connected to the Raspberry Pi very similarly to an LED – with one pin connected to a GPIO pin and the other to ground. However, unlike an LED, it doesn’t matter which pin on the button goes where.

You’ll also need to import the button – just type from gpiozero import Button at the top of the code. You’ll also have to give the button a name and tell the Pi which pin it’s plugged into using an initialization statement. It’s effectively the same as the one for an LED – but substitute the word “LED” for “Button”.

Buttons are generally used with if/else statements. In order to check if a button is pressed, you’ll use “buttonName.is_pressed” as the condition for the if statement.

Ultrasonic Sensor

Ultrasonic sensors use sound waves to sense the distance from whatever it’s pointed at. It’s name when importing it from the gpiozero library is DistanceSensor.

When attaching the ultrasonic sensor to the breadboard, you’ll notice that there are four labelled pins. The pins should be connected as follows:

  • VCC to a 5V power pin
  • Trig to a GPIO pin
  • Echo to a different GPIO pin
  • GND to a ground pin

Unlike most sensors, the ultrasonic sensor needs to be connected to two GPIO pins rather than one. So, when you initialize the sensor, you need to input both pin numbers (eg. sensorName = DistanceSensor(pin1, pin2)).

In the code, [sensorName].distance gets the distance reading of the sensor in meters – so if you want it to be in cm, you’ll have to multiply it by 100. For example, a variable can be declared to store the cm value: this would be written as  distance = [sensorName].distance * 100.

Once you have a distance value, you can start using it in if/else statements and the like. The easiest application of it would be something like “if distance > x, then do y, otherwise do 

Buzzers

A buzzer is a device that makes sound – its name in the gpiozero library is simply Buzzer. The usage of the buzzer – down to the functions used to operate it – is exactly the same as the LED, so just revisit the section on how to operate an LED if you need help.

Light Sensors

Light sensors detect the local light level and output a signal if the light level is greater than a certain threshold. However, the one used for this tutorial is called a Light Dependent Resistor, or LDR for short. These don’t actually sense light in a conventional way – it will put up more resistance to electricity the darker its surroundings are. Its name in the gpiozero library is LightSensor.

However, the LDR can’t do a whole lot by itself. To get it working, we need to use a capacitor, which temporarily stores electric charge.  If it’s connected to the LDR, it will charge faster if the resistor puts up less resistance (eg. if it’s bright), and vice versa. This lets us measure the light intensity by using the time it takes for the capacitor to fully charge.

An example of how these can be used is for a night light. For that you’ll need to build this schematic:

Python + Raspberry Pi Tutorial

The LDR will give a true or false value – if it senses light, its value will be true, and vice versa. To make your night light work, you’ll need to make an if/else statement using the LDR’s readings.

The LDR and Analog Input

While the LDR generally provides digital values (true or false) when used this way, we can make it give us analog values instead. By making it give us specific numbers instead of just true or false, we can make more precise programs.

To achieve this, we have to use this code:

import RPi.GPIO as GPIO
from time import sleep 
GPIO.setmode(GPIO.BOARD) 
ldr = 7 

def rc_time (ldr):

    count = 0
    GPIO.setup(ldr, GPIO.OUT)
    GPIO.output(ldr, False)
    sleep(0.1)
    GPIO.setup(ldr, GPIO.IN)
    while (GPIO.input(ldr) == 0):

        count += 1

    return count

while True:

    value = rc_time(ldr)
    print(‘ldr value: ‘, value)
    sleep(0.5)

In essence, this code sets up all of the required components before defining a function that quantifies the amount of light present. This quantitative value can then be called upon in the code and assigned to a variable, where it can be used (in this case, the code just prints the light level). The most important part of this code is the function declaration – what you do with it afterwards is up to you.

Angular Servos

Servo motors are a type of motor able to control their angular position depending on the signal sent to it. The ones this tutorial will be referring to have a total range of 180 degrees, meaning they can turn to any angle between 0 and 180. Its name in the gpiozero library is AngularServo.

The servo should have three wires coming out of it. Holding the servo with the exposed end of the shaft facing towards you and the wires coming out of the bottom end, the leftmost wire goes into a ground pin, the middle one goes into a power pin, and the rightmost one goes into a GPIO pin. They should be black/red/yellow respectively, but the colors may differ depending on the servo. 

When initializing a servo, there are three parameters that must be inputted – the pin, the minimum angle, and the maximum angle. For example, for a servo in pin 18:

servo = AngularServo(18, min_angle = -90,  max_angle = 90)

To move a servo in the code, just type [servoName].angle = [angle]. Make sure to include a sleep function so the servo knows how long to hold that position for.

Continuous Servos

Unlike angular servos, continuous servos have freedom of rotational movement and aren’t bound within a specific range of angles. However, they are unable to control angular position, and are just used to continuously rotate things like wheels. Their name in the gpiozero library is simply Servo, and connecting them to the board is the same as connecting an angular servo.

When initializing this servo, all you need is the pin number. To use it, just write [servoName].value = [speed], where speed is any value between -1 and 1. The closer to 1, the faster the motor will spin forwards, and the closer to -1, the faster it’ll spin backwards.