How to connect a new Raspberry Pi to your Laptop without a screen? Click here to master it!

Introduction to Rasperry Pi

Posted by Momen 09/03/2017 0 Comment(s)

Welcome to Zeroohm Raspberry Pi Training series. In this series of Raspberry Pi Training, Zeroohm will focus its efforts on helping the community learn more about Raspberry Pi fundamentals and basics starting with basic control of LED's, motors, sensors and utilizing of wirless communication. We hope that you find this useful, Please, leave a comment for any questions or comments or reviews!

We provide all our trainings for groups from schools, universities, public sector and private sector in Abu Dhabi, Dubai, Sharjah, Fujirah, RAK or anywhere in UAE. Please,click here to contact us directly for any training inquires.

Our Raspberry Pi training series:

1. Introduction to Raspberry Pi

2. Analog Inputs/Output In Raspberry Pi

3. Wireless Communication in Raspberry Pi

4. How to connect a new Raspberry Pi to your Laptop without a screen

5. Communication between Raspberry Pi and Arduino

 

 

Getting started:

Raspberry pi is a very powerful SBC (single board computer). It can drive HDMI display, process a mouse, keyboard and camera, it can connect to the internet via Ethernet or WiFi, and it can run a full-featured Linux operating system. But it’s not only a computer, it’s also a prototyping device, it has pi-directional input/output pins which can be used, with proper programing, to perform many tasks.

  • Hardware:
    • Raspberry Pi (Raspberry Pi 2 Model B).
    • SD Card with SD Card Adapter.
    • Compatible Keyboard + Mouse.
    • HDMI Cable.
    • Power Supply (USB Cable).
    • Screen.
  • Software:
    • Raspbian OS Image.
    • Image Writer Software.
  • Setting up the SD Card:
  1. Download Raspbian Image file from www.raspberrypi.org/downloads/raspbian.
  2. Install and Run Image writing tool.

  • First Boot up :
  • Username: pi
  • Password: raspberry
  • GPIO pins:

To use raspberry pi’s GPIO pins in python you must first download the ‘RPi.GPIO’ library. To do so, open the terminal in the raspberry pi and run the following command:

Sudo apt-get update

After it’s done, run:

Sudo apt-get install rpi.gpio

To access the GPIO pins in python you must first import the ‘RPi.GPIO’ library to the code:

RPi.GPIO as GPIO

Then we must the mode of the pins. In this you have two options, the first mode is ‘BOARD’ mode where use the physical numbering of the pins (you can simply count with your finger!!). The second mode is the ‘BCM’ mode, when use this mode you need to follow the number after ‘GPIO’ in the figure below:

To set the mode to ‘BOARD’ we use:

GPIO.setmode(GPIO.BOARD)

To set the mode to ‘BCM’ we use:

GPIO.setmode(GPIO.BCM)

Then we set the pin that we want to use as input or output.

GPIO.setup(pin,GPIO.IN)
GPIO.setup(pin,GPIO.OUT)

Where ‘pin’ is the number of the GPIO pin based on whether you used BOARD or BCM:

Ex: In BOARD pin number 3 is pin number 2 in BCM.

  • Experiment 1: Blinking LED

Light-Emitting Diode (LED) is a semiconductor light source. It’s a two-lead electrical component, one lead connects to an n-type semiconductor (negative) and the other lead connects to p-type semiconductor (positive). LED’s has a long life expectance and come in many sizes, shapes and colours.
In this task you will control the switching of an LED through using raspberry pi by the following these steps:
1.    Connect the following Circuit using the shown components.

2.    From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.
3.    Write the following code:

import RPi.GPIO as GPIO  
import time
# to use Raspberry Pi board pin numbers  
GPIO.setmode(GPIO.BOARD)
# set up GPIO output channel
GPIO.setup(8, GPIO.OUT)

pin=8
# blink GPIO14 10 times
for i in range(0,10):
    GPIO.output(pin,GPIO.HIGH)  
    time.sleep(1)  
    GPIO.output(pin,GPIO.LOW)  
    time.sleep(1)
GPIO.cleanup()  

4.    Run the code by pressing “F5”.

  • Discussion:

-    Raspberry pi is unlike Arduino, it does not automatically run the code on a loop forever unless you program it to do so.
-    At the beginning of any python code you should import the necessary libraries or they are called in python “Modules”.
-    The time module is used to do any time based operation, for our code it’s used to delay the execution of the next line of code by one second so that the blinking will be visible.
-    To blink the LED, we must turn it ON and OFF repeatedly, to do so we first create a ‘for’ loop.
-    Inside the loop we turn the LED ON by setting the GPIO pin to HIGH, delay for one second, setting the GPIO pin to LOW and finally delay again for one second. The command “GPIO.output(pin , GPIO.HIGH / LOW)” is used for that.
-    Finally we run the command “GPIO.cleanup()” in order to return the GPIO pin to the default settings (i.e input).

