Raspberry

Workshop

Content

 

  • What is a Raspberry?
  • Why Rasberry?
  • Generations of Raspberry
  • Parts of the raspberry
  • Linux commands
  • Bash
  • Compile/Run (C,Python)
  • JavaScript basics
  • IoT?
  • Server with Node.js
#!/bin/bash
Topic="Raspberry Workshop"

SubTopic[0]="What is a Raspberry"
SubTopic[1]="Why Rasberry"
SubTopic[2]="Generations of Raspberry"
SubTopic[3]="Parts of the raspberry"
SubTopic[4]="SSH"
SubTopic[5]="Linux"
SubTopic[6]="Bash"
SubTopic[7]="Compile/Run (C,Python)"
SubTopic[8]="IoT?"
SubTopic[9]="JavaScript basics"
SubTopic[10]="Firebase"

getContent(){
    echo ${SubTopic[$1]}
}

echo $Topic
getContent $1

#Run: bash workshop.sh 0 

What is a Raspberry?

 

Is a low cost, credit-card sized computer.

 

Enables people of all ages to explore computing.

 

It’s capable of doing everything you’d expect a desktop computer to do.

 

Why Raspberry?

It’s Cheap!

It’s Tiny

Can Run A Variety Of Operating Systems

Is Really Versatile

You Can Overclock It

Generations of raspberry

Raspberry Pi 1

Release date

February 2012

CPU

Memory

Storage

700 MHz single-core ARM1176JZF-S (model A, A+, B, B+, CM)[2]

256 MB[3] (model A, A+, B rev 1) 512 MB (model B rev 2, B+, CM)

SDHC slot (model A and B), MicroSDHC slot (model A+ and B+), 4 GB eMMC IC chip (model CM)

Raspberry Pi 1 model B+

Power

1.5 - 3.5 W

Raspberry Pi 2

Release date

February 2012

CPU

Memory

Storage

900 MHz quad-core ARM Cortex-A7

1 GB RAM

MicroSDHC slot

Raspberry Pi 2 model B

Power

4.0 W

Raspberry Pi 3

Release date

29 February 2016

CPU

Memory

Storage

1200 MHz quad-core ARM Cortex-A53

1 GB RAM

MicroSDHC slot

Raspberry Pi 3 model B

Power

4.0 W

Raspberry Pi Zero

Release date

November 2015

CPU

Memory

Storage

1000 MHz single-core ARM1176JZF-S

512 MB RAM

MicroSDHC slot

Raspberry Pi Zero

Power

Price

0.8 W

US$5

Parts of the Raspberry

SSH

SSH?

Secure Shell is a cryptographic network protocol for secure data communication, remote command-line login, remote command execution, and other secure network services between two networked computers.

We will use a SSH client to connect to the Raspberry Pi remotely over a Local Area Network (LAN)

Software and configurations

No additional software is required, but we need to activate SSH service

*Putty: Free SSH and telnet client

*Xming: 

pi@raspberrypi ~ $ sudo raspi-config

Restart your Pi and login again.

Advanced Options >>

SSH >>

Enable

IP Address

pi@raspberrypi ~ $ ifconfig

A list of networks will appear, look at eth0 and save the IP Address.

Using SSH in PuTTY

Password:

raspberry

User:

pi

Graphic mode?

In windows open Xming Server

pi@raspberrypi ~ $ startlxde

In Linux

Linux 

What is Linux?

 Four main parts make up a Linux system:

 

  • The Linux kernel
  • The GNU utilities
  • A graphical desktop environment
  • Application software

Linux Kernel

 The kernel is primarily responsible for four main functions:

  • System memory management
  • Software program management
  • Hardware management
  • Filesystem management

System File

The Shell

  • The GNU/Linux shell is a special interactive utility.

 

  • It provides a way for users to start programs, manage files on the filesystem, and manage processes running on the Linux system.

 

  • It allows you to enter text commands, and then it interprets the commands and executes them in the kernel.

Bash Shell

The default shell used in all Linux distributions is the bash
shell.
 The bash shell was developed by the GNU project as a replacement for the standard Unix shell, called the Bourne shell (after its creator). The bash shell name is a play on this wording, referred to as the “Bourne again shell.”

Bash Shell

https://goo.gl/T4eDKg

The default prompt symbol for the bash shell is the dollar sign ($). 

I will be using the "$" in my codes to represent terminal input, you don't need to type it.

You can check more basic commands

Basic commands

Display current directory:

$ pwd

Now create an empty file:

Display the content of the folder:

$ touch file.txt
$ ls -lh

