You are on page 1of 89

1

Introduction
What this is about and what you gain from it
This book is part of an initiative called DIY Hacking (Do It Yourself!) http://diyhacking.com,
which has been instigated in the hope of inspiring young minds with technology develop-
ment. It aims at imparting pragmatic knowledge through various hands on projects and
tutorials. It provides tutorials in the realm of the latest technologies, for example: one of
the projects published in it – Smart Cap, a DIY Google Glass clone, was even featured on
Techcrunch. Watch the promo video of this book here: https://youtu.be/FntF8EUtie0

Technology prototyping has become so facile and swift today that terms like “Rapid Proto-
typing” is used instead for it. New and powerful open source development platforms like
“Arduino” and “Raspberry Pi” make it easy for even school children to work on robotics
and other fascinating technologies. These technologies have become an inevitable step to
gaining profound knowledge about microcontrollers and microprocessors and hence should
even be made a part of the current academic curriculum.

There are prolific number of communities and forums surrounding these platforms which
allow for quick and easy troubleshooting. Furthermore, beginner tutorials in YouTube are
also very helpful in gaining a better perspective about it. Today, with the advent of 3D print-
ers, now you can even create a custom casing for your project or print your own PCB.

This book will act like a beginner’s guide for you to start prototyping using tools like the Ar-
duino and Raspberry Pi. Moreover, this book has been designed in such a way to promote
self-learning and ingenuity. It is also recommended that you download the eBook version of
this book from: http://maker.diyhacking.com/ebook.html to seemlessly view online videos
and links. So, have fun with this book and good luck on being a Maker!

-Arvind Sanjeev Keep in mind:


ars@diyhacking.com The first step is always to get a good
Founder, DIY Hacking internet connection.
Who is a MAker?
And some other terms you need to know

A Maker is a person who transforms their project from an idea on paper to reality. Anyone
who does this and who uses open source tools for the same can be called a Maker. They
even share their project with the world by posting through online blogs or other platforms
and thereby contributing back to the same open source community which had aided them
initially in their work.

Why you should be a Maker?


Being a Maker is extremely beneficial. Apart from letting you stand in good stead in
your community it can also:
• Help you in building a good work-experience profile, thereby increasing your chanc-
es of getting a good job.
• Help you earn money while in college, by doing part time work for others.
• Help you gain good credibility and even get covered by the media and newspapers.
• Allow you to work on really cool projects while in college/school.
• Keep you updated with the latest technologies around you and help you develop the
skills for building your own.

DIY - Do It Yourself
DIY stands for Do It Yourself. DIY is one of the most popular acronyms used by Makers
today. It emphasizes on the fact that - everything could be made/achieved with your own
effort.

For example: if you want to make an electric car, you can do that yourself today, because
of the resources and tons of information relating to that, which is available on the internet
right now! Don’t believe me? Check out this article and video in it: :

Build an electric car: http://goo.gl/tzQNHJ

3
The DIY phenomenon has created prolific number of communities and projects which al-
lows you to build absolutely anything, using the knowledge from a collective community,
instead of just an individual.

The collaborative and altruistic nature of all the members is the sole reason for its suc-
cess. This means that you can search for queries regarding your project and find innu-
merable solutions or results pertaining to it, instead of relying on an individual.

4
What is Open Source?
Open source means that the original project, its design files or even source code is
made freely available. You can use this free info for building your projects.

Makers rely on both open source hardware like: arduino and raspberry pi and also on
open source software like: python, android OS, etc.

These data are not confined by any patents; instead they are made available for free, so
that Makers and DIYers can build upon these free technologies.

Posting to open source


You only become a true Maker when you post your projects online and contribute back
to the community. Your efforts will in turn help your friends and others in your communi-
ty, just like how you were aided in your initial phases.

