This article is aimed at people who are new to the world of Raspberry Pi [Like me]. It gives an idea about what Raspberry Pi and Raspbian are and what are the uses of those. It also gives a simple guide to setup your first Pi and its OS, play around with a hello world program and set you on your path to build an army of Robots which will take over the world someday.
Below are the topics covered.
Article about the IoT overview linked below may serve as a good introduction to what the IoT is and its uses.
Internet of things - Overview
*Let’s start Raspberry Pi as just Pi to save some real estate :).
One line answer to the about question would be, “Pi is a single-board computer”. Pi is a small scale computer in the size little bigger than a credit card, it packs enough power to run games, word processor like open office, image editor like Gimp and any program of similar magnitude.
Pi was introduced as an educational gadget to be used for protyping by hobbyists and for those who want to learn more about programming. It certainly cannot be a substitute for our day to day Linux, Mac or Windows PC.
Pi is based on a Broadcom SoC (System of Chip) with an ARM processor [~700 MHz], a GPU and 256 to 512 MB RAM. The boot media is an SD card [which is not included], and the SD card can also be used for persist data. Now that you know that the RAM and processing power are not nearly close to the power house machines you might have at home, these Pi’s can be used as a Cheap computer for some basic functions, especially for experiments and education. The Pi comes in three Configurations and we will discuss the specifications of those in the coming sections. The cost of a Pi is around $35 for a B Model and is available through many online and physical stores.
Below are the basic things you would need to get started with using a Pi.
Computer
| A Raspberry Pi
|
Storage
| SD Card and a SD card reader to image the OS [These days laptops have inbuilt card readers]
|
Power supply
| 5 volt micro USB adapter, mostly your android phone charger would work
|
Display
| An TV/Monitor with DVI or HDMI port
|
Display connector
| HDMI cable or HDMI to DVI converter cable
|
Input
| USB Mouse
|
Input
| USB Keyboard
|
Network
| Ethernet cable
|
Case
| If you really need one, you can get them online based on the model you have
|
As discussed earlier the Pi comes in three configurations. Below is a table that gives the details about all three models namely A, B and B+.
Description
| Model A
| Model B
| Model B+
|
Chip
| Broadcom BCM2835 (CPU, GPU, DSP, SDRAM, and single USB port)
|
Processor
| 700 MHz ARM1176JZF-S core (ARM11 family, ARMv6 instruction set)
|
RAM
| 256 MB
| 512 MB
| 512 MB
|
USB
| 1 (direct from BCM2835 chip)
| 2 on board
| 4 on board
|
Storage
| SD Card
| SD Card
| MicroSD card
|
Voltage
| 600mA upto 1.2A @ 5V
| 750mA upto 1.2A @ 5V
| 600mA upto 1.8A @ 5V
|
GPO
| 26
| 26
| 40
|
For our learning we shall choose Model B and explain things with regards to that model. In case if you are wondering why B and not B+, it’s because I only own a B and not a B+ :)
Below are the ports on the Raspberry Pi board and some of their uses. The ports may also be used for other purposes than listed below.
USB
| Mainly used for pheriperals like Keyboard, mouse and a Wifi Adapter. A powered USB hub can be connected and be expanded
|
HDMI
| This is the High Definition Multimedia Interface [HDMI] and is use to connect to a Display unit like TV or Monitor or sometimes a projector
|
Stereo Audio
| Audio connections using a 3.5 mm jack
|
SD Card
| SD card is used as a boot device and also persistent storage. More stoage can be attached to the USB
|
Micro USB
| The micro usb port is used for supplying power to the unit
|
CSI Connector
| CSI [ Camera serial Interface] is used for connecting a camera to the unit
|
Ethernet
| Used for connecting to a network using a network cable
|
DSI Connector
| DSI [ Digital serial Interface] is used for connecting aLCD to the unit
|
One other important pin is the GPIO.
GPIO stands for General Purpose Input and Output.
There are 26 Pins on a Model B in total.
- There are three power supply pins [3.3v, 5.0v and 0v].
- 6 Do not Connect (DNC) pings
- 17 GPIO pins
We shall build a simple circuit towards the end of this tutorial to understand more about how to use these GPIO. Before that let’s get our Pi setup with an Operating system.
Below are some of the Operating systems that a Pi can run but in this article we will only learn about Raspian.
Linux
| There are three official Linux flavors available for download namely
|
Debian [Raspbian] *Recommended
|
ArchLinux
|
Pidora [Based on Fedora]
|
RISC OS
| A retro looking 1080p GUI designed by the ARM designers. RISC was more common during the 90's
|
Firefox OS
| A new OS by the Firefox team. Pretty much a combination of Firefox and PTXdist-built Linux
|
Plan 9
| Unix like OS by the by the Bell Labs, created by the UNIX creators
|
Android
| No explanation necessary, but this hasn't gone beyond a 2.3 build and a bit too slow.
|
Raspian OS is one of the official Operating systems available for free to download and use. The system is based on Debian Linux and is optimized to work efficiently with the Raspberry Pi computer. As we already know an OS is a set of basic programs and utilities that runs on a specified hardware, in this case the Pi. Debian is very lightweight and makes a great choice for the Pi. The Raspbian includes tools for browsing, python programming and a GUI desktop.
The Raspian desktop environment is known as the “Lightweight X11 Desktop Environment” or in short LXDE. This has a fairly attractive user interface that is built using the X Window System software and is a familiar point and click interface. We shall look more into how to install and use this OS in the next section.
Let’s first connect the board with all the necessary accessories to install and run an operating system.
Step 1: Take the Pi out of its anti static cover and place it on the non-metal table.
Step 2: Connect the display – Connect the HDMI cable to the HDMI port on the Pi and the other end of the HDMI cable to the HDMI port of the TV.
Step 3: Connect your Ethernet cable from the Router to the Ethernet port on the Pi
Step 4: Connect your USB mouse to one of the USB ports on the Pi
Step 5: Connect your USB Keyboard to the other USB port on the Pi
Step 6: Connect the micro USB charger to the Pi but don’t connect it to the power supply yet
Step 7: Flash the SD Card with the Raspian OS.
- To prepare the car for use with the Pi we will need to put a OS on the card. We certainly cannot drag and drop the OS files on to the card but the flashing the card is not too difficult either.
- Since we have already decided to install Raspbian, lets download the RASPBIAN image from the following link. http://www.raspberrypi.org/downloads/.
- Unzip the contents of the Zip file into a folder on your machine, one of the unzipped files would be a .img file which is what needs to be flashed on to the SD card.[In case there are more than one file, the current version of the zip has only this file and none other]
- Flashing from Linux instructions.
- Start the terminal on your Linux OS
- Insert the empty SD Card into the card reader of your machine.
- Type sudo fdisk -l to see all the disks listed. Find the SD card by its size,and note the device address (/dev/sdX, where X is a letter identifying the storage device. Some systems with integrated SDcard readers may use /dev/mmcblkX— format, just change the target in the following instructions accordingly).
- Use cd to change to the directory with the .img file you extracted from the Zip archive.
- Type sudo dd if=imagefilename.img of=/dev/sdX bs=2M to write the file imagefilename.img to the SDcard connected to the device address. Replace imagefilename.img with the actual name of the file extracted from the Zip archive. This step takes a while, so be patient! During flashing, nothing will be shown on the screen until the process is fully complete.
-
- Flashing from Windows Instructions
-
The Image Writer for Windows is used in place of dd which designed specifically for creating USB or SDcard images of Linux distributions, it features a simple graphical user interface that makes the creation of a Raspberry Pi SDcard straight forward. Download the latest version of Image Writer for Windows from the website: https://launchpad.net/win32-image-writer. Below are the steps.
i. Download the binary (not source) Image Writer for Windows Zip file, and extract it to a folder on your computer.
ii. Plug your blank SDcard into a card reader connected to the PC.
iii. Double-click the Win32DiskImager.exe file to open the program, and click the blue folder icon to open a file browse dialogue box.
iv. Browse to the imagefilename.img file you extracted from the distribution archive, replacing imagefilename.img with the actual name of the file extracted from the Zip archive, and then click the Open button.
v. Select the drive letter corresponding to the SDcard from the Device drop-down dialogue box. If you’re unsure which drive letter to choose, open MyComputer or Windows Explorer to check.
vi. Click the Write button to flash the image file to the SDcard.
- Once the OS is flashed, insert the SD card into the Pi SD Card slot
- Connect the MicroUSB to the power source and switch it on.
- Now the system boots into the below screen and the LED’s on the board will Blink. Below is a small GIF showing the boot screen
- Now you will need to login with username/password combination of pi/raspberry.
- If you would like to use the GUI interface type startx. Below is the image showing the previous two steps.
You are now all set with the OS installed and your Pi up and running.
* I am using Qemu emulator to get screen shots but the real config has all the below options plus some more like camera config.
If you need to enter the config menu of the Pi, you will need to use the sudo raspi-config command.
This config appears on the first boot of your Pi as well. Below are some options available and their quick explanations.
Below are some options I used on my first boot.
Step 1 : expand_rootfs.
Choose or highlight the “expand_rootfs” option and press enter. Use your keyboard arrow keys to select the option. Once you press enter you will get a confirmation screen like below, press enter again and you will be taken back to the main config screen.
Step2: overscan :
You can either enable or disable overscan here. I am disabling it so my screen fills up completely.
Step 3: configure_keyboard:
Since the initial setting gives me the UK keyboard format, I will change the setting to use the generic international 105 with English(US) option. Select "configure_keyboard" and press Enter.
Once the keyboard type is set, you'll need to specify the layout. There's a good chance you want a different layout than English (UK) like me, so choose "Other" and select an appropriate option for you. I am sticking with English (US).
After this just choose the default modifier keys when asked, as well as "No compose key" on the next screen. If later you find you need a compose key to create alternative characters, you can return to this configuration screen by running "raspi-config".
Step 4: Change password. Select change_pass and the rest are self-explanatory steps. I think it’s a good idea to change the generic password :)
Step 5: Setting up Locale:
If you live in the USA then you want en_US.UTF-8 else it depends on where you live. Scroll down to your locale you need, and de-select the en_GB [Great Britian] option on your way. In our case, we'll be enabling en_US.UTF-8
The next dialogue window will ask you to choose a default locale, select the locale you just chose on the previous screen and press Enter.
Step 6: Setup Timezone:
Select the "change_timezone" option. You'll be presented with a list of regions first.
The next dialogue will show you a list of zones within that region. I am sure you can handle it from here J
Step 7: Finish
Go back to the main menu and select Finish. This should take you back to the original boot screen and you can type startx from there to enter the LXDE environment or the GUI.
As discussed briefly earlier LXDE is the Graphical user interface for the Raspian Operating system. Now let’s quickly look at what are the tools and functions included with the LXDE.
The GUI doesn’t load by default and you will need to enter the startx command to launch the GUI.
The LXDE comes preinstalled with a plenty of software to get started. Below is a list of some of the available softwares for the Pi, the list is not exhaustive and you are free to explore the functions that are not listed here. The list below only serves as an introduction to the LXDE software packages.
The LXDE softwares are divided into categories as below:
- Accessories
- Debian Reference—A guide with a detailed explanation of the Debian Linux distribution and how programmers can contribute to its development.
- File Manager—This is called PCManFMfile and it provides a graphical browser for files stored on the Pi or any connected storage device.
- Image Viewer—This is called the GPicView and it’s the image viewer for the OS. The image can be from a digital camera or on a connected storage device.
- Leafpad—Notepad for the Raspian and is used for quick notes and some simple programs
- LXTerminal—This LXDE terminal package allows you to use the Linux command line in a window without leaving the graphical user interface.
- Root Terminal—Similar to LXTerminal, the Root Terminal automatically logs you in as the root super-user account in order to carry out system maintenance tasks unavailable to a regular user account.
- Xarchiver—If you need to create or extract compressed files, such as ZIP archives, this is the tool for the job.
- Education
- Scratch— This is a graphical programming language designed for kids, we shall see more about this in a separate section.
- Squeak— This is a platform on which the Scratch runs, you will probably never use this menu entry as we will be using the Scratch to create programs.
- Internet< >Midori—Lightweight but fast web browser which is equivalent to Internet Explorer or a safari on Windows or Mac OSx respectively.<!-- -->Midori Private Browsing—Browse privately to cover your tracks instead of wiping them off later ;). Your browsing history and other details from the site you visit will never be saved<!-- --> NetSurf Web Browser—An alternate web browser to Midori
- Programming
- IDLE—This is an IDE for Python programming language 2.7 version. We shall learn more about using IDLE to write your own Python programs in a separate section in this article.
- IDLE 3—This is another Python IDE but for the version 3. Both version are compatible with each other but some programs specifically require version 3
- Scratch—Same as scratch from education
- Squeak—Same as Squeak from education
- System Tools
- Task Manager— Similar to Task manager from Windows. You can lookup free memory, kill programs that are nagging, see the workload on the processor and so on.
- Preferences
- Customize Look and Feel— Change the appearance of the desktop
- Desktop Session Settings—A tool for changing how the system works when the user is logged in, including what programs are automatically loaded and which window manager the software that draws the borders and title bars of windows is used.
- Keyboard and Mouse—A tool for adjusting input devices. If your keyboard is typing the wrong characters for certain keys, or your mouse is too sensitive, the settings can be altered here.
- Monitor Settings—The resolution that the monitor or TV connected to the Pi runs at can be altered here, although advanced changes require modification of configuration files.
- Openbox Configuration Manager—The LXDEGUI uses a desktop environment called Openbox, which can be adjusted here. Using this tool, you can apply new themes to change the GUI’s appearance, or alter how certain aspects of the interface operate.
- Preferrences.
As most of you already know a File System is the chosen data structure and access methods used by any operating system to store, organize and access files. File System is also used to denote the partitions on the disk that is being used on a machine. Every filesystem has its own method of storing files onto a storage medium [like a hard disk or SD card]. Without these representations which are recognized it would be hard to share file between systems and people.
Logical layout
The Linux way of storing and organizing files is a bit different than that of Windows. Unlike Windows where everything is stored under drives and each drive having a letter, in Linux everything is grouped under a branch under the root file system.
To take a look at what these branches are, open the Terminal on your pi and type the below command.
ls /
As you can see in the above gif image, there are various directories. Some of those directories on the SD Card for persisting files and others are the virtual directories for accessing different portions of the operating system or the hardware. Below are the list of what you see and a short description.
Directory
| Description
|
boot
| Folder for Linux Kernel and other packages necessary to booth/start the Pi
|
bin
| The Raspian related binary files including those for required to run the GUI of the OS
|
dev
| This is one of those virtual directories and this is used for accessing all the connected devices including the storage
|
etc
| Misc config files like encrypted passwords are put in this
|
home
| This is like My documents and each username will get a separate directory under this
|
lib
| Lib= libraries, code required by various applications
|
lost+found
| Dump of pieces of files are stored here when the system crashes
|
media
| Dir for removable storage dives like USB and CD
|
mnt
| Used to mount external hard drives and similar storage devices manually
|
opt
| Optional software directory, any apps that are not part of the OS will go here
|
proc
| Another Virtual directory, this contains info about running processes (programs)
|
selinux
| Security utilities originally developed by our beloved NSA and these are related to Security Enhanced Linux
|
sbin
| System maintenance binaries typically used by the root/superuser
|
sys
| Operating system files
|
tmp
| Temporary files
|
usr
| This is used as storage for user accessible programs
|
var
| Virtual directory that a program can use to persist data
|
Physical Layout
Even though we see all those directories above, if you look at the SD card contents you will see a completely different structure.
For the Raspbian the card will be organized into two sections or partitions.
The first partition is a smaller with around 75 MB and is formatted as VFAT, this is the same format used by Microsoft for the removable drives. This partition is mounted and is accessible by Linux in the /boot directory and this is the folder in which all the files used to configure the Pi and run the OS are stored.
The second partition a larger one and formatted as EXT4, EXT4 is one of the native Linux Filesystems and is considered for its data safety and high speed. This contains the main chunck of the distribution and the programs and user files.
Even though the packaged software that comes with the distribution is enough to start with we will always need to install new software on the operating system for new projects or work.
Installing softwares on the Pi is pretty straight forward and simple process. The tool called apt will help us do these tasks and is the default package manager for the Raspbian. Softwares are addressed as packages in Linux world and hence lets start using the term. Packages are nothing but programs or a collection of programs designed to work together to perform a task.
apt tool can be executed through the command line on the Terminal and there are also GUI based package managers like Synaptic Package Manager built on the apt tool which you could use. For now lets use the command line version as Synaptic eats up a lot of memory. There are three things about software installation, namely Finding a software, installing it and uninstalling it. Lets look at each of them below.
The first step in installing any package would be to find the package by its name. Usually we should search the cache for the available packages and chances are that we find the one we need in there. The Cache is a list of all available packages that can be installed via apt, and are stored on repositories [internet servers]
The apt tool includes a utility for managing this cache called, apt-cache. Using this tool, we could search for a software with a word or phrase.
For example to find all available package managers we can type the below:
apt-cache search package manager
Command is basically telling the apt-cache tool to search for all the packages which has “Package manager” in their title or description. Usually we get a lot of records back and hence it’s better to be as specific as possible. Below is what happens once you execute the command.
As you can see I was not specific enough and ended up with a big list. :)
Once you have chosen the name of the package to be installed, we need to use the apt-get command to install it. Installing is only allowed on a root user and hence the command needs to be run with a sudo prefix to let the OS know that this command is run as a root user.
Let’s chose the package thrust and install the same.
Type the below command
sudo apt-get install thrust
Below is what happens.
Once you have decided to remove a package from the system you use the same apt-get command with remove argument to uninstall a software. Below is the command and the image of how it works.
Sudo apt-get remove thrust
Remove also has a boss named purge. The remove command leaves the config files in the system where as purge would wipe out everything related to the package. Below is the command
sudo apt-get purge thrust
At times we will need to get the latest version for an already installed package. To do this apt-get uses the same install argument. If the package is already installed then it will treat a install command as upgrade and if the latest version is already installed then it will just let you know that the software is already up to date and exit. Below is the command.
sudo apt-get install
Also to upgrade all the softwares on the system at once you could use upgrade argument like below.
sudo apt-get upgrade
Apart from upgrading the packages if you need to get the updated tool of apt-get then use the Update argument like below.
sudo apt-get update
Below is the image showing all three commands above
As we already know Raspbian is preloaded with Python programming language and IDE for the same. I will quickly give a demo for a Hellow world program on Python. Learning Python is a whole different section which I will try covering on a different article. Python is also considered the official language of the Raspberry Pi.
Learning any new computer language typically/traditionally starts with the Hello World program and I really wouldn’t be the one to break the tradition. Below are the steps to write and execute your first “Hello World” Pi-Thon program [pun intended ;) ]
Step1: Click and open the IDLE 3[Phython 3 IDE] from the start menu
Step2: Click on File menu and open a new Window
Step3: Type the below code in your new window
#my first Pi-thon program
print (‘Hello World’)
username = input("What is your name? ")
print (‘Welcome to Pi world, ' + username + ' have a good one!')
Step4: Click save from the file menu and give a name to the file
Step5: Click run from the Run menu or press F5. That’s it. Below is a gif with the above steps demonstrated.
As we saw earlier the GIPO pings on the Pi are used to interface with other input and output devices.
Let’s put together a quick example of switching a Green LED on when there are no new emails in your inbox and a RED led when there are new emails.
We shall use Python as our programming language. To access the GPIO, python provides a library called RPi.GPIO, and this is preinstalled with the Raspian we are using. However, let’s import the library and get the latest version of the library just in case its out of date. Below is the command for the same.
sudo apt-get install RPi.GPIO
Now that we have got our GPIO library installed and lets also install feedparser library which will help parse the feed we get from gmail.
sudo pip install feedparser
Now let’s open a new widow on IDLE and start the below code, first line would be to import all the libraries we need namely
import RPi.GPIO as GPIO, feedparser, time
Now let assign the numbering system for our Pins which we will be using down below
#assign numbering for the GPIO using BCM
GPIO.setmode(GPIO.BCM)
#assingn number for the GPIO using Board
#GPIO.setmode(GPIO.BOARD)
I have commented out the Board numbering mode above as I will be using the BCM numbering for the rest of the example. The difference between BCM (Broadcom SoC numbering) and BOARD mode is that the Board uses the Pins in the exact same way that they are laid out on the board whereas BCM has two different ways for two different versions. Below is a quick image from Meltwater’s Raspberry Pi Hardware to show the different BCM numberings between Revision 1 and 2.
Let us now declare some variables that we shall be using in our program
USERNAME = "YOUR_USERNAME" #just the part before the @ sign, add yours here
PASSWORD = "YOUR_PASSWORD"
NEWMAIL_OFFSET = 0
MAIL_CHECK_FREQ = 2 # check mail every 2 seconds
The logic below will check the feed coming back from Gmail and see if the unread count is greater than 0 then it sets the GPIO GREEN to true, meaning light the GREEN LED.
Else Light the RED LED. Since we have connected the Green LED to pin 18 [BCM number] on the Pi and Red LED to pin 23 the same has been set as intial values of those variables respectively.
GREEN_LED = 18
RED_LED = 23
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)
while True:
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
if newmails > NEWMAIL_OFFSET :
print("You have", newmails, "new emails!")
GPIO.output(GREEN_LED, True)
GPIO.output(RED_LED, False)
else:
print("You have no new emails!")
GPIO.output(GREEN_LED, False)
GPIO.output(RED_LED, True)
time.sleep(MAIL_CHECK_FREQ)
Below is how we would connect the circuit.
Once we run the code below is the result