Brainstorming:
An efficient way of programming is something called “Functional Programming”, it’s basically a method of programing where you divide your code into functions and then calling these functions when needed.
For example in the first experiment the functional programing way will be as follows:
import RPi.GPIO as GPIO  
import time  
# blinking function  
def blink(pin):  
        GPIO.output(pin,GPIO.HIGH)  
        time.sleep(1)  
        GPIO.output(pin,GPIO.LOW)  
        time.sleep(1)  
        return
    
# to use Raspberry Pi board pin numbers  
GPIO.setmode(GPIO.BOARD)  
# set up GPIO output channel  
GPIO.setup(8, GPIO.OUT)  
 
for i in range(0,10):  
        blink(8)  
GPIO.cleanup()  

  • Experiment 2: Push button

A push button is an electrical component that connects two point in a circuit when it is pushed. It can be used to temporally switch ON and OFF any electrical device or component like the ringing of a doorbell when a person pushes a button, or when numbers are displayed on a calculator.

In this experiment you’ll be switching an LED ON and OFF using a push button by following these steps:
1.    Connect the following Circuit using the shown components.

2.    From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.
3.    Write the following code:
import RPi.GPIO as GPIO  
import time  
# to use Raspberry Pi board pin numbers  
GPIO.setmode(GPIO.BOARD)
# set up GPIO pin 8 as output channel
GPIO.setup(8, GPIO.OUT)
# set up GPIO pin 10 as input channel
GPIO.setup(10, GPIO.IN)
led=8
button=10
# check if button is pressed 1000 times
for i in range(0,1000):
    x = GPIO.input(button)
    if x == True:
        GPIO.output(led,GPIO.HIGH)
    else:
        GPIO.output(led,GPIO.LOW)
    time.sleep(0.1)

  • Discussion:

-    In this code GPIO pin 8 is set as an input, while GPIO pin 10 is set as an output.
-    The ‘for’ loop is set so that we constantly check the status of the GPIO input.
-    We simply do the following operation:
-    We read the GPIO input pin 10 using the command ‘GPIO.input(pinNumber)’.
-    We check if it’s hi or low using “If statement”.
-    We turn the LED ON or OFF based of the result with ‘GPIO.output(pin , GPIO.HIGH or LOW)’.
-    Finally we put a delay on the loop to gives a little time to push and release the button as we like.
-    A pull-down resistor is used at the GPIO input pin 10. If you don’t use a pull-down resistors to the input port, the returned status will not be clearly defined. It will be “floating”. It can be affected by static electricity from you or any devices the surrounding environment. Also any wires attached to the GPIO pin will act as antenna and it can be affected by random electromagnetic radiation.


Brainstorming:
As you will notice, we set the loop to 1000 loops and we put a delay time on each time by 0.1 seconds, this will give us a time of 100 seconds to push and see the result. If the delay is not put the code will loop at a very fast speed (1.2 GHz for pi 3) and thus we will not have enough time to act.
But the ‘for’ loop has one big disadvantage, it does not run for ever!! In real life cases we might need to read the input for as long as our system is working, thus a ‘for’ loop will not be efficient.
To solve that, a very useful technique can be used. We can use a ‘while’ loop as follows:
while True:
    x=GPIO.input(button)
    if x == True:
        GPIO.output(led,GPIO.HIGH)
    else:
        GPIO.output(led,GPIO.LOW)
    time.sleep(1)

Now you might say why we didn’t but a equality condition on the loop like ‘while x == True’, that is because again when the code is running as processor speed it will check the condition, if it is satisfied it’ll run the commands inside the loop and when it’s not satisfied it’ll break out of the loop and continue with the next line after the loop section which in our case is none (The End!!).
Use ‘While loop’ with just one Boolean variable is helpful. For example ‘while x:’ will run the loop body as long as ‘x’ is ‘True’. Now you can understand the ‘while True’ will run forever since ‘True’ will always be evaluated to ‘True’.

 

  • Experiment 3: Piezo Buzzer

A buzzer is audio outputting device that outputs a specific tune based on the input voltage signal. Typical uses of buzzers and beepers include alarm devices.

In this experiment you’ll be making some noise using a piezo buzzer with the help of one library called ‘softTone’.

1.    Connect the following Circuit using the shown components.

2.    From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.
3.    Write the following code:
import RPi.GPIO as GPIO
import time

#set the buzzer pin variable to number 8
buzzer_pin = 8                  
GPIO.setmode(GPIO.BOARD)
GPIO.setup(buzzer_pin, GPIO.OUT)  #Set pin 8 as an output pin