Tools like Github, etc are made available for you to post the source code of your project
(https://github.com/). You can view several examples of this at: Instructables :http://
www.instructables.com/and DIY Hacking: http://diyhacking.com

FYI- If you are viewing this eBook in a web browser, please press the Ctrl button while
clicking on the hyperlinks, to open it in a new tab.

5
DIY Projects
Some cool projects you can do later

Arduino Air Drums Project

In this cool DIY, you can see how you can bring an air drum to life by using an arduino.
Check out this cool video to see what I am talking about:
https://www.youtube.com/watch?v=jjvy_jzGlAQ : Youtube Video.

Arduino Coke Can Piano

You won’t find a better use for used coke cans anywhere else. In this DIY, a Maker has
turned a bunch of used coke cans into a really cool and versatile musical instrument.
https://www.youtube.com/watch?v=Ttm62RBdOuo : Youtube Video.
Arduino Passcode Lock for Bikes

The main reason that I did this project was because I always used to keep losing the keys
of my scooter and this resulted in getting a lot of duplicate ones made, each time I loose
one. So after a lot of frustration, I came up with this idea to use a passcode lock system
for my scooter; instead of a keypad lock. Check out this video:
https://www.youtube.com/watch?v=AZ2tjWeCKZY : Youtube Video.

Raspberry Pi Based Head Mounted Display

In this DIY project, I was able to create a cool head mounted display which was capable of
mimicking the functions of a Google Glass, as it had: a head mounted display, voice rec-
ognition and first person video streaming using a webcam. It even got featured on Tech-
crunch. Check out this video:
https://www.youtube.com/watch?v=-sqBGGc_kWw : Youtube Video.
The guide to making it (check it out after you’re finished with this ebook):
http://diyhacking.com/diy-head-mounted-display/ : Smart Cap Tutorial.

7
Raspberry Pi Powered Autonomous Boat

Check out this cool project, where a Maker has used a raspberry pi to create an autono-
mous/remote controlled boat. It even has a camera that streams a live feed from the boat.
https://www.youtube.com/watch?v=vXgNio2lJWU#t=93 : Youtube Video.
The tutorial:
http://goo.gl/mM4p02 : Autonomous Boat Tutorial.

Raspberry Pi Quadrotor

In this project, you can see a quadrotor, which has been built using a raspberry pi. The
system uses IMU sensors and brushless motors for stabilizing and powering the copter.
Check out the video:
https://www.youtube.com/watch?v=Vlv6xCv-Tt0 : Youtube Video.
The tutorial:
http://www.instructables.com/id/Autonomous-Cardboard-Rasberry-Pi-Con-
trolled-Quad/?ALLSTEPS
Raspberry Pi Quadrotor Tutorial. 8
What you will be learning
1. Introduction to Raspberry Pi 11

Technical specifications 13
Introduction to NOOBS 17
Setting up your pi 20
Connecting to the Internet 25

2. Getting started with Scratch 29

3. Python basics 32

4. Introduction to GPIO 35

Blinking an LED 37
PIR motion sensor based automation 38

5. Building a Robot using the Raspberry Pi 40



Interfacing an IR sensor 42
Controlling motors 45

6. Some Raspberry Pi DIY projects 52

7. Beginner’s guide to Arduino 56



Getting technical 59
Hands-on with arduino 62 9
Programming in Arduino 66
Interfacing sensors with Arduino 69
Making your first project 72
Some Arduino DIY projects 76

7. Arduino or Raspberry Pi, which is better? 81

8. Introduction to 3D Printing 84

9. Future Scope and Technologies 86

10
Raspberry Pi
The tiny and super cool mini PC

The raspberry pi is an extremely sleek and tiny computer board. It is about the size of a nor-
mal credit card, and runs on a linux based operating system called the raspbian. This board
can be thought of as a miniaturized version of the motherboard in your CPU. It might not
offer the same powerful processing capabilities as a normal PC, but it gets the job done.
The raspberry pi can be manipulated to turn ON/OFF relays, LEDs, motors, etc using its
GPIO pins and by using python programming (one of the easiest programming languages).

Just like how you need to hook up your CPU to a monitor, keyboard, mouse and LAN. The
raspberry pi also offers USB ports for hooking up a keyboard and mouse, an HDMI (High
Definition Multimedia Interface) port to connect a monitor/TV and an ethernet port to
hook your LAN cable, to gain internet access. And the raspberry pi is powered using a micro
USB port on it (5v, 1A), you can use your normal smartphone charger to connect and power
it.
Just like you have a hard disk on normal computers, the raspberry pi has an SD card that
acts as the hard disk. The OS is loaded into the SD card and plugged into the board. You
can use various memory capacity SD cards: 8GB, 16GB, 32GB, etc.

You can buy these boards online from popular sites like EBay or others for about Rs.2,800
(40$).

Now, check out this cool introduction video about raspberry pi from raspberry pi.org:
https://www.raspberrypi.org/help/what-is-a-raspberry-pi/
Raspberry Pi Introduction Video.

12
Getting Technical with Raspberry Pi
There are different versions of the raspberry pi:
1. Raspberry pi model A
2. Raspberry pi model B
3. Raspberry pi model B+
4. Raspberry pi model B revision 2

However, most of the boards out there are model B+ or 2, so you are more likely to end up
with them. B+ is the most common and updated version of model B, offering four USB ports
and other features. And the Raspberry pi 2 is the latest version that offers 1GB RAM and a
processing power of a quad-core 900MHz processor. The pi 2 is about six times faster than
the pi and even supports windows 10.
The raspberry pi offers USB ports for connecting various peripherals like: keyboards, mouse,
pen drives, webcams, etc. It also offers a LAN port, HDMI, composite video plugs, audio
output jack, GPIO pins, etc. Check out the following diagram:
The basic specifications of the Raspberry Pi A, A+, B, B+ and pi 2 are:

Compute Module
Note: all interfac-
Model Generation 2
Model A Model B Model B+ es are via 200-pin
A+ Model B
DDR2 SO-DIMMcon-
nector.
Target US$30 (in batches of
US$25 US$20[31] US$35[32][33]
price: 100)[34]
Broadcom BCM2835
Broadcom BCM2835 (CPU, GPU, DSP, SDRAM, Broad- (CPU, GPU, DSP,S-
SoC:
one USB port) [1][34] com BCM2836 DRAM, one USBport)
[1][34]

900 MHz quad-
700 MHz single-core
CPU: 700 MHz single-core ARM1176JZF-S[1] core ARM
ARM1176JZF-S
Cortex-A7
Broadcom VideoCore IV @ 250 MHz [35][36]

GPU: OpenGL ES 2.0 (24 GFLOPS)


MPEG-2 and VC-1 (with license),[37] 1080p30 H.264/MPEG-4 AVC high-profile decoder and encoder[1]
512 MB (shared with
Memory 1 GB (shared 512 MB (shared with
256 MB (shared with GPU) GPU) as of 15 October
(SDRAM): with GPU) GPU)
2012
2 (via the on-
USB 2.0 4 (via the on-board 5-port 1 (direct from
1 (direct from BCM2835 chip) board 3-port
ports: [10]
USB hub) [32][39]
BCM2835 chip)
USB hub)[38]
Video 15-pin MIPI camera interface (CSI) connector, used with the Raspberry Pi cam- 2× MIPI camera inter-
input: era or Raspberry Pi NoIR camera[40] face (CSI)[34][41][42]
HDMI (rev
1.3 & 1.4), 14
HDMI reso-
HDMI
HDMI (rev 1.3 & lutions from HDMI (rev 1.3 & 1.4), 14
(rev 1.3
1.4),  14 HDMI reso-
[43] 640×350 to HDMI resolutions from
& 1.4), HDMI, 2× MIPI display
lutions from 640×350 1920×1200 640×350 to 1920×1200
14 HDMI interface (DSI),[34][42]MIPI
Video to 1920×1200 plus plus var- plus various PAL and NTSC
reso- display interface (DSI)
outputs: various PAL and NTSC- ious PAL standards, composite
lutions for raw LCDpanels,[44][45]
standards,[29] composite and NTSC video (PAL and NTSC) via
from composite video[41][46]
video(PAL and NTSC) standards, 3.5 mm TRRS jack shared
640×350
via RCA jack composite with audio out
to
video (PAL
and NTSC)
via RCA jack
Audio
As of revision 2 boards, I²S[47]
inputs:
Audio
Analog via 3.5 mm phone jack; digital via HDMI and, as of revision 2 boards, I²S Analog, HDMI, I²S
outputs:
4 GB eMMC flash
SD / MMC / SDIO card SD / MMC / memory chip;[34] may
On-board
slot (3.3 V with card Mi- SDIO card MicroSD slot or may not support
storage:[10]
power only) slot external SD cards with
configuration changes

14
On-board 10/100 Mbit/s Ethernet (8P8C) USB adapt-
net- None er on the third/fifth port of the USB hub None
work:[10] (SMSC lan9514-jzx)[38]
46× GPIO, some
Low-level 8× GPIO[48] plus the 17× GPIO plus the same
of which can be
peripher- following, which can specific functions, and HAT
used for specific
als: also be used as ID bus
functions includ-
Power 200 mA 700 mA 600 mA 900 mA (4.5 to
300 mA (2.5 W)[52] similar to Model A+
ratings: (1 W)[53] (3.5 W) (3.0 W)[32] 5.5 W)
Power
5 V via MicroUSB or GPIO header 5 V
source:
85.60 mm × 56.5 mm
(3.370 in × 2.224 in) – 85.60 mm × 56.5 mm (3.370 in × 2.224 in) 67.6 mm × 30 mm
Size: 65 mm
not including protruding – not including protruding connectors (2.66 in × 1.18 in)
connectors
23 g
Weight: 45 g (1.6 oz) 45 g (1.6 oz) 7 g (0.25 oz)[54]
(0.81 oz)
Model Generation 2
Model A Model B Model B+ Compute Module
A+ Model B

To view the specifications of the model A, B, B+ and pi 2 and to compare their features,
please check out: http://en.wikipedia.org/wiki/Raspberry_Pi

GPIO (General Purpose Input/Output) pins


While working on your robotics or other kinds of projects with your raspberry pi, the GPIO
pins act as the interface between the board and the external circuit of your project (relays,
LEDs, motors, arduino, etc). Please note that the header configuration is same for both the
B+ and raspberry pi 2.

In order for the board to control these external peripherals, you just need to connect them
to the GPIO pins and write the corresponding python program to power ON/OFF a partic-
ular pin, which consequently turns ON/OFF the device attached to that pin (LEDs, relays,
etc).

You can also connect sensors or other peripherals that communicate using I2C (Inter-Inte-
grated Circuit), SPI (Serial Peripheral Interface) and UART (Universal Asynchronous Receiv-
er Transmitter). The raspberry pi has dedicated GPIO pins for communicating using each of
these protocols as shown above.

15
For more information on using GPIO pins and to learn to connect an LED to it, check this:
http://www.raspberrypi.org/documentation/usage/gpio/

GPIO# 2nd fun pin# pin# 2nd fun GPIO#


- +3V3 1 2 +5V -
GPIO2 SDA1 (I2C) 3 4 +5V -
GPIO3 SCL1 (I2C) 5 6 GND -
GPIO4 GCLK 7 8 TXD0 (UART) GPIO14
- GND 9 10 RXD0 (UART) GPIO15
GPIO17 GEN0 11 12 GEN1 GPIO18
GPIO27 GEN2 13 14 GND -
GPIO22 GEN3 15 16 GEN4 GPIO23
- +3V3 17 18 GEN5 GPIO24
GPIO10 MOSI (SPI) 19 20 GND -
GPIO9 MISO (SPI) 21 22 GEN6 GPIO25
GPIO11 SCLK (SPI) 23 24 CE0_N (SPI) GPIO8
- GND 25 26 CE1_N (SPI) GPIO7
(Models A and B stop here)
EEPROM ID_SD 27 28 ID_SC EEPROM
GPIO5 - 29 30 GND -
GPIO6 - 31 32 - GPIO12
GPIO13 - 33 34 GND -
GPIO19 - 35 36 - GPIO16
GPIO26 - 37 38 - GPIO20
- GND 39 40 - GPIO21
Model B rev 2 also has a pad P6 of 8 pins offering access to an additional 4 GPIO connections. [2]

Function 2nd fun pin# pin# 2nd fun Function


- +5V 1 2 +3V3 -
GPIO28 GPIO_GEN7 3 4 GPIO_GEN8 GPIO29
GPIO30 GPIO_GEN9 5 6 GPIO_GEN10 GPIO31
- GND 7 8 GND -
16
NOOBS - New Out Of Box Software
New Out Of the Box Software or NOOBS is an easy operating system install manager for
the Raspberry Pi. Using this software you will be able to easily select the operating system
of your choice and install it on your Raspberry Pi. The following Operating Systems are cur-
rently included in NOOBS:

• Raspbian
• Pidora
• OpenELEC
• RaspBMC
• RISC OS
• Arch Linux

How to get NOOBS?


NOOBS is already installed in the SD card you received. However, if you want to get a new
one, you can buy an SD card with NOOBS pre installed from online stores. Or you can easily
install NOOBS in an ordinary SD card.

17
Installing NOOBS in your SD card
Like stated earlier, the SD card you received has NOOBS pre installed, so please follow
these steps if you wish to install NOOBS in a new SD card.

Step 1: Download NOOBS


The first step is to download NOOBS from here: http://www.raspberrypi.org/downloads
onto your computer.

Step 2: Format SD card


You need to get an SD card of size atleast 4GB to load NOOBS, however 8GB is recom-
mended. To format the SD card, follow these steps for the respective operating system on
your computer:

WINDOWS
For Windows users we recommend formatting your SD card using the SD Association’s For-
matting Tool, download from: https://www.sdcard.org/downloads/formatter_4/
You will need to set “FORMAT SIZE ADJUSTMENT” option to “ON” in the “Options” menu
to ensure that the entire SD card volume is formatted, and not just a single partition.

MAC OS
The SD Association’s Formatting Tool is also available for Mac users and can be download-

18
ed from: https://www.sdcard.org/downloads/formatter_4/
Although the default OSX Disk Utility is also capable of formatting the entire disk. To do
this, select the SD card volume and choose Erase with MS-DOS format.

LINUX
For Linux users we recommend gparted (or the command line version parted). Norman
Dunbar has written up instructions for Linux users: http://goo.gl/K0us13

Step 3: Copy NOOBS to SD card


Extract the files from the NOOBS zip file that you downloaded in the first step.
Copy the extracted files onto the SD card that you just formatted so that this file is at the
root directory of the SD card. Please note that in some cases it may extract the files into a
folder; if this is the case then please copy across the files from inside the folder rather than
the folder itself.
On first boot the “RECOVERY” FAT partition will be automatically resized to a minimum,
and a list of OSs that are available to install will be displayed.

19
Hands - On with your Raspberry Pi
Before moving on to hooking up your raspberry pi, check out this really cool and short
quick start video from raspberrypi.org:
https://www.raspberrypi.org/help/quick-start-guide/

The tools required for you to begin working on your raspberry pi project are:
1. Raspberry pi model B+
2. A class 4 SD card (minimum- 8GB) with NOOBS software
3. Micro USB smartphone charger
4. USB keyboard
5. HDMI/composite video cable
6. HDMI monitor/TV
7. USB mouse
8. LAN cable and modem for connecting to the internet (optional, but preferred)

The SD card you received has NOOBS pre installed, but if you want to install it in a new SD
card, just follow the steps in the earlier pages to install NOOBS.

Now follow these steps to start using your raspberry pi:


1. Start by plugging in the SD card to your raspberry pi until you hear a click sound as you
insert it.

2. Next, power it using your smartphone charger by plugging the adapter into the micro USB
adapter on the raspberry pi. And then plug in the HDMI to VGA converter (if your monitor
is VGA) or your HDMI cable (if your monitor is HDMI) to the HDMI port on the raspberry pi.

21
3. Now, plug in your USB keyboard and mouse into your raspberry pi through any of the
four USB ports on the pi.

After doing all these steps, now you will see that the monitor or your TV will start loading
the NOOBS software and show you a list of Operating Systems that can be installed in your
raspberry pi. Out of this, Raspbian is the recommended OS for installation. Select Raspbian
and click the install button on top of the window.

22
The installation takes around twenty minutes. After the installation is done, a black screen
with commands comes up. Next you need to enter the username: “pi” with password:
“raspberry” when it asks for it. After that, you can enter the command “startx” and hit
enter, to load the desktop environment and UI (User Interface).

Congrats! You have successfully booted your raspberry pi for the first time.
You can now begin using your raspberry pi like a normal computer, by navigating with the
help of a keyboard and a mouse.
Video guide: https://www.youtube.com/watch?v=y4GOG4P-4tY
Online guide: http://www.raspberrypi.org/help/quick-start-guide/

The Rasbian desktop interface 23


You can even connect your raspberry pi to the display of your laptop after setting up.
Please check this tutorial to do that:
http://diyhacking.com/connect-raspberry-pi-to-laptop-display/

24
Getting internet on your Raspberry Pi
After setting up your raspberry pi, the next thing you need to do is setup internet on your
raspberry pi. After doing this you will be able to surf through Google, and do other great
stuff on the internet just like a normal computer. Follow these steps to get internet on your
raspberry pi. There are mainly two ways to get internet on your raspberry pi:

1. Through LAN (Local Area Network)


Here, you need a LAN cable like this: http://goo.gl/IWT5hQ to connect your raspberry pi
to the internet. This is the easiest way to get internet, as it only requires you to connect
the LAN cable on the ethernet port of your raspberry pi and the other end of the cable
to the modem or router that provides you with the internet connection. You need to
buy the LAN cable from any local electronics store or from online sites.
After doing this, the raspberry pi will get automatically connected to the internet.

LAN cable

2. Through Wifi (Wireless Network)


Here, you need a USB wifi dongle to get internet on your raspberry pi via your local wifi
network. Buy the USB wifi dongle from online sites or local stores. One good dongle you
can use is this: http://goo.gl/xZkQNe
Connect the USB dongle to the USB port on the raspberry pi. After that you need to
configure the internet settings on the Raspberry Pi and add your local wifi network by
entering the network password for it.
Wifi Dongle

Follow these steps to set up wifi internet connectivity on your raspberry pi:

Step 1: Open the Wifi configuration utility


Open up the Wifi configuration utility, the software having the icon as shown below. It can
be found on the desktop or o through the Start menu--> Internet --> wpa_gui

26
Step 2: Scan for networks
After opening the application, you will see an interface like below.

After that, click on the scan button on the window that opened. After which, a new win-
dow will open and then you need to select the network you want to connect to from this
wondow, by double clicking.

27
Step 3: Enter the password
Now, enter the password in the psk field of the new window, like shown below:

Now click save and add the network. After doing this, you will be connected to the internet
and you will see the network that you are connected to, in the main window:

28
Getting started with Scratch on Raspberry Pi
Scratch is a visual programming tool which allows the user to create animations and games
with a drag-and-drop interface. It allows you to create your own computer games, interac-
tive stories, and animations using some programming techniques without actually having
to write code. It’s a great way to get started programming on the Raspberry Pi with young
people. Check this page for more details:
https://www.raspberrypi.org/learning/getting-started-with-scratch/worksheet/

Step 1: Getting started with Scratch


You’ll find Scratch on the desktop of Raspbian and in the applications menu under Educa-
tion. Once opened you will see a window like this:

29
Step 2: Make the scratch cat move
The cat in the white preview window is an example of a sprite in Scratch. Currently the
Scratch cat sprite is on a blank stage. Let’s get the cat to move.

1. Click on the Scratch cat sprite.


2. Then click on the blocks palette and select Control.
3. Next drag a When green flag clicked block and place it on the scripts area in the middle
of the screen.
4. Add a blue Move 10 steps block from the Motion blocks palette and connect it to the
When green flag clicked block.
5. Now click the green flag icon in the top right hand side of the screen and see the cat
move!
6. How would you get the cat to move further?

Step 3: Changing the way the sprite looks


All sprites in Scratch can wear different costumes.

1. Click on your sprite to select it. In the Scripts area in the middle of the screen, click on
the Costumes tab.
2. You will see that the cat has two costumes. Click on Copy to make a third costume and a
new cat costume should appear.
3. Select costume3 and click on Edit. This will open the Paint Editor. Experiment with all
the buttons and tools to find out what they do.
4. Next, draw some clothes on the costume and click OK.
5. To switch between costumes, click on the Scripts tag. Add the purple Looks block,
Switch to Costume, to the other blocks and connect it.
6. Select costume3 from the drop-down menu on the purple block.
7. Now run your program to see the costume change.

30
Step 4: Add sprites
If you feel that the Scratch cat sprite does not suit your needs then you can add other
sprites, or even create your own!

1. At the top of the Sprites palette are three icons to create a new sprite.
2. The first allows you to Paint your own sprite. Click on this and it will open the Paint Edi-
tor window. Here you can use shapes, lines, and freehand drawings to make fun charac-
ters.
3. The second icon allows you to Choose a new sprite from those already built into Scratch
or saved on your Raspberry Pi. Click on this, and you will be able to navigate to the fold-
ers containing those sprites and select one you like.
4. The third icon will, when clicked, give you a surprise sprite. Click this and see what hap-
pens!

Step 5: What’s next?


• Now you know the basics of the Scratch, why not try completing the Robot Antenna
Resource: https://www.raspberrypi.org/learning/robot-antenna/worksheet/ to make
an LED blink.
• Or create a button using candy sweets with the Sweet Shop Reaction Game Resource:
http://www.raspberrypi.org/learning/reaction-game/

31
Python on the Raspberry Pi
Before moving on to learning to program using the python programming language, it would
be useful if you could check out a few basic linux commands, while working on the termi-
nal. You can access the terminal from the Start menu → Accessories → LXterminal.

Check out this video, showing a few basic terminal commands:


https://www.youtube.com/watch?v=sEh-VEGci3k Basic Linux Terminal Commands.
Python is the easiest programming language out there, so you don’t need to hesitate if
you don’t know to use it. It is recommended to be one of the first computer programming
languages to learn, due to its ease of use.
Check out this documentation from the raspberry pi foundation for python beginners:
http://www.raspberrypi.org/documentation/usage/python/

To do a simple “hello world” on python, you can either open IDLE or open the Leafpad text
editor in Accessories, inside the start menu.
In IDLE, you just need to enter:
print “Hello World”

Hello World in Idle

If you are doing it using the Leafpad text editor, type in the above command and then save
the file name as “test.py” (something.py). The “.py” extension is used to mark it as a py-
thon script.
Now, to run this, open the terminal from Accessories and enter the command:
python test.py
It will then print “Hello World”.

33
Now to learn more about python on raspberry pi, check out a few python tutorial videos:
https://www.youtube.com/watch?v=OR5h0UnMcUE
Raspberry Pi Python Tutorial Videos.

Or to learn more about python programming language, check out the several tutorials
available online, like:
https://www.youtube.com/watch?v=cpPG0bKHYKc
Python Tutorial Video Series and http://www.learnpython.org/ and several more!

Next, learn how to blink an LED using a python program and the GPIO pin of a raspberry pi:
http://diyhacking.com/raspberry-pi-gpio-control/
Blinking an LED using the Raspberry Pi.

34
Playing with the GPIO pins on Raspberry Pi

This tutorial, based on the latest Raspberry Pi B+/model 2, will show you to interface a PIR
motion sensor with the Raspberry Pi. And also guides you to use the GPIO pins on it. The
GPIO pins on the raspberry pi are critical when it comes to making a hardware project.
May it be a robot, home automation system, etc. In all these cases you will have to use
the GPIO (General Purpose Input/Output) pins of the raspberry pi. With this simple tuto-
rial, you will be able to learn to control the output on the GPIO pins. And also read inputs
through it. Moreover, you will get to read the output from a PIR motion sensor and also
write a simple code to blink an LED. And if you are a true beginner, you can always use our
free eBook: http://maker.diyhacking.com/eBook.html on Raspberry Pi and Arduino to get
started from step 0. So gear up and get ready to have fun with the Raspberry Pi GPIO s :)

What are the stuff required to do this?


1. Raspberry Pi B/B+ or 2 and basic peripherals: SD card, keyboard, mouse, etc.
2. An LED and 220Ohm resistor.
3. PIR motion sensor: http://www.ebay.in/itm/like/141623663561?aff_source=Sok-Goog
4. Breadboard.
5. Male to male and Female to Male jumper wires.

35
How does this work?
The raspberry pi GPIO can be accessed through a python program. You will get to know
about how to access these pins and the commands required to do that, later in this tutori-
al. Each pin on the raspberry pi is named based on its order (1,2,3,..) as shown in the be-
low diagram:

Here, we are using a PIR motion sensor. PIR stands for Passive InfraRed. This motion sensor
consists of a fresnel lens, a infrared detector and supporting detection circuitry. The lens
on the sensor focuses any infrared radiation present around it towards the infrared detec-
tor. Our bodies generate infrared heat and as a result this gets picked up by the motion
sensor. The sensor outputs a 5V signal for a period of one minute as soon as it detects the
presence of a person. It offers a tentative range of detection of about 6-7 m and is highly
sensitive. When the PIR motion sensor detects a person, it outputs a 5V signal to the rasp-
berry pi through its GPIO. And we define what the raspberry pi should do as it detects an
intruder through python coding. Here we are just printing: “Intruder detected”.

36
Step 1: Blinking an LED using the Raspberry Pi GPIO- Output GPIO control

After you have setup the raspberry pi, we can now start messing around with its GPIO pins.
Here, we will try to blink an LED using a python script. Copy and paste the following code
into your raspberry pi. You can do this by opening the text editor: “leafpad” on the rasp-
berry pi. And then copy this code into it and save this as a python file: ledblink.py :

import RPi.GPIO as GPIO


import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3,GPIO.OUT) #Define pin 3 as an output pin

while True:
GPIO.output(3,1) #Outputs digital HIGH signal (5V) on pin 3
time.sleep(1) #Time delay of 1 second

GPIO.output(3,0) #Outputs digital LOW signal (0V) on pin 3


time.sleep(1) #Time delay of 1 second

Next, we need to connect the LED to pin 3 of the raspberry pi GPIO. You can check out the
connection diagram below for doing that:

3 6

37
You can then notice that the LED starts blinking after you execute the python program.
Using this command: sudo python ledblink.py. The LED blinks since it receives a HIGH (5V)
signal and a LOW (0V) signal from the raspberry pi GPIO at a delay of one second. You can
check out the video below for the demo:
https://youtu.be/L6kq1fBwe3A

Step 2: Interfacing the PIR motion sensor- Input GPIO read

Now, we can try reading the output from the PIR motion sensor. The sensor outputs a digi-
tal HIGH (5V) signal when it detects a person.
You can use this project to build a home automation system. Here, this sensor triggers an
LED ON, instead you can connect it to a relay to control the lights in your home Copy and
paste the following code into your raspberry pi and save it as a python file: pirtest.py:

import RPi.GPIO as GPIO


import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT) #LED output pin
while True:
i=GPIO.input(11)
if i==0: #When output from motion sensor is LOW
print “No intruders”,i
GPIO.output(3, 0) #Turn OFF LED
time.sleep(0.1)
elif i==1: #When output from motion sensor is HIGH
print “Intruder detected”,i
GPIO.output(3, 1) #Turn ON LED
time.sleep(0.1)

38
Now, connect your raspberry pi GPIO to the PIR motion sensor as per the following con-
nection diagram:

You will notice that this code prints:


“Intruder detected” when you place
your hand over the sensor and lights up
an LED. And after removing your hand
and waiting some time, it prints: “No
intruders” and the LED turns OFF.

In certain PIR motion sensors you can


even adjust the delay at which the
sensor outputs a HIGH signal at the ex-
You just need to turn the two knobs on the sensor counter clockwise using a screwdriver.
You can extend the display of your laptop to the raspberry pi via VNC server and a LAN cable
by using this tutorial:
http://diyhacking.com/connect-raspberry-pi-to-laptop-display/.
You can see this sensor in action, in the video below:
https://youtu.be/LocUihLat14
39
Making your first robot with Raspberry Pi

If you are a beginner to Raspberry Pi and were looking for a simple hardware project, then
look no further. This tutorial will show you to develop a python based robot which avoids
obstacles and navigates freely.
Obstacle avoiding robots are fairly common and easy to make. Here, you can use this
project to add object avoidance functionality to your robot. Or simply use it to start mess-
ing around with python and the hardware peripherals on raspberry pi. This system uses
IR modules to detect objects, but we will get to the technical side later. So, if you have a
raspberry pi and want to build something based on hardware using it, just scroll down and
have fun :). Check out the video at the bottom to see how the raspberry pi obstacle avoid-
ing robot works.

40
What are the stuff required to do this?

1. Raspberry Pi B/B+ or 2 and basic peripherals: SD card, keyboard, mouse, etc.


2. IR sensor modules like this: http://goo.gl/Tvdjs1
3. Geared DC motors: http://goo.gl/WI3O35
4. L293D driver board: http://goo.gl/GdjyRW.
5. Robot chassis: http://goo.gl/PZyS4w and wheels: http://goo.gl/043oyQ.
6. Caster wheel: http://goo.gl/Ck3uG8.
7. Breadboard and double side tape.
8. Male to male/Female to male jumpers.
9. 9V Battery and connectors.
10. Push button and 220R resistor.

How does it work?

The entire working of this robot is really simple, nothing to sweat about :) The whole sys-
tem avoids colliding into obstacles thanks to its onboard sensors. Here, this robot uses two
IR sensor modules which can detect objects within a range of 5-6cm. This sensor outputs a
digital LOW (0V) signal when there is an object within its range. And outputs a digital HIGH
(5V) signal otherwise.

41
So how does these IR sensors work? IR stands for Infra Red, which is a wavelength of light
not visible to the human eye (but can be seen through our smartphone cameras!). These
modules consist of a pair of receiver and transmitter IR leds. When an object gets in front
of the IR sensor, the surface of the object reflects a part of the IR light back to the receiv-
er. Thus, the receiver then outputs a LOW signal notifying that an object is in front of the
sensor.

42
These sensors are wired to the GPIO input pins of the raspberry pi. The pi then using a
python script checks whether the GPIO pins connected to the IR sensor modules goes low.
If it does go low, then it commands the DC motors to move in the reverse direction first
and then turn. Moreover, this robot is initially activated when we push the button on the
breadboard, after which the raspberry pi commands the DC motors to move forward via
the L293D driver board. You can check out the demo video at the bottom of this page to
see how this robot works.

Step 1: Connecting the IR Sensors for the raspberry pi obstacle avoiding robot

First, you need to turn ON your raspberry pi after connecting it to the monitor, keyboard,
etc. Then we need to check the IR sensor modules. To do this, connect the IR modules to
your raspberry pi as shown in the diagram on the next page. Power the sensor by provid-
ing 5V (+ pin), GND (- pin) from the raspberry pi. And connect the B pin on the sensors to
raspberry pi’s GPIO pins 3 and 16.

You can check out the raspberry pi GPIO pin out as per the pin diagram above. We are
using the GPIO.BOARD configuration, which means the pins are numbered based on their
normal order on the board (1,2,3,..). Read the pin configuration on the sensor module and
connect correspondingly.

43
2 6

Next, you need to copy and paste the following code and save it as a python file- irtest.py:

import RPi.GPIO as GPIO


import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.IN) #Right sensor connection
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Left sensor connection
while True:
i=GPIO.input(3) #Reading output of right IR sensor
j=GPIO.input(16) #Reading output of left IR sensor
if i==0: #Right IR sensor detects an object
print “Obstacle detected on Left”,i
time.sleep(0.1)
elif j==0: #Left IR sensor detects an object
print “Obstacle detected on Right”,j
time.sleep(0.1)

44
After saving this file and running it: “sudo python irtest.py”. You will notice that when you
block the sensor with your hand, following output gets printed on the screen:

Step 2: Connecting the motors with L293D

After testing the IR sensor modules, next you need to connect and test the L293D module
and the motors. Power the L293D module by connecting the + and – pins of the board to
the 9V battery. Also, connect the “-” of the board to the GND of raspberry pi. You can refer
to the connection diagram here for completing the connections:

45
Next, you have to provide the inputs to the board. Four output GPIO pins from the rasp-
berry pi control the direction of rotation of the two motors. The two terminals of the mo-
tors are then connected to the 4 output terminals of the board. The motors then, based
on the command from the raspberry pi are powered by the 9V battery. The logic for con-
trolling the motors from the raspberry pi is as given below:

Here, HIGH means 5V signal or digital 1 and LOW is 0V signal or digital 0. Eg: GPIO.out-
put(5,1), this command sends a HIGH signal (digital 1) to pin no 5 on the raspberry pi. Thus
each motor’s direction can be controlled by writing HIGH/LOW signals through two GPIO
pins from the raspberry pi.

Next, you need to wire a push button to the raspberry pi as shown in the above connection
diagram. This button is used to activate and de activate the robot. After wiring the robot,
you need to attach the wheels. Use double side tape to fix the parts together on the robot
chassis. After which, you will have a setup that almost looks like this:

46
After connecting the motors you need to check them. Use the code below to check the
motors and the L293D. Make sure you have powered the driver board (L293D) and given
the connections as per the above diagram. After that, copy the code below and save it as
a python file: motor.py on your raspberry pi. Then run it using the command: sudo python
motor.py. You will notice that both the motors rotate in one direction first and then after a
second rotates in the opposite direction. This process repeats until you interrupt it.

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT) #Left motor input A
GPIO.setup(7,GPIO.OUT) #Left motor input B
GPIO.setup(11,GPIO.OUT) #Right motor input A
GPIO.setup(13,GPIO.OUT) #Right motor input B
GPIO.setwarnings(False)

while True:
print “Rotating both motors in clockwise direction”
GPIO.output(5,1)
GPIO.output(7,0)
GPIO.output(11,1)
GPIO.output(13,0)
time.sleep(1) #One second delay

print “Rotating both motors in anticlockwise direction”


GPIO.output(5,0)
GPIO.output(7,1)
GPIO.output(11,0)
GPIO.output(13,1)
time.sleep(1) #One second delay

Step 3: Uploading the code for the raspberry pi obstacle avoiding robot

After completing all the hardware setup, you need to download and copy this python
program from here: http://diyhacking.com/projects/robot.py to your raspberry pi. You can
view the source code in the next page. This program called: robot.py, when executed using
this command: sudo python robot.py, will bring life to your robot and it will begin moving
when you press the push button. And you will notice how it avoids objects in front of its
sensors and navigates freely.

47
#DIYhacking obstacle avoiding robot. Check out: http://diyhacking.com for the tutorial
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.IN) #Right IR sensor module
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Activation button
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Left IR sensor module
GPIO.setup(5,GPIO.OUT) #Left motor control
GPIO.setup(7,GPIO.OUT) #Left motor control
GPIO.setup(11,GPIO.OUT) #Right motor control
GPIO.setup(13,GPIO.OUT) #Right motor control

#Motor stop/brake
GPIO.output(5,0)
GPIO.output(7,0)
GPIO.output(11,0)
GPIO.output(13,0)

flag=0
while True:
j=GPIO.input(12)
if j==1: #Robot is activated when button is pressed
flag=1
print “Robot Activated”,j

while flag==1:
i=GPIO.input(3) #Listening for output from right IR sensor
k=GPIO.input(16) #Listening for output from left IR sensor
if i==0: #Obstacle detected on right IR sensor
print “Obstacle detected on Right”,i
#Move in reverse direction
GPIO.output(5,1) #Left motor turns anticlockwise
GPIO.output(7,0)
GPIO.output(11,1) #Right motor turns clockwise
GPIO.output(13,0)
time.sleep(1)

48
#Turn robot left
GPIO.output(5,0) #Left motor turns clockwise
GPIO.output(7,1)
GPIO.output(11,1) #Right motor turns clockwise
GPIO.output(13,0)
time.sleep(2)
if k==0: #Obstacle detected on left IR sensor
print “Obstacle detected on Left”,k
GPIO.output(5,1)
GPIO.output(7,0)
GPIO.output(11,1)
GPIO.output(13,0)
time.sleep(1)

GPIO.output(5,1)
GPIO.output(7,0)
GPIO.output(11,0)
GPIO.output(13,1)
time.sleep(2)

elif i==0 and k==0:


print “Obstacles on both sides”
GPIO.output(5,1)
GPIO.output(7,0)
GPIO.output(11,1)
GPIO.output(13,0)
time.sleep(2)

GPIO.output(5,1)
GPIO.output(7,0)
GPIO.output(11,0)
GPIO.output(13,1)
time.sleep(4)

elif i==1 and k==1: #No obstacles, robot moves forward
print “No obstacles”,i
#Robot moves forward
GPIO.output(5,0)
GPIO.output(7,1)

49
GPIO.output(11,0)
GPIO.output(13,1)
time.sleep(0.5)
j=GPIO.input(12)
if j==1: #De activate robot on pushing the button
flag=0
print “Robot De-Activated”,j
GPIO.output(5,0)
GPIO.output(7,0)
GPIO.output(11,0)
GPIO.output(13,0)
time.sleep(1)

This program is really simple. The robot is activated when the user presses the push but-
ton, after that the robot moves forward and checks whether any obstacles show up in
front of it. Whenever your IR modules detects an object within 5cm in front of it, it tells
the raspberry pi that an object is near it (sending digital LOW signals). Then the pi sends
commands to the motor, making it move in the reverse direction and then turning right/
left and again the robot moves forward by dodging the object. The robot gets de activated
when we press the push button again.
50
After copying the code to your raspberry pi, you can make it truly wireless by using a
smartphone battery bank to power it. And a USB wifi dongle to communicate with it.
You can either extend the display of your laptop via VNC server and a LAN cable by us-
ing this tutorial: http://diyhacking.com/connect-raspberry-pi-to-laptop-display/. Or
use SSH to connect remotely to your pi from the terminal wirelessly using this tutorial:
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-6-using-ssh. And finally, check out
the video showing the raspberry pi obstacle avoiding robot in action:

https://youtu.be/cRIH-ZkM_oc

51
Some Raspberry Pi DIY Projects
Raspberry pi powered arcade gaming table

Check out this really cool application of using a raspberry pi to power an arcade gaming
table. Hook up your pi to a gaming joystick and some buttons to create an arcade gaming
table.
Check it out in action:
https://www.youtube.com/watch?v=e66lx_bQ4ro Youtube Video.
Tutorial: http://www.instructables.com/id/Raspberry-Pi-Arcade-Table/
Instructables Tutorial.

Video streaming robot using the raspberry pi


Use a webcam with your raspberry pi and make a cool robot which streams video wirelessly.
It can be used to create a surveillance robot and even to send it through hard to reach plac-
es to detect blockages in air vents, etc. Watch it in action: https://youtu.be/z3361LosqI4
Tutorial: http://diyhacking.com/raspberry-pi-webcam-robot/
Home automation using Internet of Things

Check out this tutorial to learn how to control the lights or other appliances in your room
through the internet. Watch it in action:
https://www.youtube.com/watch?v=0y_IFptCZDA
Youtube Video.
Tutorial: https://www.youtube.com/watch?v=0y_IFptCZDA
DIY Hacking Tutorial.

And several more, available on http://diyhacking.com/ and on the internet.


Raspberry Pi Based Head Mounted Display

In this DIY project, I was able to create a cool head mounted display which was capable of
mimicking the functions of a Google Glass, as it had: a head mounted display, voice rec-
ognition and first person video streaming using a webcam. It even got featured on Tech-
crunch. Check out this video:
https://www.youtube.com/watch?v=-sqBGGc_kWw : Youtube Video.
The guide to making it (check it out after you’re finished with this book):
http://diyhacking.com/diy-head-mounted-display/ : Smart Cap Tutorial.
53
Raspberry Pi Powered Autonomous Boat

Check out this cool project, where a Maker has used a raspberry pi to create an auton-
omous/remote controlled boat. It even has a camera that streams a live feed from the
boat.
https://www.youtube.com/watch?v=vXgNio2lJWU#t=93 : Youtube Video.
The tutorial:
http://goo.gl/mM4p02 : Autonomous Boat Tutorial.

Raspberry Pi Quadrotor

In this project, you can see a quadrotor, which has been built using a raspberry pi. The
system uses IMU sensors and brushless motors for stabilizing and powering the copter.
Check out the video:
https://www.youtube.com/watch?v=Vlv6xCv-Tt0 : Youtube Video.
The tutorial:
http://www.instructables.com/id/Autonomous-Cardboard-Rasberry-Pi-Con-
trolled-Quad/?ALLSTEPS
Raspberry Pi Quadrotor Tutorial. 54
Additional Resources and Tutorials
Raspberry Pi Tutorial Series
Check out these tutorial videos on raspberry pi, to learn more about it in detail:
https://youtu.be/OR5h0UnMcUE?list=PLFA4eZ_bEubl_zVY-Dikk7Rpttk2xeWFv
Raspberry Pi Youtube Tutorial Series.

Support and guidance


There is tons of support available for raspberry pi on the internet. Hence, whenever you are
facing an error or need to troubleshoot, you can search for it online and find solutions for it
from people who have been in the same situation.

You can also post your queries on http://www.raspberrypi.org/forums/, to get solutions


from experts on raspberry pi.
Arduino
The easiest electronics development platform

What is Arduino?
Arduino is an open source microcontroller board designed for quickly prototyping an elec-
tronic project. It is an embedded electronics platform, which uses a programming language
comprising of simple and easy C/C++ functions. It is a perfect tool that can be used for
working on your school/college projects or to quickly prototype a cool product idea.

Arduino is usually interfaced with various sensors like: motion sensors, temperature sen-
sors, etc, either individually or collectively and whose output signals act as an input to ar-
duino, based on which we can program it to do certain tasks. To understand the basic logic
flow model for arduino, consider the following example:
Suppose that we have connected a temperature sensor (LM35) to arduino and our ob-
jective is to turn ON the air conditioning when the temperature exceeds 27C/80F. For the
arduino to do that, we program it using the following logic:

if(temperature>27)
{
Turn ON the AC
}
else
{
Turn OFF the AC
}

The programming jargon used for “Turn ON the AC” and “Turn OFF the AC” will be ex-
plained in detail later.

Now, to get a basic understanding of what arduino is all about and to see some projects
that are built using it, watch this video:
https://www.youtube.com/watch?v=CqrQmQqpHXc
Arduino Introduction Video.

The video above initially alludes different sensors such as:


• Photoresistor or LDR (Light Dependent Resistor) - To measure the intensity of light.
• Motion sensor- To detect the presence of a person in a room (using the infra red
radiations from our body).
• GPS (Global Positioning System) sensor- To track something in an outdoor environ-
ment using latitude and longitude coordinates.

The video also demonstrates the working of a project where: the lights in a living room
switch off when you turn ON the TV. This is done using an IR (Infra Red) sensor, which
detects the signals coming off from the IR LED of the TV remote. The arduino reads these
signals through an IR sensor and commands the lights to be turned OFF/ON depending on
these signal values.

You can do all sorts of cool stuff like this, arduino makes it pretty easy. Most of the projects
that are built using arduino are even posted as open source with detailed tutorials on plat-
forms like Instructables, DIY Hacking, etc.

57
Note- Arduino boards come in various forms and types, a few of them are:
• Arduino Uno
• Arduino Due
• Lilypad Arduino- Can be integrated into clothing.
• Arduino Mega- For extra pins and more muscle.

There are also several arduino clone boards like the freeduino, which offer the same func-
tionalities as the arduino, but at a cheaper price (Rs.800 or approx 9$). These boards differ
only in appearance; their functions and working are all the same. You can buy these boards
and its sensors online from popular sites like eBay or others. Moreover, you can even make
your own arduino boards at home.

Reference link: http://arduino.cc/en/Main/Products?from=Main.Hardware

58
Getting Technical with Arduino
Some of the chief components that make up the arduino are:

• ATMega328 Microcontroller
ATMega328 is the brain of Arduino, all the programming and software associated
with arduino is loaded inside this. It offers 32 KB of program memory and runs at 5V.

• FTDI (Future Technology Devices International) USB Chip
This chip is responsible for converting the USB signals (from the PC) into serial UART
signals, understandable by arduino.

• Voltage Regulator
This chip is used to provide a constant 5V power supply to the arduino from the
power jack. Arduino can also be powered alternatively through the USB cable.

• Clock Crystal
The 16 MHz crystal is used as the clock to arduino, it is imperative for applications
relating to timing, etc.

• Reset Button
To reset a program running on the arduino, that is to make it run from the begin-
ning.

• Digital Pin headers
Digital pins are present for digital control applications and to interface with digital
sensors respectively.

• Analog Pin headers
To interface with analog sensors, it can also be used as GPIO (General Purpose Input/
Output) pins.

For more information, please check out: http://www.arduino.cc/en/Reference/Board


Pin Assignments
To connect a sensor or a motor to an arduino, you need to connect them to its pins. Hence,
you’ll be using them for all your projects. The three different types of pins and their uses
are:

1. Power Pins
These are the set of 6 pins on the lower left side of the board as in the figure above. The
ones you would use most frequently from these are:

• 5V
To provide a 5V output power supply to your sensors, motors, LEDs or other
components you connect to arduino. The arduino supplies the power to these exter-
nal peripherals.

• GND
Every component that you connect to the arduino requires a GND (ground) connec-
tion along with the power supply. This pin is used to provide the ground connection
to those external peripherals.

• 3V3
This pin provides 3.3V power supply to external peripherals like sensors, etc, since
some of the sensors work at 3.3V instead of 5V.

60
2. Analog Pins
The six analog pins in the arduino (0-5) are used to connect to analog sensors. These
pins have the capability to convert the analog signals or voltages from these sensors
into digital (in the range 0-1023) using the ADC (analog to digital converter) on the AT-
Mega328. Pins 4, 5 are also used for I2C communication with sensors like IMU (Inertial
Measurement Unit), etc.
Reference link: http://arduino.cc/en/Tutorial/AnalogInputPins

For example: if you need to connect a light sensor (LDR), you connect it to one of the
analog pins. The variations in light intensity are interpreted in the form of voltage varia-
tions from 0-5V, which are converted into the digital range 0-1023, by arduino. 0- being
the lowest intensity of light and 1023- the highest intensity.
Reference video:
https://www.youtube.com/watch?v=d_4R3ZModcs
Arduino LDR Tutorial.

3. Digital Pins
The digital pins in the arduino range from 0-13. These pins are used for connecting LEDs,
motors, or even digital sensors to arduino. These are called as GPIO (General Purpose
Input/Output) pins, since they can be used for either taking inputs from sensors or can
be used to control output devices like LEDs. These pins can provide a maximum of 5V to
power output devices like LEDs or relays.
These pins (0, 1) also support UART communication, to communicate with sensors like
bluetooth, xbee, etc.

61
Hands - On with your Arduino

The following are the stuff you need to have with you, in order to start working on your
arduino project:

1. Arduino or arduino clone board.


2. USB programming cable.
3. Laptop/PC.
4. Arduino IDE (Integrated Development Environment).

First Step - Downloading the Arduino IDE on your Computer

To download the arduino software, go to: http://arduino.cc/en/main/software and select


the latest version of arduino and your respective operating system and download it.

Since the downloaded file is a zip file, you just need to extract it and then click on the ardui-
no application to launch it.

To see this in action, watch this video:


https://www.youtube.com/watch?v=ylPpO-NG2pA
Arduino Installation Video.
The earlier video is just one of the several arduino tutorial videos which are available on
youtube, you can refer them for learning about arduino in detail.

The Arduino IDE

Second Step - Hooking up arduino to your computer

Use the USB cable to connect your arduino to your computer and check to see if the power
light on the arduino is ON.
If you find that the driver is not successfully installed, refer to the video given above to
view the solution.

Now, we need to find the COM port assigned to your arduino (this is a serial port assigned
to each serial device that is connected to your computer).

63
For doing this:

1. First open the arduino IDE and disconnect your arduino from your computer, then
go to: Tools → Serial Port and find out the names of the serial ports listed there and
note them down.

2. Next, connect the arduino to your PC and again go to: Tools → Serial Port and check
to see if a new COM port has come up this time, by comparing with the list you noted
earlier. This new COM port is the one assigned to your arduino.

Furthermore, select your arduino board from: Tools → Board, most of the boards out there
are Arduino Uno, so select Arduino Uno.

Third Step - Loading your First Arduino Program

Now, we’ll try to blink an LED using arduino. There are several example programs available
for the arduino, you can access them from: File → Examples. To program the arduino to
blink an LED, you can view the example program from: File → Examples → Basics → Blink.

This is a video which shows how the program is uploaded to the arduino board and how
the LED is connected to it.
https://www.youtube.com/watch?v=EFp6oE26__k
Arduino LED Blink Video.

64
This is the program code for the above program to blink an LED, “//” represents com-
ments, which are not read during program execution:

void setup() {
pinMode(13,OUTPUT); //assigns digital pin 13 as the output pin
}

void loop() {
digitalWrite(13, HIGH); //sets pin 13 to 5V
delay(1000); //maintains pin 13 at 5V for 1000ms or 1 second.
digitalWrite(13, LOW); //sets pin 13 to 0V
delay(1000); //maintains pin 13 at 0V for 1000ms or 1 second.
}

After uploading this code, by pressing the upload button on the arduino IDE, you will no-
tice an LED blinking on the arduino.
Note - In arduino, by default there is an LED connected to pin 13 on the board, so it’s not
necessary to connect an external LED to it.

Congrats! You have now successfully run your first arduino program.

65
Programming in Arduino
Here, let us consider an example of switching an LED ON using a button switch. The connec-
tions are made as per the following image.

Based on the above example I will be explaining the programming structure in arduino.
Here, we need to find the state of the button press and switch ON the LED accordingly.
Furthermore, if the button is pressed, a HIGH (5V) voltage is passed to the digital pin; else a
LOW (0V) voltage is passed.

The two basic functions that are used in every arduino program are:

• void setup()
This function is used to set up the pins, baud rate, etc of the arduino for a particular
program. It is run only once initially, unlike the void loop(). It is used to define pins
as input/output, set the baud rate for communication, etc.

An example of its use:

void setup()
{
pinMode(2, INPUT); //sets digital pin 2 as INPUT pin for a button switch
Serial.begin(9600); //sets baud rate for communicating with your computer
at 9600bps.
}

• void loop()
This function is the main program loop of arduino. Everything that the arduino is
supposed to do is written inside here. The code written inside this function keeps
repeating again and again until it is programmed over the next time.

Here, digital value 0 indicates no or LOW voltage and digital value 1 indicates HIGH
voltage.

An example of its use:

void loop() {
int button=digitalRead(2); //reads the state of the button switch on pin 2.

if (button == 0) //if the button is not pressed
{
digitalWrite(3, LOW); //turn the LED on pin 3 OFF
}

else if (button == 1) //if the button is pressed
{
digitalWrite(3, HIGH); //turn the LED on pin 3 ON
}

Here, the if-else statements determine whether the LED should be turned ON/OFF.
Thus, when the arduino detects a button press, it turns ON the LED, else switches it
OFF.

67
Some popular functions in arduino:

• digitalRead()
Used to read digital signals from a switch or sensor.
Syntax: digitalRead(1);

• digitalWrite()
Used to output voltages: HIGH (5V) and LOW (0V).
Syntax: digitalWrite(1, HIGH);

• analogRead()
Used to read analog voltage signals from a sensor.
Syntax: analogRead(0);

• analogWrite()
Used to output voltages in the mapped range of 0-1023 (0-5V).
Syntax: analogWrite(1, 700);

• Serial.print()
Used to print or view data from the sensors via the arduino serial monitor.
Syntax:Serial.print(“hello”);

• delay()
To delay the next command for a particular period.
Syntax: delay(1000);

68
Interfacing Sensors with Arduino
LDR (Light Dependent Resistor)
Purpose - To detect intensity of light.
Connection - To arduino analog pins.
Example - It can be used to create an automatic emergency light, which turns itself ON us-
ing an arduino when the lights in a room turn OFF due to power supply failure.
Reference - https://www.youtube.com/watch?v=d_4R3ZModcs
- Youtube Video.

PIR (Passive InfraRed) Motion sensor


Purpose - To detect the presence of a person in a room.
Connection - To arduino digital pins.
Example - It can be used to automatically turn ON the lights in a room, when a person or a
group of people walks inside.
Reference - https://www.youtube.com/watch?v=dv1v00Nytbk
Youtube Video.
Ultrasonic Distance Sensor
Purpose - To detect the distance from nearest object.
Connection - To arduino digital pins.
Example - To build an obstacle avoiding robotic car.
Reference - http://arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor
Arduino Ultrasonic Sensor Tutorial.

70
Force Sensitive Resistor (FSR)
Purpose - To detect the applied force.
Connection - To arduino analog pins.
Example - Can be placed under the door mat, outside your door and used to detect guests
at your home, when they step over the mat.
Reference - https://learn.adafruit.com/force-sensitive-resistor-fsr/using-an-fsr
Arduino Force Sensitive Resistor.

IMU (Inertial Measurement Unit) Sensor


Purpose - To detect movement in 3D space.
Connection - To arduino I2C pins (analog 4,5), other variants use normal analog pins too.
Example - If you have this sensor placed on your hand, you can program arduino to control
a robot or other stuff based on the gestures you make with your hand.
Reference - http://goo.gl/MplSMm
Arduino IMU Sensor.

71
Arduino DIY Project - Auto Lights
Wouldn’t it be cool if we could eliminate darkness? In this beginner arduino project, I have
posted a very simple project that focuses on eliminating darkness.
What it does is that- whenever a room gets dark due to a fused bulb or any other factors, a
light bulb automatically turns ON. This can be used even as an emergency lighting system,
which automatically turns a light ON whenever there isn’t sufficient light in a room.
Here, in order to detect the intensity of light or darkness, we use a sensor called LDR (Light
Dependent Resistor). The LDR is a special type of resistor which allows higher voltages to
pass through it (low resistance) whenever there is high intensity of light and passes a low
voltage (high resistance) whenever it is dark. We can take advantage of this factor of the
LDR and use it in our DIY project. Check this link
https://www.kitronik.co.uk/blog/how-an-ldr-light-dependent-resistor-works/ to know more
about LDR.

What are the stuff required to do this project?

Hardware:
Arduino: http://goo.gl/wdx3bh or an arduino clone board (freeduino).
LDR (you can buy it online or from a local electronics store very cheaply)
5V SPDT Relay:http://www.tenettech.com/product/1655/relay-spdt-sealed
9V Battery and connector
Connecting wires

Software:
http://arduino.cc/en/main/software
Arduino IDE
How does it work?
This system works by sensing the intensity of light in its environment. Here, the sensor that
can be used for detecting light is an LDR, you can buy it from any local electronics store or
online, for a very cheap price.
The LDR gives out an analog voltage when connected to Vcc (5V), which varies in magni-
tude in direct proportion to the input light intensity on it. That is, greater the intensity of
light, greater will be the corresponding voltage from the LDR. Since the LDR gives out an
analog voltage, it is connected to the analog input pin of the arduino. The arduino, with its
inbuilt ADC (Analog to Digital Converter) then converts the analog voltage (from 0-5V) into
a digital value in the range of (0-1023). Thus, when there is sufficient light in its environ-
ment or on its surface, the converted digital values read from the LDR through the arduino
will be in the range of 800-1023.
Furthermore, we then program the arduino to turn ON a relay and hence correspondingly
turn ON an appliance (light bulb), when the light intensity is low (can be done by covering
the surface of the LDR with any object). That is, when the digital values read are in the
higher range than usual.

Step 1: Connecting the components together


First of all, you need to connect the LDR to the analog input pin 0 of arduino. You have to
use a voltage divider configuration to do this. The connection diagram for the arduino is as
given below:

73
Here, one leg of the LDR is connected to VCC (5V) on the arduino, and the other to the an-
alog pin 0 of the arduino, a 100K resistor is also connected to the same leg and grounded.

Step 2: Uploading the code and testing the LDR


Now, after connecting the LDR to arduino, we can check for the values coming from the
LDR via arduino. For this, connect the arduino via USB to your PC and open up the arduino
IDE or software. Now, paste this code and upload it to arduino:

int sensorPin = A0; // select the input pin for ldr


int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
Serial.begin(9600); //sets serial port for communication
}
void loop() {
sensorValue = analogRead(sensorPin); // read the value from the sensor
Serial.println(sensorValue); //prints the values coming from the sensor on the screen
delay(100);
}
After uploading the code, click on the button on the arduino IDE called “Serial monitor“.
This will open a new window, which prints different values on the screen. Now, test out
the sensor, block its surface from light and see what all values you get on the serial moni-
tor. This is how it looks:

74
Step 3: Connecting the relay to arduino
A relay is an electro mechanical switch; it can be used to turn ON/OFF an appliance work-
ing on AC/DC. Here, when the arduino supplies HIGH voltage (5V) to the relay, it turns
it ON (the switch is ON), else it remains OFF. You can learn more about it in detail here:
http://goo.gl/ebnA3l
In this project, we are using a 5V SPDT (Single Pole Double Throw) relay and connecting
one terminal of the coil to arduino digital pin 2, and the other end to GND. We are con-
necting a light bulb to it as well, since we are dealing with high power AC voltages, do
take proper precautions. If you are still confused about connecting a relay to an appliance,
check this link: http://goo.gl/PFWzUN. The overall circuit is now as shown:

After connecting the arduino as shown above, next we need to test it by uploading the
final code to arduino. The final sketch can be found here: arduino code.
http://diyhacking.com/projects/ArduinoNoMoreDarkness.ino
In this sketch, we have set a threshold light value as 700, but it can vary for your projects,
you need to find out the particular value, below which the light bulb should turn ON. This
needs to be done after testing it empirically. So basically, the arduino turns ON the light
bulb (via the relay) whenever the light intensity falls below 700, and when it is above 700,
it turns the light bulb OFF. Finally a video showing it in action:
https://www.youtube.com/watch?v=oqgnAOiZano
Youtube Video.

To know more about this project and others, check out: http://diyhacking.com.

75
DIY Projects
Some cool projects you can do later

Arduino Air Drums Project

In this cool DIY, you can see how you can bring an air drum to life by using an arduino.
Check out this cool video to see what I am talking about:
https://www.youtube.com/watch?v=jjvy_jzGlAQ : Youtube Video.

Arduino Coke Can Piano

You won’t find a better use for used coke cans anywhere else. In this DIY, a Maker has
turned a bunch of used coke cans into a really cool and versatile musical instrument.
https://www.youtube.com/watch?v=Ttm62RBdOuo : Youtube Video.
Arduino Passcode Lock for Bikes

The main reason that I did this project was because I always used to keep losing the keys
of my scooter and this resulted in getting a lot of duplicate ones made, each time I loose
one. So after a lot of frustration, I came up with this idea to use a passcode lock system
for my scooter; instead of a keypad lock. Check out this video:

https://www.youtube.com/watch?v=AZ2tjWeCKZY : Youtube Video.

Secret knock detecting lock


Protect your privacy by making your own intelligent door lock that unlocks based upon a
pre programmed secret knock combination. Watch it in action:

Youtube Video:https://www.youtube.com/watch?v=zE5PGeh2K9k

Tutorial:http://www.instructables.com/id/Secret-Knock-Detecting-Door-Lock/?ALLSTEPS
Instructables Tutorial.

Arduino kitten feeder


Make an automated pet feeder with this easy tutorial. It uses a linear actuator to pass the
correct amount of pet feed.

Tutorial: http://goo.gl/EMeXiY Arduino Kitten Feeder Tutorial.

77
Smartphone controlled robot
Make a really cool android smartphone controlled robot with this tutorial. Use your smart-
phone as a remote control, to control your robotic car. Watch it in action:
https://www.youtube.com/watch?v=LuJ7l4kBp-0
Youtube Video.
Tutorial: http://diyhacking.com/make-android-controlled-robot/
DIY Hacking Tutorial.

And several more, available on http://diyhacking.com/ .


Additional Resources and Tutorials
Arduino Tutorial Series:
Check out this arduino beginner tutorial series to get a feel of working with arduino, there
are several other tutorial series similar to this available on YouTube:
https://www.youtube.com/watch?v=fCxzA9_kg6s&list=PLA567CE235D39FA84#t=0
Arduino Youtube Tutorial Series.

Support and guidance:


Whenever you are beleaguered with errors on arduino, you can always search through
Google for the solution. I can guarantee that there would be several others who would
have faced the same problems/errors and who would have found solutions to it. Hence,
readymade solutions to several of them would already be present in the net.

You can also use arduino forums, to post your queries or doubts regarding arduino, if you
were unable to find an appropriate solution to it: http://forum.arduino.cc/
The Final Step
What is the final step to being a MAker?

A maker is someone who shares their work with the world. They post their projects online
along with videos and pictures, so that other people would also get benefitted by it, just
like how you were able to take advantage of this free information.

If you want to become a Maker or if you already are a Maker, please click this button below.
DIY Hacking will be organizing a bunch of future events including workshops, newslet-
ters, more eBooks, etc for you guys. We will be letting you know about all these activities
through the information you have entered here. We will also be providing a platform for
you guys to post your projects through DIY Hacking. Click this button: http://goo.gl/zCfeSY

I want to be a MAker
There are lots of platforms you can use for posting your projects online, you can either
make your own blog using Google blogspot or even post to DIY Hacking: http://diyhacking.
com to help friends around you, with your knowledge. To post to DIY Hacking, you can con-
tact me at: ars@diyhacking.com and I will be happy to help you out.

You become a true maker or open source contributor, only after posting any of your proj-
ects online. Hence, I strongly encourage you to do the same, that is to give back to the
community and contribute.
Arduino or Raspberry Pi?
Which is the right board for you!

After going through all this information, you might be thinking about which board to use for
your project idea, or which board is better. However, the arduino and raspberry pi are two
completely different boards. It would be like comparing an apple with a banana.
Both these boards excel in their particular fields. To bring a bit more clarity to help you
choose the right board, I will list out a few use cases for each:

Arduino can be used for


• Connecting lots of analog/digital sensors.
• Connecting lots of motors and servos.
• Making a simple and cost effective project.
• Making simple robots like: line followers, obstacle avoiding robots, etc.
• Performing simple logical operations and programs.
Raspberry pi can be used for
• Connecting LCD touch displays and monitors.
• Connecting webcams and performing image processing.
• Running highly complex programs, requiring powerful processing.
• Making internet dependent applications.

In certain applications, you can even use both the boards together. Here, raspberry pi can
do complex stuff like processing, image recognition, etc and then the arduino connected to
the pi via UART can control motors or servos.

To get a better understanding of the differences between arduino and raspberry pi, check
out this video:
https://www.youtube.com/watch?v=7vhvnaWUZjE
Comparing the Arduino and Pi Video.

82
Free DIY Projects
Stay updated on the latest DIY projects

In order to get First and Free access to all latest content from DIY Hacking, including latest
DIY projects (head mounted displays, wearables, Internet of Things, etc), Ebooks, tutorials
and other awesome stuff, you just need to do these two things:

1 .Just LIKE the Facebook page by clicking on the button below:


https://www.facebook.com/diyhacking?ref=bookmarks

Facebook
2. After that on the page, post this message on the wall- “I am a Maker“

I will be adding you to my elite members group through this action and alerting you First on
all other future stuff that might benefit you.
3D Printing
An introduction to 3D printing

3D printing is definitely going to be big, so equipping yourself with the knowledge to use
this, will be a boon for you. 3D printing allows you to make three dimensional objects in
your home using a 3D printer, you might have used a normal 2D printer to print on paper.
But, imagine printing a physical object in 3D.

For those of you, who don’t know what 3D printing is all about, check out this video:
https://www.youtube.com/watch?v=Vx0Z6LplaMU
What is 3D Printing.

For printing objects, you can use design files available online (http://www.thingiverse.com/)
and feed it to the 3D printer for printing that particular object. Or you can even use a 3D
scanner to scan any object you like to replicate.
Sketch up is one of the popular 3D designing softwares available: http://www.sketchup.
com/3Dfor/3D-printing
For example: I recently broke the handle on the door of my refrigerator, if I have a 3D print-
er, I could just search for design files of similar handles online and then download the file
and print it using a 3D printer. These printers use ABS plastic as the ink to print objects in
3D.

Check out this video of a 3D printer in action:


https://www.youtube.com/watch?v=QnChn7vtWHU
Live 3D Printing Video.

The future of 3D printing is enormous; it is even used to print human organs, food, weap-
ons, prosthetic limbs and even houses. It can be used for making any physical object or to
even print another 3D printer.
Check out this video showcasing the future scope of 3D printing:
https://www.youtube.com/watch?v=AYRDVMZ3TbY
Future of 3D Printing Video.

85
The Future
Few examples of the technologies of tomorrow

The future holds many exciting technologies. They range from drones and robots to even
self-driving cars. Check out a couple of these technologies below.

Some of the most blossoming technologies are those based on drones or UAVs (Unmanned
Aerial Vehicles). The most common of them are quadrotors. Quadrotors are really power-
ful, since they consist of four propelling motors, that allow to carry huge payloads. Check
out these videos, showing the power of quadrotors:

Quadrotor Video 1:https://www.youtube.com/watch?v=w2itwFJCgFQ


Quadrotor Video 2:https://www.youtube.com/watch?v=w2itwFJCgFQ

The future also flaunts self driving car technologies. Audi has already created a prototype
of it, check out this cool auto parking car.
https://www.youtube.com/watch?v=b_m8DqTlOLE
Auto Parking Car.

Robots are also being extensively tested in the military. The future promises to safeguard
the lives of soldiers by using humanoids and other robots for military missions, Check out
this cool video of one such robot:

https://www.youtube.com/watch?v=5FFkDV2NKEY
Military Robots.
About the Contributors
Author - Arvind Sanjeev
Arvind hails from Cochin and is an Electronics
Engineer and Inventor. Following his passion for
electronics and robotics, he has developed many
innovative gadgets, some of them which were
even featured on Techcrunch, BBC, Yahoo, etc.

He has won several accolades for his ingenuity


and the “Most Promising Innovator” award from
Yahoo-Accenture being one of them.

He aspires to shorten the gap between the tech-


nological resources available in India to those
possessed by its counterparts abroad. DIY Hacking
is one of the initiatives he uses to achieve this,
Profile: Personal Profile through information dissemination. He also thanks
Blog: Personal Blog his parents (Dr.Sanjeev and Dr.Usha) in supporting
Follow him on Twitter: @ArvindSanjeev him in all of his initiatives.

Illustration - Nidhiya V Raj


Nidhiya is a student entrepreneur, open source
enthusiast and Mozillian based in Cochin. She
runs a startup company with her six classmates.

She is in to software development, UI / UX Design


Strategy and is highly passionate in the field of
electronics.

She has won the Angelhack Hackathon, 2014. You


can find her in organizing many reputable events
as well.
Profile: Personal Profile
Company Profile: Webaccede
Design - Muhammed Shabeer
Muhammed is a multidisciplinary visual art-
ist. He has cofounded the startup- Webaccede
based in Cochin, Kerala and is currently a stu-
dent at Cochin University of Science and Tech-
nology.

He has a profound skill set in designing and mul-


timedia editing. He is also well equipped with an
experience in Nokia App development.

Profile: Personal Profile


Linked in: Profile

Video Promotion - CAT Entertainments


CAT entertainments is an completely inhouse me-
dia production team, with a fully fledged and out-
standingly talented crew. With a vision to create
refreshingly different and artistically significant
visual depictions of various real world scenarios.
The team also boasts an extremely sound and
advanced technical team that allows them to
work in a more streamlined and produce awe-
some innovative interpretations of their projects.

CAT is a media content creation company that


specializes in corporate videos, ad film and TV
shows . Their team of highly talented and cre-
ative individuals strives to deliver high quality
content to their clients in a timely manner.
Company profile: Profile

The layout and illustration for the second eBook ”10 Easy Electronics DIY Projects”, which
will be launched soon has been done by Sahana Rao, a pass out from College of Fine Arts,
Bangalore. Contact: sahana1992.rao@gmail.com

88
Pitch - In
Help me with this initiative by sharing
If you like what I am doing, you can even donate to my cause. You can do so either through
PayPal or can contact me directly at: ars@diyhacking.com
You can also help me in spreading awareness about this initiative, by simply sharing this
free book to your friends, and help get the word out; you can do it through Twitter or Face-
book easily by just clicking below:
http://goo.gl/ieTZdZ
http://goo.gl/hLwOB0

Twitter

Facebook

The text and content on this Ebook is the work of Arvind Sanjeev.
Licensed under the Creative Commons Attribution-ShareAlike License.

You might also like