Display a string:

Create a variable and display its content:

$ echo "Hello world!"
Hello world!
$ var="Hello world!"
$ echo $var
Hello world!
$ echo var
var
$ rm file.zip
$ rm -R dir

Delete

More commands

Bash

Scripts

If you need to write code that needs to run more than one time, you must consider to writing down in a file and then execute it when you need it.

Scripts needs to have at the first line the shebang.

#!/bin/bash

The shebang is used to tell the system the name of the interpreter that should be used to execute the script that follows.
 

Hello world!

  • Now time to write our first script
  • We will use an editor to write our script. 
  • Two popular editors: the traditional vi and the user friendly nano
  • I will use vi
$ vi hello_world.sh

Hello world!

#!/bin/bash

# This is a comment
echo 'Hello World!' 
# "" and '' have the same effect

Type (i) and later the code:

Save script. (Press Esc and then :wq Enter)

We can execute  file type:

$ sh hello_world.sh

Output:

Hello World!

The other way to execute the file is to make it an executable file

chmod 755 hello_world.sh
$ ls -l hello_world
-rwxr-xr-x 1 pi pi 63 2015-10-07 10:10 hello_world

Execute file 

$ ./hello_world.sh
Hello World!

If statment

We can evaluate an expression: 

#!/bin/bash

x=1

if [ $x -eq 10 ]; then
    echo "x is equal to 10"
elif [ $x -gt 10]; then
    echo "x es greater than 10"
else
    echo "x is less than 10"
fi

For loop

Example 1: 

Example 2: 

Example 3: 

Example 4: 

#!/bin/bash

for i in $( ls ); do
    echo item: $i
done
#!/bin/bash

n="1 2 3 4 5 6 7 8"
for i in $n; do
    echo "number: "$i
done
#!/bin/bash

for i in `seq 10`; do
    echo i
done
#!/bin/bash

for i in `seq 1 2 10`; do
    echo i
done

While loop

Example 1: 

Example 2: 

Older UNIX shells like Borne shell  and ksh88 have clumsy, inefficient way of doing arithmetic based on external expr command

#!/bin/bash

count=0
while [ $count -lt 10 ]; do
    echo $count
    count=`expr $count + 1`
done
#!/bin/bash

count=0
while [ $count -lt 10 ]; do
    echo $count
    count=$((count + 1))
done

Parameters

You can send parameters to a script. Write:

Execute file by typing:

#!/bin/bash

echo $0
echo $1
echo $2
echo $#
$ sh myscript.sh Hello World
myscript.sh
Hello
World
2

Program 1

Make a script that prints a count depending on the first parameter​

?

Program 2

Validate if a given number is odd

?

Program 3

Calculate the factorial number of a given number (0-9)

?

GPIOs

General Purpose Input Output

About GPIOs

* All GPIOs are 3.3 V tolerant

 

* They can provide maximum 16 mA, but not exceeding 50 mA from all at the same time


* 3.3 V pin can deliver 50 mA maximum


* 5 V pin can deliver your power supply – 700 mA for the raspberry*

Differences having an OS

Several inputs:

You have a mouse, keyboard, Ethernet connection, monitor, SD card without need to connect additional electronics
Filesystem:

Being able to read and write data in the Linux file system will make many projects much easier. 
Linux tools:

Packaged in the Raspberry Pi’s Linux distribution is a set of core command-line utilities, which let you work with files, control processes, and automate many different tasks.
Languages:

There are many programming languages out there and embedded Linux systems like the Raspberry Pi give you the flexibility to choose whichever language you’re most comfortable with

Program

We will turn on and off and LED


Connect and LED to GPIO25 using a 330 ohm resistor

Digital Output: Lighting Up an LED

You can then use the Linux command line to turn the LED on and off.

Steps:
1) Connect to raspberry (SSH) 
2) In order to access the input and output pins from the command line, you’ll need to run the commands as root, the superuseraccount on the Raspberry Pi. To start running commands as root, type sudo su  at the command line and press enter:

The root account has administrative access to all the functions and files on the system and there is very little protecting you from damaging the operating system if you type a command that can harm it.

pi@raspberrypi ~ $ sudo su
root@raspberrypi:/home/pi#

Digital Output: Lighting Up an LED

3) Before you can use the command line to turn the LED on pin 25 on and off, you need to export the pin to the userspace(in other words, make the pin available for use outside of the confines of the Linux kernel), this way:
 

root@raspberrypi:/home/pi# echo 25 > /sys/class/gpio/export

The echo command writes the number of the pin you want to use (25) to the export file, which is located in the folder /sys/class/gpio. When you write pin numbers to this special file, it creates a new directory in /sys/class/gpio that has the control files for the pin. In this case, it created a new directory called /sys/class/gpio/gpio25.

Digital Output: Lighting Up an LED

4) Change to that directory with the cd command and list the contents of it with ls:

root@raspberrypi:/home/pi# cd /sys/class/gpio/gpio25
root@raspberrypi:/sys/class/gpio/gpio25# ls
active_low direction edge power subsystem uevent value

The echo command writes the number of the pin you want to use (25) to the export file, which is located in the folder /sys/class/gpio. When you write pin numbers to this special file, it creates a new directory in /sys/class/gpio that has the control files for the pin. In this case, it created a new directory called /sys/class/gpio/gpio25.

Digital Output: Lighting Up an LED

5) The directionfile is how you’ll set this pin to be an input (like a button) or an output (like an LED). Since you have an LED connected to pin 25 and you want to control it, you’re going to set this pin as an output:

root@raspberrypi:/sys/class/gpio/gpio25# echo out > direction

6) To turn the LED on, you’ll use the echo command again to write the number 1 to the value file:

root@raspberrypi:/sys/class/gpio/gpio25# echo 1 > value

7) After pressing enter, the LED will turn on! Turning it off is as simple as using echo to write a zero to the value file:

root@raspberrypi:/sys/class/gpio/gpio25# echo 0 > value

Virtual Files

The files that you’re working with aren’t actually files on the Raspberry Pi’s SD card, but rather are a part of Linux’s virtual file system, which is a system that makes it easier to access low-level functions of the board in a simpler way. 


For example, you could turn the LED on and off by writing to a particular section of the Raspberry Pi’s memory, but doing so would require more coding and more caution.

Program

We will read a digital input and display its status “0” for GND and “1” for 3.3v.


Connect the following diagram

Digital Input

Almost same instructions. Remember to run commands as root.

root@raspberrypi:/home/pi# echo 24 > /sys/class/gpio/export
root@raspberrypi:/home/pi# cd /sys/class/gpio/gpio24
root@raspberrypi:/sys/class/gpio/gpio24# echo in > direction
root@raspberrypi:/sys/class/gpio/gpio24# cat value
0

(1) Export the pin input to userspace.
(2) Change directory.
(3) Set the direction of the pin to input.
(4) Read the value of the of the pin using cat command.
(5) Print the result of the pin, zero when you aren’t not pressing the button.

Compile/Run (C,Python)

Python GPIOs

We can use Python to control the GPIOs.
Open Python by typing on the Linux console:

sudo python

First make sure this library its already installed on the Raspberry Pi. In console type:

>>> import RPi.GPIO as GPIO

If you don’t get an error, you’re all set.
Close the console

How to install Python library

Type the following command on the Linux console

$ wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz
$ tar zxf RPi.GPIO-0.1.0.tar.gz
$ cd RPi.GPIO-0.1.0
$ sudo python setup.py install

The instructions here refer to an early version of RPi.GPIO. Please search the web for the latest version and replace the version numbers in the instructions below. On newer Raspbian distributions library is included.

Installing and Testing GPIO in Python

On the Python console type:

>>> import RPi.GPIO as GPIO
>>> GPIO.setmode(GPIO.BCM)
>>> GPIO.setup(25, GPIO.OUT)
>>> GPIO.output(25, GPIO.HIGH)
>>> GPIO.output(25, GPIO.LOW)
>>> exit()

1) Import GPIO library
2) Use BCM convention for the names of the GPIOs
3) Pin 25 as output
4) Turn on pin 25 (send 3.3v)
5) Turn off pin 25 (connect to ground)
6) Close python interpreter

BCM is for Broadcom BCM 2835 chip, the chip that is containned in the Raspberry Pi. When we set mode as BCM we are telling to the library that I want to use the real pin names of the BCM chip. There are other configurations that we will not use in this class (such as board).

Blinking an LED

We will use a Python Script.
Create a new file,  name it blink.py
Write the following code:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)
while True:
	GPIO.output(25, GPIO.HIGH)
        time.sleep(1)
        GPIO.output(25, GPIO.LOW)
        time.sleep(1)	
touch blink.py
vi blink.py

Run:

pi@raspberrypi ~ $ sudo python blink.py

Your LED should now be blinking!!!
Hit Ctrl+C to stop the script and return to the command line

Read a Button

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
while True:
    inputValue = GPIO.input(24)
    if (inputValue == True):
        count = count + 1
        print("Button pressed " + str(count) + " times.")
        time.sleep(.3)		#Wait for the user
    time.sleep(.01)  #So the CPU is not at 100%

IoT?

What kind of things?

How will the things be used?

JavaScript basics

Scripting language

  • Only work in a web browser

  • Cannot access local files

  • Cannot directly access database

  • Cannot access hardware (USB, etc..)

Major implementations:

It's not Java

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}

It’s more Scheme/Lisp-style functional

Scheme

Lisp

(define hello-world
   (lambda ()
         (begin
	(write ‘Hello-World)
            (newline)
	(hello-world))))
(DEFUN HELLO ()
  "HELLO WORLD"
) 

Embedding JavaScript

In head or body tags

External file

<!DOCTYPE html>
<html>
<head>
<script>
    alert("Hello world!!!");
</script>
</head>

<body>

<script>
    var a = 3;
    document.write(a);
</script>

</body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>

    </head>
    <body>
        <H1>Text...</H1><br/>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed venenatis lectus elit, sed efficitur libero dictum sed. Mauris pellentesque finibus massa. Morbi eu elementum massa. Curabitur massa lorem, tincidunt nec orci sit amet, consequat pellentesque nulla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pellentesque lacus finibus cursus congue. Vivamus ullamcorper dui eu massa commodo, sit amet convallis turpis tempor. Aenean et porta justo.</p>
        <script src="myScript.js"></script>
    </body>
</html>

Using Chrome console

Open Developer Tools and bring focus to the console

 

Ctrl + Shift + J

Variables

Operators are how we perform actions on variables and values.

var a = "42";
var b = Number( a );
var c = 5;

c += 4;
console.log( a );   // "42"
console.log( b );   // 42
console.log( c );   // 9

Functions

Is generally a named section of the code that can be "called" by name, and the code inside it will be run each time.

function printAmount(amt)
{
    console.log( amt.toFixed( 2 ) );
}

function formatAmount()
{
    return "$" + amount.toFixed( 2 );
}

var amount = 99.99;

printAmount( amount * 2 );    // 199.98

amount = formatAmount();

console.log( amount );        //$99.99

Firebase

JSON

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight data interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand
[
    {
        "id": 2,
        "name": "An ice sculpture",
        "price": 12.50,
        "tags": ["cold", "ice"],
        "dimensions": {
            "length": 7.0,
            "width": 12.0,
            "height": 9.5
        },
        "warehouseLocation": {
            "latitude": -78.75,
            "longitude": 20.4
        }
    },
    {
        "id": 3,
        "name": "A blue mouse",
        "price": 25.50,
        "dimensions": {
            "length": 3.1,
            "width": 1.0,
            "height": 1.0
        },
        "warehouseLocation": {
            "latitude": 54.4,
            "longitude": -32.7
        }
    }
]
from random import randint
import os

page = "https://.....firebaseio.com/.json"
user_id = randint(0,999)
user_name = raw_input('Type the name')
info1 = " \"user_id\" : \""+str(user_id)+"\" "
info2 = " \"name\" : \""+user_name+"\" "
complete_info = info1 + "," + info2
command = "curl -X POST -d '{"+complete_info+"}' '"+page+"'"
os.system(command)

http://pastie.org/10792854

<html>
    <head>
        <title>Results</title>
        <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <script>
        var myDataRef = new Firebase('https://amber-inferno-8840.firebaseio.com/');

        myDataRef.on('child_added', function(snapshot) {
              var message = snapshot.val();
	      var id = message.user_id;
	      var name = message.name;
	      $('#results tr:last').after('<tr><td>'+id+'</td><td>'+name+'</td></tr>');
        });
        </script>
        
    </head>
    
    <body>
        <center>
            <table class="table table-bordered table-hover" id="results">
		<tr>
			<th>ID</th>
			<th>Name</th>
		<tr>
	    </table>
        </center>
    </body>
</html>

http://pastie.org/10792852

Additional info:

Search for:

Firebase

www.firebase.com

Jquery

https://jquery.com/

Boostrap

http://getbootstrap.com/

Thanks for your attention

References:

  • https://www.raspberrypi.org/help/what-is-a-raspberry-pi/
  • http://www.makeuseof.com/tag/7-reasons-raspberry-pi/
  • http://www.flaticon.com/
  • https://en.wikipedia.org/wiki/Raspberry_Pi
  • https://www.sparkfun.com/news/1888

http://makerobots.tk/

Raspberry

By Irving Norehem Llamas Covarrubias