freq_s = input('Enter Pitch (200 to 2000): ')   #ask the user to type in the pitch
freq = float(freq_s)    #convert user input to a floating decimal
duration_s = input('Enter Duration (seconds): ')  #ask the user to type in the duration
duration = float(duration_s)  #convert user input to a floating decimal
period = 1.0 / freq    #in physics, the period (sec/cyc) is the inverse of the frequency (cyc/sec)
delay = period / 2     #calcuate the time for half of the wave
cycles = int(duration/ period)   #the number of waves to produce is the duration times the frequency


for i in range(cycles):    #start a loop from 0 to the variable “cycles” calculated above
    GPIO.output(buzzer_pin, True)   
    time.sleep(delay)    
    GPIO.output(buzzer_pin, False)    
    time.sleep(delay)

  • Discussion:

-    As all previous experiments, we first imported the necessary modules.
-    Then we set the GPIO numbering mode and set the pin that we’re going to use as output.
-    In this experiment we introduced the command ‘input(“statement”)’ where you can ask the user to input using the keyboard. The ‘statement’ can be anything, its purpose is to explain to the user what to input.
-    We asked the user to input the frequency of the tone that we wish to pay on the buzzer and the duration of that tone. We converted both inputs to ‘float’, you may ask why? Because the command ‘input’ returns a string type variable, so we must convert the inputted string number to float to proceed with our calculations.
-    Buzzers works with small voltage ac signals, in this experiment we generate a square wave to activate the buzzer, but what is the variables ‘freq’ and ‘period’ for.

-    Frequency equals the number of cycles per second, a cycle starts with the wave ‘HIGH’ and ends when the cycle goes from ‘LOW’ to ‘HIGH’. A period is the time it takes one cycle to finish and it’s equals to the reciprocal of the frequency. The duration is simple, it’s the time from the start to the end (it can’t be forever!!).
-    To generate the wave we calculate who many cycles we need and loop that many times.
-    Inside the loop we set the output as ‘HIGH’ then delay for half the period, the set it as ‘LOW’ and delay for the second half of the period. They we go for the second loop to generate the second cycle and so on.

 

  • Experiment 4: RGB LED.

RGB LED is a four pin LED that can emit light with different colours based on which pins is activated. Unlike one coloured LEDs which have one anode and one cathode, an RGB LED has three cathodes and one anode. Each cathode is connected to a single colour (red, green or blue) and the different colours are produced in that one single LED.
In this experiment you’ll produce different colours out of the RGB LED based on a keyboard input:
1.    Connect the following Circuit using the shown components.


2.    From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.
3.    Write the following code:
import RPi.GPIO as GPIO
import time
#set the RGB pins variable to number 8
red = 8
green = 10
blue = 12
GPIO.setmode(GPIO.BOARD)
GPIO.setup(red, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)

colors='colours list: red,green,blue,yellow,cyan,purple,white'
print(colors)
while True:
     colour = raw_input('Input a colour: ')
 
     if colour == 'red':
        GPIO.output(red,True)
        GPIO.output(blue,False)
        GPIO.output(green,False)
    elif colour == 'green':
        GPIO.output(red,False)
        GPIO.output(blue,False)
        GPIO.output(green,True)
    elif colour == 'blue':
        GPIO.output(red,False)
        GPIO.output(blue,True)
        GPIO.output(green,False)
    elif colour == 'yellow':
        GPIO.output(red,True)
        GPIO.output(blue,False)
        GPIO.output(green,True)
    elif colour == 'cyan':
        GPIO.output(red,False)
        GPIO.output(blue,True)
        GPIO.output(green,True)
    elif colour == 'purple':
        GPIO.output(red,True)
        GPIO.output(blue,True)
        GPIO.output(green,False)
    elif colour == 'white':
        GPIO.output(red,True)
        GPIO.output(blue,True)
        GPIO.output(green,True)
    else:
        print('Inputed color is not in the list')

  • Discussion:

-    In this code we start by setting the GPIO pins to output, make sure to name, number and connect the right pin with respect to colour.
-    Then we give the user a list of accepted colours by simply printing it for the user to read.
-    Then we give the user the option of using a colour by using the command “raw_input(‘statement’)”.
-    After that we simply compare the input to find which colour the user have entered, then we set the GPIO pins so that the RGB LED will emit that colour.


Brainstorming:
In this code we used the command “raw_input(‘statement’)” instead of “input(‘statement’)”, that is because in python 2.x the “raw_input(‘statement’)” returns a string while the command “input(‘statement’)” tries to evaluate the input as python code. To simplify, if you’re using python 2.x, with the first command user can simply type the word red, while with the second when to input a string the user must type ‘red’ since in python string variables are defined by between quotation marks. In python 3.x both commands returns a string.

 

 

Leave a Comment