Introduction: Raspberry Pi - GPIOs, Graphical Interface, Pyhton, Math, and Electronics.

Picture of Raspberry Pi - GPIOs, Graphical Interface, Pyhton, Math, and Electronics.

Hello people!

This instructable aims in playing with some of Raspberry's features.

I won my Raspberry Pi from one my friends some time ago, and at the beginning I had no idea of how to use it. I already was a bit familiar with Arduino, but didn't know how Raspberry works. Since then, It has helped me to understand a little more about Linux, start in Python language, and also play a little with python's module Pygame.

So, now you have your pretty Raspberry PI running Raspbian and ready for coding?

So, let's see what we can do.

Step 1: Getting Started

Picture of Getting Started

I presume that you have a Raspberry running Raspbian and connected to a screen.If you don't, don't wait too much, there are a lot of good instructables teaching how to burn Raspbian on a SD card.

You won't need to download anything,so there is no need to connect your raspberry to internet, if you were worried (I only have wifi in my accommodation). Raspbian fortunately already comes with Pygame and Raspi GPIO.All software that we need for this task.

However, to test your GPIO, You will need additional electronics. I used a RGB LED (with resistors), but you can use any LED you want or other pieces of electronics you already is comfortable with (LED displays, Motors' drivers...).

Step 2: Running Python Codes.

Picture of Running Python Codes.

I generally use Python's IDLE to code, to open it go to Raspbian menu, then Programming, then Python 3(or 2). I don't know exactly all the differences between Python 2 and Python 3, except that I know that print is different:

print("Hello World!")#Python 3
print"Hello World!"  #Pyhton 2

After clicking the Python icon, the Python Shell opens, here we can input commands one at time. For example:

>>>2+2
4
>>>

or:

>>>print("Nothing")
Nothing
>>>

Ok, but I generally use the editor to make codes. To open the editor, go to File menu, then 'New window'. You will see the following window, use it to type your codes.

Oh, I almost forgot. Differently from C and Arduino, in Python we use indentations to limit code blocks. See the difference below:

C syntax:
if(i==5){
	printf("equal to five");
}
Python syntax:
if i==5:
	print("equal to five") 

After finishing your code, save it in the '.py' format. I recommend you to not change the location of saving, as the home folder it is the first place open in the terminal. To run your codes, open LXTerminal and type:

sudo Python3 nameofthescript.py

Also, I recommend this site to study Python.

Step 3: Raspberry GPIO Numbering

Picture of Raspberry GPIO Numbering

There are two kinds of numbering on the raspberry board, the main chip one(BCM) and the board one. Personally, prefer the board numbering, but anyway I always have to google a picture hehehe, so both are good, choose the one you prefer, but remember to follow it(if you mix the two, it can be a bad time).

You can see which GPIO is connected to a pin in this link from wikipedia. Just remember that you choose the board numbering, you will use the pin numbers. However, if you choose the BCM numbering, you wiil have to use the GPIO number connected to the pin you want to use.

For example:

The GPIO4 is connected in the physical board pin 7.

If you choose the board numbering:

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)

If you choose the BCM numbering:

GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.OUT)

These two pieces of code do the same thing. Although, you can hear me whisper that the board numbering is easier to use ;).

Step 4: Undestanding How Raspberry GPIOs Work

Picture of Undestanding How Raspberry GPIOs Work

Raspberry GPIOs work not so differently from the Arduino ones. The sequence is same, first you define the direction of the ports(input or output), than you read or write the state of the port, but differently some settings have to be done in order to use them, but you will get them easy.

Some times we take pieces of code that other programmers kindly share to make ease to program. These pieces of code are called libraries, with Arduino we use '#include

' to import a library to our project. With Python, we use 'import library' or 'import library as something', so we can use them.

To use GPIOs with Python we do some simple steps:

The first step is import the RPi.GPIO library:

import RPi.GPIO as GPIO

Next, you will need to set the numbering that you want to use:

GPIO.setmode(GPIO.BOARD) 

or:

GPIO.setmode(GPIO.BCM)

Then, we have to set the direction of the pin (output in this case):

GPIO.setup(pin,direction)# equivalent to Arduino 'pinMode'
example:
GPIO.setup(3,GPIO.OUT)

Finally, we set the state of the pin(high or low):

GPIO.output(pin,state)#equivalent to Arduino 'digitalWrite'
example:
GPIO.output(3,GPIO.HIGH)  

Step 5: Simple Blink Program.

Picture of Simple Blink Program.

Let's see how to run the 'hello world' of electronics on raspberry.

Arduino has the delay() function that let us wait some time until next line of code. However, using Raspberry we need to import the library time to have a form of delay. Then, to have a delay we use 'time.sleep(t)', where is the time in seconds,differently for Arduino where we use 'delay(t)' where t is given in milliseconds.

Continuing, below is the code to make a LED connected to board pin 3 blink:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(3,GPIO.OUT)
while True:
    GPIO.output(3,GPIO.HIGH)
    time.sleep(1)
    GPIO.output(3,GPIO.LOW)
    time.sleep(1)

Step 6: What Is Pygame?

Picture of What Is Pygame?

Pygame is a python module used to make games. Although, you can use it just to draw things on the screen, as also receive input from keyboard and mouse. I will show and explain how to use it to control the GPIOs through a simple graphical interface.

To use Pygame library, you will have to import it first:

import pygame

Then, you will have to start the display to be able to draw on screen.:

pygame.init()
screen=pygame.display.set_mode((480,160))

The second line creates a surface where we can draw, The arguments inside the two parenthesis are the size of our canvas. I used 480x160, to best fit my code. When you get used to it, you will find the best size for your project.

Step 7: Cartesian Plane

Picture of Cartesian Plane

Your computer's screen is formed by pixels, that are organized in a grid. It is like a cartesian plane, but its origin(0,0) is at the top left corner. I think i read in some place that this is because of how old computers' screens worked. The lines were drawn from the left to the right, one by one from the top to the bottom of the monitor.

Please, see the picture below with some points market:

The points are referenced by their x and y coordinates, x is the horizontal distance and y is the vertical distance.The fist coordinate is x and the second is y, on the form (x,y). Said this, the points on the picture above are:

A=(2,2)

B=(9,1)

C=(7,4)

D=(11,3)

E=(1,9)

F=(12,9)

So, when we want to draw something on the screen, we have to think how far from the origin it has to be drawn. For example, if we are using a screen size of 320x240 and want to draw a circle on middle, we draw its center at (160,120).

See, it is easy, is not? Remember that differently from school, there are no negative values.

Step 8: Drawing Objects.

Picture of Drawing Objects.

To draw shapes on the screen, we have to know the syntax of each one.The syntaxes for rectangles, circles, arcs, lines and others can be found on this link.

For example, to draw the circles I used as buttons:

pygame.draw.circle(screen,red,(80,80),60,0)

This code draws the first circle on the image above, the first parameter is 'screen' that is the surface we created some steps ago. 'red' is the color for the circle, but we create these colors. the first two numbers (80,80) are the location of the centre of the circle(remeber the cartesian plane) and the last two are the radius and thickness(leave zero to fill completely).

Ah look, to define a new color we use:

color=(R,G,B)
ex:
red=(255,0,0)
Purple=(255,0,255)
black=(0,0,0)
white=(255,255,255)

We just mix red,green and blue to make the colors we want to use. The values to red, green and blue can be any value between 0 and 255, where 255 is the brightest.

You will need to update the screen always that you draw a new object on it, that is simple:

pygame.display.update()

Step 9: Events

In programming, a event can change the behavior of a algorithm, for example, a mouse click can make the program run a particular piece of code. I used a event in my code to change the state of LEDs attached to GPIOs when the inside of the circles are clicked.

To check if there was a mouse click, first we check the events happening, if there was any mouse click we get the position of the pointer:

ev=pygame.event.get()
    for event in ev:
     if event.type == pygame.MOUSEBUTTONUP:
        mpos=pygame.mouse.get_pos()

Step 10: Pythagoras' Theorem

Picture of Pythagoras' Theorem

What Pythagoras has to do with python and raspberry?

Simple, suppose we need to verify if the inside of circle was clicked, how to proceed?

Well,first we need the position of the click. We already know from the last step how to get this.

Also, the center of the circle we already have, as we defined it when drawing.

Then, we just need to know if the distance form the point clicked to the center of the circle is smaller or equal the radius of the circle.

Please, see the image above. The green point represents the click outside the circle. We can see that the distance from the centre of the circle and the clicked point is bigger than the radius of the circle.The blue point, however, is inside the circle and we can see that its distance from the center of the circle is smaller than the radius.

From the Pythagoras's theorem, it is known that the square of the largest side of a right triangle is equal to the sum of the squares of the two smaller sides. So, to calculate the largest side, we do a simple operation, with give us the the largest side of the right triangle is the square root of the sum of the squares of the two smaller sides(confusing? See the image above).

Then, we get that the distance from the circle center is:

distance = square root((x-xcenter)^2+(y-ycenter)^2)

Where x and y are the coordinates of points clicked, and xcenter an ycenter are the coordinates of the center of the circle. This distance must be smaller than the radius of the circle if the inside of the circle was clicked.

Block of code in Python:

if math.sqrt(math.pow(mpos[0]-240,2)+math.pow(mpos[1]-80,2))<60:

The math.sqrt method does the square root of the argument, which is the sum of the squares.

-mpos[0] and mpos [1] are the mouse click coordinates.

-240 and 80 are the coordinates of the center of the circle.

math.pow(x,n) does x^n, the square in this case.

Step 11: RGB LEDs

Picture of RGB LEDs

I connected a RGB LED to pins 3,5,7 on my Raspberry Pi. The circles inside the program control each color of the LED. A RGB LED is like three LEDs together, putting a voltage in each pin light up red or green or blue.

Activating more than one terminal to mix the colors generates new colors. For example, mixing red and green creates yellow, blue and green generates teal an ]d mixing red,green and blue generates white.

However. high bright RGB LEDs don't mix the colors well, we need something to diffuse the light, thats why I used that cute hat you can see on the last picture above.

Don't forget LEDs need resistors, without resistors they can burn or even damage your Raspberry Pi. I used 1k resistors because they were the only ones I had here, but they are higher than the value needed, so no problem. You can calculate the value for you resistors here.

Step 12: Whole Code.

Below is the code that I wrote, also if you wish, you can download it below.

Remember that to run python scripts with Raspberry we need to open the terminal and type:

sudo python3 nameofthescript.py

Just left a comment if you have any problem with running the code ;)

Whole code:

import RPi.GPIO as GPIO
import time
import pygame
import math

pygame.init()
screen=pygame.display.set_mode((480,160))
mpos=(0,0)

GPIO.setmode(GPIO.BOARD)

GPIO.setup(3,GPIO.OUT)#Red
GPIO.setup(5,GPIO.OUT)#Blue
GPIO.setup(7,GPIO.OUT)#Led

white=(255,255,255)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
    
screen.fill(white)
pygame.draw.circle(screen,red,(80,80),60,0)
pygame.draw.circle(screen,green,(240,80),60,0)
pygame.draw.circle(screen,blue,(400,80),60,0)
pygame.display.update()

GPIO.output(3,GPIO.LOW)
GPIO.output(5,GPIO.LOW)
GPIO.output(7,GPIO.LOW)

while True:
    ev=pygame.event.get()
    for event in ev:
     if event.type == pygame.MOUSEBUTTONUP:
        mpos=pygame.mouse.get_pos()
        print(mpos)
        if math.sqrt(math.pow(mpos[0]-80,2)+math.pow(mpos[1]-80,2))<60:
            print ("red")
            GPIO.output(3,1^GPIO.input(3))
              
        if math.sqrt(math.pow(mpos[0]-240,2)+math.pow(mpos[1]-80,2))<60:
            print ("green")
            GPIO.output(5,1^GPIO.input(5))
            
        if math.sqrt(math.pow(mpos[0]-400,2)+math.pow(mpos[1]-80,2))<60:
            print ("blue")
            GPIO.output(7,1^GPIO.input(7))
                     
    pygame.event.pump()


Step 13: Thank You!

That is it! I hope that you have fun as I had, if you have any doubt or problem, or think that this instructable could be better, or anything else, just say in the comments.

See you in another instructable. o/

Comments

Lorenzo Daidone (author)2015-12-08

Nice! Thank you!

Thanks for reading!

Thanks for reading!

lbaldin (author)2015-12-08

I've been searching for documentation on the raspberry's GPIOs for so long and finally somebody that makes a well-structured and documented guide. Thanks man :) love it.

Robson Couto (author)lbaldin2015-12-08

You're welcome!

Don't forget to check my blog too.

About This Instructable

11,489views

168favorites

License:

Bio: A eletrical engeneering student, video games lover and hardware aficionado. Starting my journey through the world of electronics. Microcontrollers?! I love them!
More by Robson Couto:Raspberry Pi - GPIOs, graphical interface, pyhton, math, and electronics.Scanner light and Arduino as an RGB lampDot Matrix Printer from a CD/DVD Reader with Arduino
Add instructable to: