Raspberry Pi Sensors - Sample Chapter
Raspberry Pi Sensors - Sample Chapter
ee
Sa
pl
Raspberry Pi Sensors
Raspberry Pi is a single-board, credit-card-sized, computer packed with many
opportunities to explore and invent. It is really amazing to see kids start coding
Python from scratch, and build a bird box that streams live video on the Internet
to check whether a bird has got its meal. I remember that when I was a kid, I used
to play with Lego toys attached to DC motors and batteries, which was engaging.
At that time, I could not imagine the logic that went into coding, and did not get
any chance to code my projects and control the movement of those Lego blocks
using a mobile phone. But I am lucky enough now to get an opportunity to explain
such projects and provide a launchpad for young creators who really have a passion
to create something and change the world around us.
The world is moving towards a new era. Technology is revolutionizing daily
needs and habits and making them available on a simple interface, which gave
me motivation to write a book on Raspberry Pi sensors. It's a world of creativity,
and the I believe that creativity comes when you start understanding and appreciating
the fundamentals and start applying logic to it. A lot of information and projects
on Raspberry Pi are floating on various webpages, and one wishes to achieve as
much as he/she can. I feel that the information on webpages is often observed as
incomplete. It gives us a quick start to build projects but does not explain what is
behind them.
It is known that without actually diving too deep into electronic devices and
communication protocols, you can start coding on Raspberry Pi and craft amazing
projects. I have colleagues around me who often need to code and wire the sensors
on the Raspberry Pi platform for their experiments. They can develop Python code
on artificial neural networks in a short span of time, but when it comes to wiring
something, they look around. I believe that a basic understanding of electronics is
a plus for such prodigies out there, who want to develop code on such platforms.
In the opposite scenario, hardware developers can wire sensors, ensures proper
voltage levels on device pins, but when it is time to code, they need help.
The most interesting thing that I find with the Raspberry Pi is that I can still play
with the hardware components and soldering iron, and code my hardware to make
it live. This book provides a kick start for such creators, who really want to know
how things work together, and want a direction for starting projects on sensor
interfacing and the Internet of Things with Raspberry Pi. There is tremendous
growth in technology when we look towards the connected array of everything
around us.
Internet of Things opens up a new world for collecting data and analyzing it for
better user experience. A lot of data from the array of sensors has been generated
from several different sensor nodes. In this context, the Raspberry Pi provides us
with the opportunity to start with simple projects, such as uploading data to the
Internet from a developed sensor station, as described in the chapters of this book.
This will be your first step to building an Internet of Things project. Another
interesting thing is that with the rise of Raspberry Pi 2 model B, developers have
got enough processing power to perform computation-intensive algorithms on the
Raspberry Pi. Therefore, image processing has been included in one of the chapters.
It would have been very difficult to try to explain image processing to beginners,
but I have at least tried to offer a simple start for readers so that they begin image
processing on their own.
This book explores five different projects, any of which can be a startup for different
ways of building electronics projects. The approach I have followed while preparing
the projects is quite interesting. This is the methodology I often follow to develop
complex hardware designs. Although I do not rely on breadboards (as I am more into
high-speed circuit designs), small project prototypes, some of which are covered in this
book, can easily be wired on breadboards. The fist approach should be to purchase the
best hardware components (preferably through hole for breadboard testing), on which
you can rely when the code is not working or not giving the proper results. Prepare
a block diagram and consider each issue that may occur during hardware and firmware
design. Second, read datasheets of components used and ensure every single entity
meets the design requirements. Thirdly, wire the components to the breadboard and
check it thoroughly. Finally, when the hardware is built robustly, write the code (or
firmware), and rewrite it to make it more perfect. Remove the unnecessary variables
and unreachable code or loops, handle interrupts, define the sleep time and watchdogs
of a processor, and manage proper memory segments to avoid crashes. However,
this book has followed mostly simple code that does not go that deep into managing
embedded programming. Installing useful coding libraries on the Raspberry Pi takes
care of the faults often created by a programmer. Just call a function and it does all
the embedded calls in the background. Thanks to the developers of the Raspberry
Pi libraries, with which we build more robust code (whether knowingly or
unknowingly). When you prepare a sample of code, I advise you to break
it down into pieces.
You may face some difficulty when building the project for getting data from
temperature, humidity and light sensors. First, get it done for temperature and
humidity, and then code for the light sensor. Whenever both pieces of code give
you the desired values, recode them. Then you can combine them by managing
the function calls.
When writing the chapters, I have followed a common theme across the book:
first the setup, then the purpose of the project, and finally describing the hardware
with complete details. In some of the chapters, the software has been divided into
components, and then they have been merged so as to avoid monotony for you.
I apologize to you for being lengthy in the theory portion in some parts of this
book, but I am sure that you will love to read and learn a lot from it, and you
can get the most out of it.
Any questions, improvements, and suggestions are welcome,
and should probably take place in the GitHub issues for the book at
https://github.com/rushigajjar/raspberrypisensors
so that everybody can take part. Besides that, anybody can contact me
on LinkedIn at https://in.linkedin.com/in/rushigajjar,
and send messages regarding their interesting projects and startups.
I would really love to hear about it. Or you can send tweets by sharing
temperature and luminance values at @rushigajjar once you get
your air conditioner and lights automated!
Chapter 4, Monitoring the Atmosphere Using Sensors, develops your skills in choosing
a sensor from many that are available in the market. We then implement the hardware
and software required for temperature, humidity, and light sensors to automate our
home appliances.
Chapter 5, Using an ADC to Interface any Analog Sensor with the Raspberry Pi,
explains interfacing of analog-to-digital convertors with an array of sensors. We build
a sensor station for the Raspberry Pi using serial protocols to use the generic software
function built, to get data from any sensor interfaced with it. Finally, the data can be
stored in a log file for analysis.
Chapter 6, Uploading Data Online Spreadsheets, Mobile, and E-mails, takes
a dive into the Internet of Things and sensor nodes. With the help of the sensor station
developed in the previous chapter, we upload the data to online spreadsheets and observe
a real-time graph. We also get emergency e-mails on our e-mail platforms. Once you get
your project done, you can send your sensor values to
[email protected].
Chapter 7, Creating an Image Sensor Using a Camera and OpenCV, covers the basics
of image processing and how an installation of the OpenCV library can be performed
successfully. Using a camera, we will develop an IP camera to install in your backyard
to observe live streaming of activities. Further, we will build a piece of motion detection
code in OpenCV to detect human movement in a particular area and capture an image
for an immediate alert.
Appendix, Shopping List, includes the list of the hardware components that need to be
purchased in order to perform the hands-on tasks described in the book. From chapter 2
onwards, these components will be required to test our codes. You can directly take this
list to the electronics distributors near you and come home with a filled shopping bag!
[1]
Raspberry Pi 1
Models
Processor
BCM2835
Raspberry Pi 2
A+
B+
B
BCM2836
Processor cores
Single
Quad
Speed
700 MHz
900 MHz
RAM
512 MB
256 MB
512 MB
1024 MB
40 pin
40 pin
GPU
VideoCore IV
Pin header
26 pin
40 pin
RCA,
HDMI port
Ethernet port
Yes
No
Yes
Yes
USB ports
Power
Digital interfaces
Memory card
SD
MicroSD
[2]
Chapter 1
Your new friend has all the capabilities that your computer has. The RasPi can
be used to understand how a computer works, to learn programming, for word
processing, and for gaming. Here are the small and shiny hacks that we can do
with RasPi:
Do you want to use RasPi as a web server, where you can run your websites?
Not a problem with RasPi.
Do you have a vacation and want to play video games, such as Minecraft?
You can try using RasPi.
Do you want to use it as your point-and-shoot digital camera while you are
going to visit a zoo this weekend? Easy!
You can even make your own robot or quadcopter using the RasPi. Wow!
[3]
Because of its ability to interact with the outside world, the major applications
developed using RasPi include recognizing the surrounding parameters using
sensors and converting them into useful data to analyze and control the appliances
that we are going to experiment in the upcoming chapters.
I assume that you have the RasPi (model B or B+) in your hand, and you might be
wondering what are the different connectors and electronic elements on the board.
Rather than introducing the jargon of specifications, I will introduce what we need to
make our projects. Take a look at the different connectors in the following diagrams.
The nomenclature presented here will be used throughout the book.
[4]
Chapter 1
GPIO header: GPIO stands for General Purpose Input Output, which has
been brought out to pin connectors present on the board. The processor on
board (BCM283x, which is the brain of a RasPi) has a facility to provide a
specific functionality during the runtime of your own program. We are going
to use them a lot in the upcoming chapters. The great thing with this is that
you can assign a specific task to the specific GPIO in your program, and
while your program executes, it goes to logic low or high (triggers to off state
and on state) accordingly. We can read values from any other peripherals,
such as sensors, and compute the received values in your own programs.
Apart from reading the values, we can show the result of the program by
connecting LEDs or embedded LCD displays to the board. Depending on
the decision taken in the code, we can drive a motor connected on GPIO
through a motor driver circuit. This feature on RasPi makes a huge difference
compared to the normal computing board by giving developers the freedom
of crafting the creation.
[5]
RCA video out: This is the most widely used and one of the oldest
connectors that both old and new televisions or displays use. It carries the
video signal, which is the type output on the RasPi. The RCA connector or
composite video signal is merged with a 3.5 mm audio jack on RasPi 1 model
A+ and model B+ and RasPi 2 model B.
3.5 mm audio out jack: If you are not using the HDMI connection (which will
be described soon), the audio can be played through speakers or headphones
using a standard 3.5 mm jack. In RasPi 1 model B+ or RasPi 2 model B, audio
jack being the combination of composite and audio has all the functionalities
of composite video and audio out.
USB: This is the most common connector, widely used in the modern
computers, and hence called the Universal Serial Bus. You can connect your
flash drives, keyboard, Wi-Fi dongles, and mouse to play around with the
RasPi. You can also connect the externally powered USB hub with RasPi to
connect more USB-based peripherals on it.
CSI camera connector: The RasPi board does not come with camera module
integrated, but a separately bought camera module can be interfaced using
the CSI connector via a 15 cm flex cable. A longer flex cable will lead to
bad quality of images. The 5-megapixel Raspberry Pi camera module can
be used to record high-definition videos as well as still photographs. It's
easy to use for beginners, but has plenty to offer advanced users if you're
looking to expand your knowledge. This camera module provides improved
performance over a USB-connected camera.
Chapter 1
Micro USB power: You survive on food, don't you? Well, so does the RasPi
(kind of). It needs power supply to operate. The device can be powered by
a 5V input voltage, and the current ratings solely depend upon what you
have hooked up with RasPi. Have you seen any power button on RasPi? In
fact, the RasPi module does not have the power on button. Therefore, just
plugging the micro USB power adapter will boot the RasPi.
The maximum current the Raspberry Pi models A and B can use is 1
ampere, so if you need to connect a USB device that will take the power
requirements of the Raspberry Pi above 1 ampere, then you must
connect it to an externally powered USB hub. For example, a USB hard
disk will need an ample amount of current to operate, which RasPi
cannot deliver through the USB port. Alternatively, the maximum
power model B+ can use is 2 amperes before needing to connect
devices to an externally powered USB hub. There are power banks and
batteries available for connecting to the RasPi if you are designing a
remotely operated car or a quadcopter. If you are not sure how much
power the USB device is going to take, buy an externally powered USB
hub. Do not go above 2.4 amperes in any case, because this will destroy
your RasPi if peripheral current demand is highit'll be dead!
SD card slot: The SD card is important because it is where the RasPi keeps its
operating system. It is also where you will store your documents, programs,
and pictures. It is the secondary and a necessary memory part for the RasPi,
the on-board RAM being the primary. Model B requires the standard-sized
SD card (the big one!), whereas model B+ requires the microSD card.
It is suggested to purchase the microSD card with the SD card adaptor
so that if you switch over from RasPi 1 model B to B+ or RasPi 2 model
B, you can retain the same operating systems and your programs.
Additionally, after installing the libraries and setups, the OS crash can
be painful. To avoid this, the periodical backup of the entire OS should
be taken, and this can be used to install the OS on a new SD card again.
The microSD card can easily be contained in an SD adaptor to convert
it into a normal SD card, with no performance losses.
Display connector: Last but not least, the display connector is used to
connect a 7-inch finger-touch LCD display to the board for your embedded
product development. But usually, the RCA and HDMI are enough. If your
application requires this, then you will need to use it.
[7]
[8]
Chapter 1
Windows
These things need to be kept in mind while working on Windows:
Mac OS X
The following things need to be kept in mind while working on Mac OS X:
Write the image on the SD card: Insert an SD card, locate or choose the
downloaded image in the tool, and erase the SD card in the automatically
popped-up menu. Select the continue button to write the image on the
SD card.
Linux
These things need to be kept in mind while working on Linux:
Once you've entered the correct password, you will be able to see the CLI with
pi@raspberrypi~$on your screen, monitor, or TV, which is now ready to take
commands from you. Aye, aye, captain!
[ 10 ]
Chapter 1
[ 11 ]
We have to perform the following steps to enable the Wi-Fi network connection:
1. Go to the network interfaces file of the RasPi by entering the sudo nano /
etc/network/interfaces command in the CLI. Note that you will get
acquainted with these commands in the upcoming sections. Once you enter
the command, the text you need to change is this:
auto lo
iface lo inet loopback
iface eth0 inet static
address 169.254.0.2
netmask 255.255.0.0
broadcast 169.254.0.255
gateway 0.0.0.0
allow-hotplug wlan0
iface default inet dhcp
wpa-ssid "ssid_name"
wpa-psk "password"
Do not forget to put ssid (your network name) and your password
(you know it!) in the quotes.
2. After editing the file, press Ctrl + X and press Y to confirm the edit made
by you.
Shut down the RasPi by entering the sudo poweroff command. You then need to
connect the Wi-Fi dongle and turn it on again. While it is booting up, it finds the
Wi-Fi adaptor connected to it. Pretty simple, isn't it!
[ 12 ]
Chapter 1
For this method, you just need your laptop/desktop (it already
has an inbuilt Wi-Fi module, which is why we don't purchase
an additional Wi-Fi dongle for RasPi until we have a special
requirement), the Windows operating system, and an Internet
connection. You do not need any add-on displays, keyboard,
mouse, or Wi-Fi dongles connected with the RasPi.
So all we need is an Ethernet cable, a power supply to RasPi, the SD card with
Raspbian, a Windows-based PC with an Ethernet port, an SD card reader for the PC
(just required for the first time, either inbuilt or as an add-on SD card reader), and
the RasPi (obviously!).
Assemble all of these on a neat table and just start your laptop without starting up
the RasPi. I will run you through the step-by-step process. If you follow it, you'll
have a working Internet connection provided from your PC to your RasPi with no
added costs of Wi-Fi dongles.
You can change some settings by adding the static IP address of your RasPi at the
end of the line (take a look at the following code). There is no need to understand the
meaning of all of these parameters at this stage; I will introduce them when they will
be useful.
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200
console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline
rootwait ip=169.254.0.2
In bold, you will see the static IP we have provided for the RasPi.
[ 13 ]
From now onwards, you'll always have to access your Pi using this IP
address, when you access it from your PC.
If you are a Linux or Mac OS X user, insert the SD card into the
SD card reader. There will be two partitions visible. Open the boot
partition and follow the same process explained to add the IP address
to the cmdline.txt file.
Save the file, safely remove the SD card from the PC, and move on to the next step.
The ping command allows us to send the predefined size of packets to the host
systems and expects them to be reflected back. The Lost = 0 section in the response
shows that all the packets sent from the PC to the RasPi are reflected back and the
connection is working.
[ 14 ]
Chapter 1
For Linux and Mac OS X users, the connection can be verified by entering the ping
169.254.0.2 command in the terminal. Enter the ping command in the same
Command Prompt to get the Ethernet port IP address of your PC. Following this,
enter ipconfig (ifconfig in the case of Mac OS X and Linux users) and note down
the IP address of the LAN connection (Ethernet), which is 169.254.121.232 in the
following screenshot:
You will be able to see these Ethernet IP addresses only if the RasPi is
in the "powered on" state. Otherwise, you will see no IP address.
Here, the double colon (::) is the most important part to be put between the RasPi's
IP address and your PC's IP address. Then, save the cmdline.txt file.
[ 15 ]
Click on the Sharing tab. Keep the Allow other network users to connect through
this computer's Internet connection option checked and click on OK. This setting
changes the IP address of the Ethernet port of the PC; we need to reset it.
In the same window of the adapter settings, go to the properties of the Local
Area Network connection (Ethernet), double-click on the IPv4 settings, and click
on Obtain an IP Address Automatically as well as Obtain DNS server address
automatically.
The IP address we provide for the RasPi may have a subnet class different
from the network in your home. The interesting point is that this subnet
class remains between the RasPi and PC. Don't panic if the Wi-Fi adapter
of your PC is getting IPs in range of 192.x.x.x. This method still works,
as Windows allows the Internet sharing between cross subnets. This is
because we have enabled the Internet sharing and Ethernet settings as
automatic. Therefore, it is clear that the Wi-Fi-to-PC (192.x.x.x) and
PC-to-RasPi (169.254.x.x) scenarios work successfully.
Mac OS X user can follow the same steps by navigating to Preferences | Sharing and
it would be very easy to follow the GUI.
Linux users can click on network menu in the top panel and navigate to Edit
Connections... and then double click your wired connection and keep the wireless
connection untouched. Navigate to the IPv4 Settings tab and select method: Shared
to other computers.
[ 16 ]
Chapter 1
For Linux and Mac OS X users, there is no need to install the PuTTY
client, as they can directly perform this task from their terminal
window by the ssh [email protected] command.
1. In the Host Name textbox of PuTTY, provide the same IP address that you
entered in cmdline.txt (which is 169.254.0.2, as per the example given in
the previous section).
2. Following this, navigate to Category | Connection | SSH | X11 and check
the Enable X11 forwarding option.
3. In the left-side Category menu, click on Session, enter the session name
in the Saved Sessions field, and save it so that you don't have to save the
settings every time you connect the RasPi with the PC.
4. Double-click on the saved connection and enter the ID and password; you
will get the CLI on the screen of your laptop. Now how do we check the
working Internet connection on the RasPi?
5. The answer to the preceding question is simple; enter the following
command to check the Internet connection:
ping -c 4 www.google.com
You should get the same response with 0 percent packet loss, and now you have a
working Internet connection on your RasPi. All of this is one-time hard work; later
on, if you just have to keep your settings unchanged, log in to PuTTY, and enjoy the
Internet on the RasPi. For the first time, setting up is somewhat a long process, but
you know you've saved almost 10 USD for a Wi-Fi dongle. Isn't that a great thing?
Here is a beautiful tip: you can install Xming from http://www.
straightrunning.com/XmingNotes/, which is an X Windows
System Server. Once it is installed, run it and you should see that there
is no window. Worry not because as soon as you magically input the
command lxsession in PuTTY, you will see the entire desktop of the
RasPi on your PC's screen. A program similar to Xming is VNC Viewer,
which directly opens the desktop of the RasPi by entering the IP address
of the RasPi without logging in from PuTTY. Amazing, right?
[ 17 ]
Chapter 1
In the RasPi, LXTerminal is the tool that is ultimately the terminal for
RasPi. If you are using PuTTY instead of the desktop, PuTTY CLI is the
terminal, ultimately!
sudo: This is an abbreviation of Superuser DO. This command gives you all
privileges of the superuser (root, the most powerful user) of Linux. It is used
in concatenation with other commands such as nano, su, chmod, and so on.
By writing the sudo su command, you can enter superuser mode, in which
you can execute, delete, and create any kind of files in any folders. This really
gives you superpowers in Linux!
The sudo command can be dangerous if not used properly. It can be
used to hack into the Linux systems, or this superpower can allow
you to delete the entire kernel of Linux; keep in mind that next time,
the PC won't boot!
man: This is the command that shows the manual of the Linux commands
and different other function definitions. Type man sudo and you will get all
the details related to the sudo command.
pwd: This is an abbreviation of the present working directory. This shows you
the current directory you are working in. Type pwd and press the Enter key.
This should display something like /home/pi.
ls: This is a command used to list the files or search for some files contained
in a particular directory. Just typing ls and pressing the Enter key will give
you a list of all files contained in the system. The options with ls are -a, -l,
and so on. Just type man ls followed by the Enter key to see the different
[ 19 ]
cd: This command stands for change directory. Just give a path followed by
the cd command and you will be taken to that directory. For example, cd /
home/pi/python_games moves you directly to the python_games folder,
while cd .. takes one step out of a particular directory.
to another.
rm: This removes the specified file (or directory when rmdir is used).
For example, rm gem1.png.
Here's an important warning: files deleted in this way are generally
not restorable.
cat: This lists the content of the file; for example, cat example.sh will
display the content of the example.sh file.
mkdir: This creates the new directory in the present working directory; for
example, mkdir packt will create a directory named packt in the present
working directory. Just use the ls command to check whether it has been
startx: This command provides RasPi users with the user interface for
sudo shutdown -h: This leads to terminate all the processes on the RasPi,
whereas sudo halt stops the CPU from running mode and halts the OS.
The sudo poweroff command safely turns off the RasPi module.
These are the most frequently used commands for the RasPi. If more are needed in
your projects, you will be introduced to them where relevant.
[ 20 ]
Chapter 1
2. Press Ctrl + X to exit and press Y to confirm the exit while also saving the file.
The echo command simply displays the text on the screen of the terminal
when executed; this is similar to the printf command in C, but is really
simple compared to it, right?
3. Now enter the sudo chmod +x example.sh command in the terminal to
provide execution permissions on the example.sh file.
4. Execute the shell program by just typing ./example.sh (./ means a dot
followed by a forward slash, which makes the shell execute the filename that
is after the forward slash).
Notice that this is very short introduction to shell, and now you will learn the useful
commands that will be used throughout the book to create the projects.
[ 21 ]
Before installing any libraries, verify that your operating system has
the latest update. Always check for upgrades and updates by entering
these commands:
sudo apt-get update
sudo apt-get upgrade
git-core
git is a code management system used for collaborative work among programmers
across the world, and it makes tracing change in the code easy. You will find many
libraries and projects on git. If you know the source repository, you can directly get
the library using git-core. Install git-core using this command:
sudo apt-get install git-core
wiringPi
The wiringPi library is created by Gordon, written in C, and provides you with
support to extend your C programs to control the GPIOs. You can easily download
(which will need the Internet connection shared on the RasPi) this library from
Gordon's git core profile by typing the following command:
git clone git://git.drogon.net/wiringPi
The RasPi then downloads the library and creates a folder in the root directory.
Use the cd wiringPi command to change the directory and go to the wiringPi
directory. The next command to be entered is git pull origin, which fetches the
latest version, and then we are ready to build the script using the ./build command.
Now, once the build process is done, we are ready to use the wiringPi library in any
C program we write in the future. To check whether this particular library is working
perfectly, enter these commands: gpio -v and gpio readall. This will convince
you that you have installed it correctly. In Chapter 2, Meeting the World of Electronics,
you will learn how to use wiringPi in shell script and the C language.
[ 22 ]
Chapter 1
python-gpio
The latest distribution of the RasPi comes with python-gpio installed, but this
library will be necessary for those who have an old distribution installed.
The python-gpio library allows you to easily access and control the GPIO pins
while running the Python script. This library can be downloaded from the Python
organization's website, but we will install it using the LXTerminal or PuTTY.
Let's proceed by downloading the .tar file:
wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO0.5.7.tar.gz
If you aren't aware, let me tell you that a TAR file is a kind of bundled file used to
make the download compact and easy. We need to extract the downloaded file in
a directory:
tar -xf RPi.GPIO-0.5.7.tar.gz
Let's rename this folder for ease of use; use this command:
mv RPi.GPIO-0.5.7 python_gpio
Move to the python-gpio directory to install the library using this command:
cd python_gpio
While writing a command, you can use the Tab key, which provides
an autocompletion feature. For example, while writing the cd pyth
command, press Tab. This will autocomplete the command, which will
save the time spent on long filenames. Pressing the Tab key twice will
give you a list of the available commands or filenames.
There is a possibility that it gives you a response that the library is already installed
with the latest version. After this process, if you want to remove the downloaded
file, you can use the rm command and remove it. Finally, one more library that
provides support for the Python Serial Peripheral Interface (SPI) protocol on
GPIO is spidev. You can install it using the following command. You can refer to the
Serial Peripheral Interface section of Chapter 2, Meeting the World of Electronics, to learn
more on SPI protocol. We will be using the SPI protocol in Chapter 6, Uploading Data
Online Spreadsheets, Mobile, and E-mails, when we build the sensor station project to
send sensor data on web pages.
sudo pip install spidev
[ 23 ]
There are many libraries available, but we will install them later in
the upcoming chapters, when the need arises. It is simple to install the
libraries, why wouldn't it be? Linux rocks!
The C programming language offers ample benefits when developing the projects
using already available libraries, such as wiringPi, which can give you full control
of GPIO pins. If you have previously developed a project on C, you can integrate the
wiringPi functions and get the same functionalities as your previous project. Also,
you can simultaneously use GPIO.
Let's play around with both the languages; this will not give you the whole idea of
the programming, but it will give you a good start and will create interest. We will
see both the languages one by one.
[ 24 ]
Chapter 1
Type sudo nano example1.py and you will observe the nano text editor on the
screen. Then type the following code:
name = "World"
name = "Hello " + name
print name
for i in range(3):
print "Whoa"
import this
Now press Ctrl + X and then press Y to save the changes. You will be back to the
Linux CLI. Now type python example1.py. The Python program will be compiled
and the output will be displayed in the same window. One thing you should notice
is that indentation is very necessary in Python. Remove the indentation before
the print "whoa" script and then execute the program; you will find an error of
indentation. In the loops, special care for inserting indentation should be taken
while writing the code. This makes the programs easy to read for people other
than programmers.
Press Ctrl + X and press Y to save the changes. Now it's our turn to compile and
execute the program. The compiler for C programs is always included in the Linux
distribution, which can be cc or gcc. Type this command to compile the C program:
gcc -o example2 example2.c
[ 25 ]
In -o example2, the example2 part will be the name of the output file and the
example2.c part is the file we saved after writing the C program. Press Enter and
check the errors. Correct it by typing sudo nano example2.c and solve it (if any
error occurs). Once it is successfully compiled, type the ls command to check
whether the output file has been created. The output filename will be example2.
You can now type ./example2 to execute the compiled code.
These processes are really helpful in creating sensor projects, and once you practice
more codes, it will be easy for you to understand the process.
Write a program to get all Armstrong numbers below 1000. Note that
among three digit numbers, an Armstrong number is equal to the sum
of the cubes of its digits. For example, 153 is an Armstrong number
because 153 = 13+ 53+33.
Create a calculator that has all the basic functionalities, such as addition,
subtraction, division, and multiplication. Ask the user to select the function
they want. Show an error if they divide anything by zero.
Get a time value from the clock, attach to a Time is string, and display the
current time, for example, Time is 17-Oct-14 10:18:22AM.
[ 26 ]
Chapter 1
The skills acquired by performing these exercises will allow you to better understand
the projects in the upcoming chapters. You can expect an easy programming level
in upcoming chapters. These chapters will focus more on Python and C programs.
Hence, more practice on programs will help you gain a better understanding of the
language and increase logical thinking.
Summary
In this chapter, you learned about the different connectors and functionalities
available on the Raspberry Pi board. We successfully installed the operating system
on the RasPi and shared an Internet connection with it. After these processes, you
learned the basic Linux commands and a glance of the Linux terminal and shell
scripting, which will be used frequently while developing applications and projects.
Then we installed the useful libraries (in the same way as we add a chocolate topping
on top of a vanilla ice cream). A brief introduction to compiling and executing C and
Python programs was given to kick-start work on the Raspberry Pi.
I am sure that you will solve the problems stated at the end of this
chapter to get an idea of how code works. This will help a lot in the
upcoming chapters.
In the next chapter, you will be learning the basics of electronics so that you can
easily develop the projects. These basics are essential for interfacing the sensors.
You will also learn how sensors communicate with the Raspberry Pi. We will run
simple codes to drive LEDs on GPIO pins.
[ 27 ]
www.PacktPub.com
Stay Connected: