You are on page 1of 52

KNP COLLEGE OF SCIENCE & TECHNOLOGY, BHOPAL

DEPARTMENT OF CIVIL ENGINEERING


IOT LAB MANNUAL CE-705

Semester-7th

2023-2024

Enrollment No. -
Roll no. -
Submitted By -
Submitted To -
Submitted Date -
Experiment No 1

1. Study and Install IDE of Arduino and different types of Arduino.

OVERVIEW

OBJECTIVEOFTHEEXPERIMENT

This experimental setup is used for installing the different types of arduino IDE

EXPERIMENTALSETUP

Note:BothUSBandDCpowersupplymustbepluggedin.
1. Visit http://www.arduino.cc/en/main/software to download the latest Arduino IDE version for your computer’s

operating system. There are versions for Windows, Mac, and Linux systems. At the download page, click on the

“Windows Installer” option for the easiest installation.

2. Save the .exe file to your hard drive.

3. Open the .exe file.

4. Click the button to agree to the licensing agreement:

5. Decide which components to install, then click “Next”:


6. Select which folder to install the program to, then click “Install”:

7. Wait for the program to finish installing, then click “Close”:

8. Now find the Arduino shortcut on your Desktop and click on it. The IDE will open up and you’ll see the

code editor:
CONFIGURING THE ARDUINO IDE

The next thing to do is to make sure the software is set up for your particular Arduino board. Go to the

“Tools” drop-down menu, and find “Board”. Another menu will appear, where you can select from a list of

Arduino models. I have the Arduino Uno R3, so I chose “Arduino Uno”.

EXPLORING THE ARDUINO IDE

If you want, take a minute to browse through the different menus in the IDE. There is a good variety of

example programs that come with the IDE in the “Examples” menu. These will help you get started with your
Arduino right away without having to do lots of research:
Experiment No 2

2. Write the following program to blink an LED


Overview

Open the arduino IDE and write the following program to blink an LED. I have written the classicLED
blinking example provided in the book Getting Started with Arduino. You may see the screenshot below. After
writing the program you may save it with a file name of your choice (find File–>Save on menu bar of IDE)

STEP 1 – Selecting the board

You have to select the arduino board type in your IDE. I am using an Arduino Uno board. To choose the board, find
Tools on menu bar. Choose the option “Board” – and select your correct arduino board. I have chosen arduino uno. See
the screenshot.
STEP 2 – Select the right port

The port number is assigned while installing the hardware driver of board. You may refer the tutorial
on Installing Arduino on Windows to know how to find the port number of board. You can find the port number
by accessing device manager on Windows. See the section Port (COM & LPT) and look for an open port named
“Arduino Uno (COMxx)“. If you are using a different board, you will find a name accordingly. What matters is
the xx in COMxx part. In my case, its COM5. So my port number is 5. To select the right port, go to Tools–>
Serial Port and select the port number. Refer screenshot below.

Now everything is ready. Your arduino board is ready to communicate with your PC and vice versa. Instructions will be
send to arduino board from your PC. Now lets see how to do that.

There are two steps involved in loading the program from your PC to arduino board via the arduino IDE. First step
is compiling and second step is called burning. Let’s see in detail.

STEP 1:- Compiling –


This is the process of converting the code you have just written in arduino IDE to another form which is only
understood by the micro controller in your arduino board.

In our example, we use arduino uno board. It is made using Avr micro controller (Atmega328).

In the arduino IDE, compiling is called as “verify“. So hit the verify button in your IDE (see the button with tick mark
just below menu bar).

Refer the screenshot given below as well.

When you hit the verify button, the program you have written in arduino IDE will be compiled for any errors and then
converted to another form that Avr Atmega328 understands.

You may refer our article on the Arduino Software and Hardware to know in detail about the language used in
arduino.
STEP 2:- Burning
– Embedded designers use the word “burning” to refer to uploading a program to any micro controller.
So in this step, we are going to upload the verified program in arduino IDE to the arduino board.
To do this, press the “upload” button (see the button with right arrow mark).
A click on the “upload” button will begin the process of burning the compiled program to Avr micro controller on
your arduino board.
Depending on the size of your program, this will take a little time. If you look on your arduino board, you can see the
2 LED’s near Tx and Rx blinking.
This is an indication of successful communication between your PC and arduino board. If the program has been
uploaded successfully, you will see a message like “Done Uploading“.
If the uploading process was not successful, you will see an error message accordingly. Refer the screenshot given
below.
Lets Skim through the Program
Here I am writing the “classic LED blink” program again.
const int LED = 13;
void setup()
{
pinMode(LED,OUTPUT);
}

void loop()
{
digitalWrite(LED,HIGH);
delay(1000);
digitalWrite(LED,LOW);
delay(1000);
}
The arduino uno board comes with a pre installed LED at port number 13.
This is a small SMD LED marked L and you can find it near port 13.
To test the LED blink program, you don’t need to connect a separate LED.
However if you wish so, here is a simple circuit to connect an external LED at port 13.
A 330 ohms resistor is used to limit current in the circuit.
The source supply of +5 volts can be obtained from the USB port of your computer.
Your arduino board will be powered up with +5 volts supply from the PC’s USB port, when you connect board via
cable.
This supply is enough to do simple projects using arduino.
Connect anode of LED to port 13 and cathode of LED to ground pin (you can see GND pin just above port 13) as
shown in circuit diagram, with the resistor in between port 13 and anode of LED.

The first line of the program const int LED = 13; is called an assignment declaration. Here we declare a new variable
with name LED as a constant integer and at the same time we assign the variable to port number 13. From now on,
you can replace port 13 with the variable name LED anywhere in the program.
Experiment No 3

Study the Temperature sensor and Write Program foe monitor


temperature using Arduino.

CONNECT THE CIRCUIT


Connect the thermistor and resistor to your Arduino like this:

The value of the resistor should be roughly equal to the resistance of your thermistor. In this case, the resistance of my

thermistor is 100K Ohms, so my resistor is also 100K Ohms.


The manufacturer of the thermistor might tell you it’s resistance, but if not, you can use a multimeter to find out. If you
don’t have a multimeter, you can make an Ohm meter with your Arduino by following our Arduino Ohm Meter tutorial.

You only need to know the magnitude of your thermistor. For example, if your thermistor resistance is 34,000 Ohms, it

is a 10K thermistor. If it’s 340,000 Ohms, it’s a 100K thermsitor.


CODE FOR SERIAL MONITOR OUTPUT OF TEMPERATURE READINGS
After connecting the circuit above, upload this code to your Arduino to output the temperature readings to the serial

monitor in Fahrenheit:

int ThermistorPin = 0;
int Vo;
float R1 = 10000;
float logR2, R2, T;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;

void setup() {
Serial.begin(9600);
}

void loop() {

Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
T = T - 273.15;
T = (T * 9.0)/ 5.0 + 32.0;

Serial.print("Temperature: ");
Serial.print(T);
Serial.println(" F");

delay(500);
}

To display the temperature in degrees Celsius, just comment out line 18 by inserting two forward slashes (“//”) at the
beginning of the line.

This program will display Celsius and Fahrenheit at the same time:

int ThermistorPin = 0;
int Vo;
float R1 = 10000;
float logR2, R2, T, Tc, Tf;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;

void setup() {
Serial.begin(9600);
}

void loop() {

Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
Tc = T - 273.15;
Tf = (Tc * 9.0)/ 5.0 + 32.0;

Serial.print("Temperature: ");
Serial.print(Tf);
Serial.print(" F; ");
Serial.print(Tc);
Serial.println(" C");

delay(500);
}

CODE FOR LCD OUTPUT OF TEMPERATURE READINGS


To output the temperature readings to a 16X2 LCD, follow our tutorial, How to Set Up an LCD Display on an Arduino,

then upload this code to the board:


#include <LiquidCrystal.h>

int ThermistorPin = 0;
int Vo;
float R1 = 10000;
float logR2, R2, T;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
Serial.begin(9600);
}
void loop() {
Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
T = T - 273.15;
T = (T * 9.0)/ 5.0 + 32.0;

lcd.print("Temp = ");
lcd.print(T);
lcd.print(" F");

delay(500);
lcd.clear();}
Experiment No 4

Controlling relay shield from serial monitor (Arduino IDE)

RELAYSHIELD

OVERVIEW
The Relay shield is capable of controlling 4relays.Them axswitchingpower couldbe 12A/250VAC or 15A/24VDC. It
could be directly controlled by Arduino through digital IOs.

OBJECTIVEOFTHEEXPERIMENT
Controlling relayshield from serial monitor (ArduinoIDE)

EXPERIMENTALSETUP
RELAYSHIELD ARDUINOCODE
/*
* Projectname:
Relayshield-arduino
* Copyright
(c) Researchdesignlab.com
*description:
Controllingrelayshieldfromserialmonitor
*/

char
rec;voidsetup
()
{
pinMode(4,
OUTPUT);pinMode(5,
OUTPUT);pinMode(6,
OUTPUT);pinMode(7,
OUTPUT);Serial.begin(
9600);delay(1000);

Serial.println("=================================");
Serial.println("relays | ON command | OFF
command");Serial.println("=================================");
Serial.println("relay1 1N 1F");
Serial.println("relay2 2N 2F");
Serial.println("relay3 3N 3F");
Serial.println("relay4 4N 4F");
Serial.println("=================================");
}

voidloop()//runoverandover
{
while(!Serial.available());rec=
Serial.read();if(rec=='1')
{
while(!Serial.available());rec=
Serial.read();

if(rec=='N')
{
digitalWrite(4,
HIGH);Serial.println("relay1isO
N");
}
elseif(rec=='F')
{
digitalWrite(4,
LOW);Serial.println("relay1isO
FF");
}
}

elseif(rec=='2')
{
while(!Serial.available());rec=
Serial.read();

if(rec=='N')
{
digitalWrite(5,
HIGH);Serial.println("relay2is
ON");
}
elseif(rec=='F')
{
digitalWrite(5,
LOW);Serial.println("relay2isO
FF");
}
}

elseif(rec=='3')
{
while(!Serial.available());rec=
Serial.read();

if(rec=='N')
{
digitalWrite(6,
HIGH);Serial.println("relay3is
ON");
}
elseif(rec=='F')
{
digitalWrite(6,
LOW);Serial.println("relay3isO
FF");
}
}

elseif(rec=='4')
{
while(!Serial.available());rec=
Serial.read();

if(rec=='N')
{
digitalWrite(7,
HIGH);Serial.println("relay4is
ON");
}
elseif(rec=='F')
{
digitalWrite(7,
LOW);Serial.println("relay4isO
FF");
}
}

ARDUINOIDE–SERIALMONITOR
Experiment No 5
Interfacing a GSM with Arduino
GSMSHIELD

OVERVIEW
This is a very low costand simple Arduino GSM and GPR Sshield.We use the module SIMComSIM900A.

The Shield connects your Arduino to the internet using the GPRS wireless network. Just plug this moduleonto your
Arduino board, plug in a SIM card from an operator offering GPRS coverage and follow a fewsimple instructions to
start controlling your world through the internet. You can also make/receive
voicecalls(youwillneedanexternalspeakerandmicrophone circuit)andsend/receive SMSmessages

OBJECTIVEOFTHEEXPERIMENT
If GAS is detected pin 7 will go LOW and "GAS detected" message will be sent to destination
number.

EXPERIMENTALSETUP

(Note:fortesting,GetacigarettelighterandhalfpressthelighterbuttontospilloutGAS.)
GSMSHIELD
/*
* Project
name:GSMSh
ield
* Copyright
(c) Researchdesignlab.com
*description: IfGASisdetectedpin7willgoLOWand"GASdetected"messagewillbesenttodestinationnumber
*/
voidsetup()
{
Serial.begin(9600); //SERIALCOMMUNICATIONBAUDRATE
pinMode(7,INPUT); //INITIALIZEPIN7FORGASSENSOROUTPUT
delay(5000);
}
voidloop()
{
if(digitalRead(7)==LOW)
{
Serial.println("AT"); //TO CHECK
MODEMdelay(1000);
Serial.println("AT+CMGF=1"); //TOCHANGEMESSAGESENDINGMODE
delay(1000);
Serial.println("AT+CMGS=\"0123456789\""); //CHANGETODESTINATIONNUMBER
delay(1000);
Serial.print("Gasdetected");
//MESSAGEWILLSENTONCEGASISDETECTE
DSerial.write(26);
delay(1000);
}
}
Compile and upload the above code to arduino, then mount the GSM Shield onto arduino board(place
jumperonJP3)andpluginpowersupplyDC12V1A.(removeUSBcable).
Experiment No 6
1. Interfacing a LCD with Arduino

LCD-SCREWSHIELD

OVERVIEW
One of the basic interfacing requirements for the hobbyists or electronics enthusiasts is I/P(keypad) and
O/P (LCD display)for prototype applications. This shield uses minimum number I/O’s thatis 2 bits(D0 and D1) for
LCD data . 5 input key switches (Navigation keys), when it's activated serial datawill be sent to pin D0 by internal
2 line LCD controller. Each key has been pulled up to a differentvoltage level, so a different voltage will be
generated every time a user selects a key. This voltage couldbe read by the analog pin of internal 2 line LCD
controller on the board. Hence saves the no of I/O pins.The backlightoftheLCDcouldbe controlledby
settingPWM(PinD10)by addingafewlinesofcode.

OBJECTIVEOFTHEEXPERIMENT
If Gas is detected by sensor ,”gas detected” message will be displayed in LCD else ”gas
notdetected”messagewill bedisplayedinLCD.

EXPERIMENTALSETUP
(Note:fortesting,GetacigarettelighterandhalfpressthelighterbuttontospillouttheGAS.)
LCDANDKEYPAD-SCREWSHIELDARDUINOCODE
/*
* Projectname:
LCDKEYPADShield
* Copyright
(c)Researchdesignlab.com
* Description:
IfGasisdetectedbysensor,”gasdetected”messagewillbedisplayedinLCDElse”gasnot
detected”messagewillbedisplayedinLCD.

Thecircuit:
* LCDRSpintodigitalpin12
* LCDEnablepintodigitalpin11
* LCDD4 pintodigitalpin5
* LCDD5 pintodigitalpin4
* LCDD6 pintodigitalpin3
* LCDD7 pintodigitalpin2
* LCDR/Wpintoground
* 10Kresistor:
* endsto+5Vandground
* wiperto LCDVOpin(pin3)
*/
#include<LiquidCrystal.h> //includethelibrarycode:
intsensorValue =0; //valuereadfrom thekeypad
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);// initialize the library with the numbers of the interface
pinsintsensorPin= A0;

voidsetup()
{
lcd.begin(16,2); //setuptheLCD'snumberof
columnsandrows:pinMode(7,INPUT);
delay(2000);
}

voidloop(){
lcd.clear(); //clearlcddisplay
lcd.setCursor(0,0); //setthecursorto
column0,line0lcd.print("LCDKEYPADShield");
lcd.setCursor(0,1); //setthecursorto column0,line1

if(digitalRead(7) ==
HIGH)lcd.print("GASDETEC
TED");else
lcd.print("GASNOTDETECTED");
delay(500);
}
Experiment No 7
Study and Configure Raspberry Pi.
Step 1: Gather Materials

We need the following:


The Raspberry Pi itself

 A power supply with a micro USB cable to power the Pi. Get a 2A one if at all possible

 An 4gb SD card. For most cases, there isn't a need for anything larger.

 A USB wifi dongle. There are many of these that are Pi-compatible on the market

 An ethernet cable to go into your home router

Not pictured, but needed: an HDMI monitor with an HDMI cable, a keyboard and some sort of ethernet router than
lets you plug an ethernet cable directly into the back of it.

Step 2: Download Raspbian


Download the latest package here: http://www.raspberrypi.org/downloads

Make sure you double-click the downloaded .zip so that you have a .dmg file. For the
purposes of this Instructable, I leave the .img in my downloads folder.

Step 3: Initialize SD Card Using Disk Utility

Use Disk Utility to initialize your SD card. It doesn't matter what the name of the card is.

What does matter is that the format is MS-DOS (FAT). Format the SD card. It will only take a few seconds.

Quit Disk Utility when you are done.

Step 4: Copy the Raspian Image Onto Your SD Card


Open the Terminal application on the Mac, which will be in your Applications folder.

For those of you unfamiliar with using this app, Terminal provides a command-line for controlling the underlying Unix
operating system on Max OS X.

Type in (then press enter):

diskutil list

This will list all your mounted drives. You will see something like the image above: a list of drives with different
partitions on them. You want to find the information pertaining to your newly-formatted SD card. In my case it
is /dev/disk1s1. This may be different on your computer.

Now, unmount the disk using the Terminal command:


sudo diskutil unmount /dev/disk1s1

The device /dev/disk1s1 is from my setup — yours may be different. Important: use the right device name on your
system.

The preceding sudo command stands for superuser do. These are commands that can wreak havoc if misused, so will
require your Admin password.

You'll be shown a message that your SD card has been unmounted. Its disk image will disappear from the desktop.

Here's where you want to pay close attention. We want to type in a command such as:

sudo dd bs=1m if=~/Downloads/2014-01-07-wheezy-raspbian.img of=/dev/rdisk1

Note that we are using the "raw device", which means that the name /dev/disk1s1 maps to /dev/rdisk1. Make sure you
specify the appropriate raw device, i.e. if your SD device info from diskutil list is /dev/disk3s1, use /dev/rdisk3 for the
dd command.

Also, the filename or path for your wheezy-raspbian.img might be different that the one listed here, so please change it
accordingly.

Terminal will ask you for your admin password since this was a sudo command. Then you will have to
wait long awhile. There is no feedback that any copying is actually happening. This takes something like 30 or 45
minutes. Go have lunch.

Behind the scenes: what the dd command does is copy the disk image and do any necessary conversions.

Once the dd process is done, Terminal will show you how many bytes were transferred to the SD card (about 2.9 gb).
Eject the new SD card, which will be now mounted on your computer and be titled something like boot.

Congratulations, you have a bootable SD card for your Raspberry Pi!

Step 5: Basic Pi Configuration


Put the SD card in your Raspberry Pi, connect the keyboard, connect it to your HDMI monitor and plug in the USB
power. leave the wireless USB dongle disconnected.

You'll see a black screen with a bunch of text, which shows all sorts of configuration details that you don't need to
worry about.

You want to get to a Raspberry Pi configuration screen. Some versions of Raspian will load this screen automatically.
If you don't see this screen — and have to do a login (default user = pi, default password = raspberry), you can still get
to it on the command line, type in:

sudo raspi-config

You'll see the configuration screen only the first time.The options are, and the exact configuration screen may be
slightly different from this Instructable, as the Raspian builds change over time:

1. Expand Filesystem: no need to do this — some may disagree on this point

2. Change User Password: recommended to change this, as using the default password can cause security concerns

3. Enable Boot to Desktop/Scratch: by default, this is set to console, which is what we want to keep

4. Internationalisation Options: set your timezone (if in the US, choose America, then find the correct city with your
timezone)

5. Enable Camera: no (you can always change this later)


6. Add to Rastrack: no
7. Overclock: this is up to you, I usually choose Medium, which makes the Pi run a little bit faster at the expense of
power and potential component damange
8. Advanced options: choose A4 SSH -- this will enable secure shell access, which means that you can control your
Raspberry Pi from a remote computer (extremely useful)

Choose Finish and reboot

When you get to a prompt, enter:

sudo nano /etc/default/keyboard

change XKBLAYOUT to ="us" — assuming you are in the U.S., but you can set this to whatever the keyboard code is
for your country. Here is a list of country codes from Wikipedia, use two-letter lowercase ones.

nano is a simple built-in editor. Type in ctrl-X and Y and overwrite to save the file.

Make these keyboard changes take effect by rebooting:

sudo reboot

Step 6: Setting Up Auto-login


Your Raspberry Pi will be without a keyboard and without a monitor and accessible only by ssh — at least that's the
setup that I'd recommend using. For that reason, we want to set it up to automatically login.

For older installations (pre-Jessie):

After the reboot, at the command line, enter:


sudo nano /etc/inittab

now, scroll down to the line:


1:2345:respawn:/sbin/getty 115200 tty1

and comment it out by putting a '#' in front of it, such as:


#1:2345:respawn:/sbin/getty 115200 tty1

don't worry if the 115200 reads as 38400 or anything like that, we're just looking for the 1:2345 line

now add the line, beneath it:


1:2345:respawn:/bin/login -f pi tty1 /dev/tty1 2>&1

Be super-careful to get the spaces exactly right.

sudo reboot

and the pi should automatically login.

For newer installations (Jessie):

You can set up auto-login through the raspi-config screen

sudo raspi-config

Choose (3) Boot Options


Choose (B1) Desktop / CLU
Choose (B2) Console Autologin

Choose and yes to reboot

Step 7: Download an IP Scanner Package


If you're like me, there is no computer monitor near the ethernet jack. There's ways to get your Raspberry Pi ethernet
address through using commands like ipconfig and hook the Pi directly to a monitor. This technique bypasses the
lugging the monitor around the room.

My preference is to use IP scanning software on my laptop to identify the local IP address of my Raspberry Pi.

My weapon of choice is Angry IP Scanner which is a cross-platform, donation-ware tool. It has been working great on
my Mac.

A note about IP addresses — and this is a broad topic — but the Raspberry Pi will be assigned a local IP address, or one
on your private network. It will be IP-addressable, just like a networked printer, but not able to be directly accessed
outside of your network.

For most of us, these are a 24-bit block of IP addresses in the: 10.0.0.0 - 10.255.255.255 range.
Step 8: Determine the IP Address and Ssh Into It
Connect the hard ethernet jack from the router to your computer and plug in the Raspberry Pi.

In this case, the pi has been assigned to 10.0.1.25, as we can see by the scanner (you'll get an error if you try to ssh into
the other ip addresses). With the scanner packages, make sure to scan in the range of 10.0.1.0 - 10.0.1.255.

What we want to do is to log into it via ssh and finish configuring it for a static and wireless IP address.

Open Terminal and type in.

ssh pi@10.0.1.25

You may have to say "yes" to an authentication screen, but eventually should be able to get in with your password (hint:
the default password is raspberry).

Congratulations, now you can ssh into your Raspberry Pi from any laptop on your network.

Step 9: Run Package Updates


On the command line, type in:
sudo apt-get update

then type in

sudo apt-get upgrade

Both of these commands will give you a lot of gobbledygook. You will wait awhile. Be patient. These update package
lists from the various repositories and updates them to get information on the newest versions of packages and their
dependencies.

when done:

sudo reboot

You'll have to relogin via ssh. Hopefully, the same ethernet address will work, but possibly not, in which case you'll
want to use the IP scanner again.
Step 10: Clone the SD Card

This step is optional and should be used if you are making more than one Raspberry Pi SD card. It will save lots of
time. Otherwise, skip to the next steps on IP configuration.

What we do have is a fully-working Raspberry Pi setup, with auto-login, custom passwords, correct time zone and
keyboard settings. We want to clone this setup so that we can bypass the hassle of going through the set up for each SD
card: auto-login, time zone, updates, etc.

Since the static IP addresses wired & wifi are unique for each card, we will just add these individually.

Remove the SD card from your Pi and put it back into your Mac.

Launch Terminal and type in:

diskutil list

You've seen this before but now we have some slight differences in the partition name for the SD card. We don't
convert to the raw device name this time, just use /dev/disk1

Type in the dd command, like this:

sudo dd if=/dev/disk1 of=~/Desktop/pibootable.img


This will copy the SD card image onto your desktop. For making new RPI SD cards, you would copy this Image onto
your a new SD Card instead of the Wheezy image. You would then be able to proceed directly to the IP configuration
steps.

Step 11: Assigning a Static IP


At this point, you still don't have your wireless USB adapter plugged in. What we ultimately want is a static IP assigned
for every SD card. This way, when we ssh into the Raspberry Pi, we always know which address to use. Also, there
won't be any collisions or confusion on the network.

In theory, you could have a two Raspberry Pis and 10 SD cards. The IP settings will be stored on the SD card itself.

Put the SD card back in your Raspberry Pi.

Connect it with the ethernet cable to your router. Leave the wi-fi dongle disconnected.

Use ssh to get back to logging into your Raspberry Pi, i.e.

ssh pi@10.0.1.25

(or whatever address your IP scanner shows)

Type in:

sudo nano /etc/network/interfaces

You'll see some various settings that look like the image here.

We want to replace the line: iface eth0 inet dhcp


with: iface eth0 inet static

and then specify the address, netmask, network, broadcast and gateway, like this:

iface eth0 inet static


address 10.0.1.64
netmask 255.255.255.0
network 10.0.1.0
broadcast 10.0.1.255
gateway 10.0.1.1

What this is doing is instead of using DHCP, which dynamically assigns IP addresses, it assigns a static one: in this case
it is 10.0.1.64

I picked this one because it is well out-of range of the lower IP addresses, which my network will assign for laptops,
printers, etc. You can use a different IP address, if you want. This is just one that I've chosen that is out of collision
range.

Before you save these changes, keep a copy of the text of the original /etc/network/interfaces file. You can copy-and-
paste this in a text file on your local computer.

note: this is the technique that works on my home network. It may not work on yours, though it has worked for others.

Cntl-X, Y and Return to save and overwrite the file.

Now:

sudo reboot

Fingers crossed. Wait for a few minutes and see if can ssh into this new IP:

ssh pi@10.0.1.64

If asked for the RSA fingerprint, say yes.

If you have troubles, you can use the IP scanner. Real trouble and you might have to do go back to the monitor.

Step 12: Adding Wi-fi Support


At this point, you have a cable running to your Raspberry Pi. If your wi-fi dongle conks out, you can always go back to
the cable. The static IP number will always be the same.

Time to specify the same static IP number for wireless.

Type in:

sudo nano /etc/network/interfaces

You'll see your edited file, like the image here.


find the line:
allow-hotplug wlan0

above it, add:


auto wlan0

then below it add:


iface wlan0 inet static
wpa-ssid "yournetworkname"
wpa-psk "yournetworkpassword"
address 10.0.1.64
netmask 255.255.255.0
network 10.0.1.0
broadcast 10.0.1.255
gateway 10.0.1.1

for wpa-ssid, add your network name


for wpa-psk, add your network password

** Unplug the power from the Raspberry Pi. Plug in your wi-fi dongle. Unplug the cable. Now log in via ssh.

Once again, this work on my network, which uses standard WPA security. If you have a hidden network or additional
security, then you'll have to do a bit more research to get these settings right.

Step 13: Done + Troubleshooting Tips


You're done!
Experiment No 8
WAP for LED blink using Raspberry Pi.

The first step in this project is to design a simple LED circuit. Then we will make the LED circuit
controllable from the Raspberry Pi by connecting the circuit to the general purpose input/output (GPIO)
pins on the Raspberry Pi.

A simple LED circuit consists of a LED and resistor. The resistor is used to limit the current that is being
drawn and is called a current limiting resistor. Without the resistor the LED would run at too high of a
voltage, resulting in too much current being drawn which in turn would instantly burn the LED, and likely
also the GPIO port on the Raspberry Pi.

To calculate the resistor value we need to examine the specifications of the LED. Specifically we need
to find the forward voltage (VF) and the forward current (IF). A regular red LED has a forward voltage
(VF) of 1.7V and forward current of 20mA (IF). Additionally we need to know the output voltage of the
Raspberry Pi which is 3.3V.

We can then calculate the resistor size needed to limit the current to the LED’s maximum forward
current (IF) using ohm’s law like this:

RΩ=VI=3.3–VFIF=3.3–1.720mA=80Ω
Unfortunately 80 ohm is not a standard size of a resistor. To solve this we can either combine multiple
resistors, or round up to a standard size. In this case we would round up to 100 ohm.

Important information: Since ohm’s law tells us that I (current) = V (voltage) / R (ohm) rounding up the
resistor value will lower the actual current being drawn a little. This is good because we don’t want to
run our system at the maximum current rating. Rounding down instead of up would be dangerous, since
it will actually increase the current being drawn. Increased current would result in running our system
over the maximum rating and potentially destroying or damaging our components.

With the value calculated for the current limiting resistor we can now hook the LED and resistor up to
GPIO pin 8 on the Raspberry Pi. The resistor and LED needs to be in series like the diagram below. To
find the right resistor use the resistor color code – for a 100 ohm resistor it needs to be brown-black-
brown. You can use your multimeter to double check the resistor value.
When hooking up the circuit note the polarity of the LED. You will notice that the LED has a long and short lead. The
long lead is the positive side also called the anode, the short lead is the negative side called the cathode. The long
should be connected to the resistor and the short lead should be connected to ground via the blue jumper wire and pin 6
on the Raspberry Pi as shown on the diagram.

To find the pin number refer to this diagram showing the physical pin numbers on the Raspberry

Pi.
Writing the Python Software to blink the LED

With the circuit created we need to write the Python script to blink the LED. Before we start writing the software we
first need to install the Raspberry Pi GPIO Python module. This is a library that allows us to access the GPIO port
directly from Python.

To install the Python library open a terminal and execute the following

$ sudo apt-get install python-rpi.gpio python3-rpi.gpio

With the library installed now open your favorite Python IDE (I recommend Thonny Python IDE more information
about using it here).

Our script needs to do the following:

 Initialize the GPIO ports


 Turn the LED on and off in 1 second intervals

To initialize the GPIO ports on the Raspberry Pi we need to first import the Python library, the initialize the library and
setup pin 8 as an output pin.
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False)# Ignore warning for now
GPIO.setmode(GPIO.BOARD)# Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)# Set pin 8 to be an output pin and set initial value to low (off)
Next we need to turn the LED on and off in 1 second intervals by setting the output pin to either high (on) or low (off).
We do this inside a infinite loop so our program keep executing until we manually stop it.

whileTrue: # Run forever


GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1)# Sleep for 1 second
GPIO.output(8, GPIO.LOW)# Turn off
sleep(1)# Sleep for 1 second
Combining the initialization and the blink code should give you the following full Python program:

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)
whileTrue: # Run forever
GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second
With our program finished, save it as blinking_led.py and run it either inside your IDE or in the console with:

$ python blinking_led.py
Experiment No 9
Study and Implement Zigbee Protocol using Arduino / Raspberry Pi

 Introduction
 Step 1: The shield
 Step 2: A simple example.
 Step 3: Addressing.
 Step 4: Configuring the XBee module.
 Step 5: Jumper settings (Only for Arduino).
 Step 6: Using Series 2 ZB XBee's.
 Step 7: Video-Tutorial.
 Fritzing Libraries
 Links and Documentation

 2 x Arduino Uno or 2 x Raspberry Pi


 2 x Arduino XBee module (any of them) or 2 x Raspberry Pi connection bridge
 2 x Antenna (if the XBees need them)
 1 x PC

XBee shield for Arduino


The Arduino XBee shield allows your Arduino board to communicate wirelessly using Zigbee. It was developed in
collaboration with Arduino. This documentation describes the use of the shield with the XBee module.
XBee in Raspberry Pi
The Raspberry Pi to Arduino shields connection bridge allows your Raspberry Pi to communicate wirelessly using
Zigbee. Setting up the hardware is very easy, just plug the XBee module

Step 2: A simple exampleGo to index

Arduino Example
You should be able to get two Arduino boards with XBee shields talking to each other without any configuration, using
just the standard Arduino serial commands.

To upload a sketch to an Arduino board with a XBee shield, you'll need to put both jumpers on the shield to the "USB"
setting (i.e. place them on the two pins closest to the edge of the board) or remove them completely (but be sure not to
lose them!). Then, you can upload a sketch normally from the Arduino environment. In this case, upload the
Communication | Physical Pixel sketch to one of the boards. This sketch instructs the board to turn on the LED attached
to pin 13 whenever it receives an 'H' over its serial connection, and turn the LED off when it gets an 'L'. You can test it
by connecting to the board with the Arduino serial monitor (be sure it's set at 9600 baud), typing an H, and pressing
enter (or clicking send). The LED should turn on. Send an L and the LED should turn off. If nothing happens, you may
have an Arduino board that doesn't have a built-in LED on pin 13.

Once you've uploaded the Physical Pixel sketch and made sure that it's working, unplug the first Arduino board from
the computer. Switch the jumpers to the XBee setting (i.e. place each on the center pin and the pin farthest from the
edge of the board). Now, you need to upload a sketch to the other board. Make sure its jumpers are in the USB setting.
Then upload the following sketch to the board:
voidsetup(){
Serial.begin(9600);
}

voidloop(){
Serial.print('H');
delay(1000);
Serial.print('L');
delay(1000);
}
Select all
When it's finished uploading, you can check that it's working with the Arduino serial monitor. You should see H's and
L's arriving one a second. Turn off the serial monitor and unplug the board. Switch the jumpers to the XBee setting.
Now connect both boards to the computer. After a few seconds, you should see the LED on the first board turn on and
off, once a second. (This is the LED on the Arduino board itself, not the one on the XBee shield, which conveys
information about the state of the XBee module.) If so, congratulations, your Arduino boards are communicating
wirelessly. This may not seem that exciting when both boards are connected to the same computer, but if you connect
them to different computers (or power them with an external power supply - being sure to switch the power jumper on
the Arduino board), they should still be able to communicate.

Raspberry Pi Example
You should be able to get two Raspberry Pi boards with XBee shields talking to each other without any configuration,
using just serial commands.
In one of the Raspberry Pi boards we will run a code that turn on the LED attached to pin 7 whenever it receives an 'H'
over its serial connection, and turn the LED off when it gets an 'L'. The other Raspberry Pi board will run a program
that sends 'H' and 'L' sleeping 1 second in between.
Code for listening:
Show code
Code:
Select all
Code for sending:
Show code
Code:
Select all
When both programs are running (one on each board) you should see the LED on the first board turn on and off, once a
second.
NOTE: All the code examples in this tutorial developed for Raspberry Pi use the arduPi library. You can see the
documentation and download the library here.
Step 3: AddressingGo to index
There are multiple parameters that need to be configured correctly for two modules to talk to each other (although with
the default settings, all modules should be able to talk to each other). They need to be on the same network, as set by the
ID parameter (see "Configuration" below for more details on the parameters). The modules need to be on the same
channel, as set by the CH parameter. Finally, a module's destination address (DH and DL parameters) determine which
modules on its network and channel will receive the data it transmits. This can happen in a few ways:
 If a module's DH is 0 and its DL is less than 0xFFFF (i.e. 16 bits), data transmitted by that module will be received by
any module whose 16-bit address MY parameter equals DL .
 If DH is 0 and DL equals 0xFFFF, the module's transmissions will be received by all modules.
 If DH is non-zero or DL is greater than 0xFFFF, the transmission will only be received by the module whose serial
number equals the transmitting module's destination address (i.e. whose SH equals the transmitting module's DH and
whose SL equals its DL ).
Again, this address matching will only happen between modules on the same network and channel. If two modules are
on different networks or channels, they can't communicate regardless of their addresses.
Step 4: Configuring the XBee moduleGo to index
You can configure the XBee module from code running on the Arduino board, on Raspberry Pi, or from software on the
computer. To configure it from the Arduino board, you'll need to have the jumpers in the XBee position. To configure it
from the computer, you'll need to have the jumpers in the USB configuration and have removed the microncontroller
from your Arduino board.

To get the module into configuration mode, you need to send it three plus signs: +++ and there needs to be at least one
second before and after during which you send no other character to the module. Note that this includes newlines or
carriage return characters. Thus, if you're trying to configure the module from the computer, you need to make sure
your terminal software is configured to send characters as you type them, without waiting for you to press enter.
Otherwise, it will send the plus signs immediately followed by a newline (i.e. you won't get the needed one second
delay after the +++). If you successfully enter configuration mode, the module will send back the two characters 'OK',
followed by a carriage return.

Send Command Expected Response

+++ OK<CR>
Once in configuration mode, you can send AT commands to the module. Command strings have the form ATxx (where
xx is the name of a setting). To read the current value of the setting, send the command string followed by a carriage
return. To write a new value to the setting, send the command string, immediately followed by the new setting (with no
spaces or newlines in-between), followed by a carriage return. For example, to read the network ID of the module
(which determines which other XBee modules it will communicate with), use the 'ATID command:

Send Command Expected Response

ATID<enter> 3332<CR>
To change the network ID of the module:

Send Command Expected Response

ATID3331<enter> OK<CR>
Now, check that the setting has taken effect:

Send Command Expected Response

ATID<enter> 3331<CR>
Unless you tell the module to write the changes to non-volatile (long-term) memory, they will only be in effect until the
module loses power. To save the changes permanently (until you explicitly modify them again), use
the ATWR command:
Send Command Expected Response

ATWR<enter> OK<CR>
To reset the module to the factory settings, use the ATRE command:
Send Command Expected Response

ATRE<enter> OK<CR>
Note that like the other commands, the reset will not be permanent unless you follow it with the ATWR command.

Here are some of the more useful parameters for configuring your XBee module.
Command Description Valid Values Default Value

ID The network ID of the XBee module. 0 - 0xFFFF 3332

CH The channel of the XBee module. 0x0B - 0x1A 0X0C

SH and SL The serial number of the XBee module (SH gives the high 32 bits, SL 0 – 0xFFFFFFFF different for each
the low 32 bits). (for both SH and module
Read-only. SL)

MY The 16-bit address of the module. 0 - 0xFFFF 0


DH and The destination address for wireless communication (DH is the high 32 0 – 0xFFFFFFFF 0 (for both DH a nd
DL bits, DL the low 32). (for both DH and DL)
DL)

BD The baud rate used for serial communication with the Arduino board or 0 (1200 bps) 3 (9600 baud)
computer. 1 (2400 bps)
2 (4800 bps)
3 (9600 bps)
4 (19200 bps)
5 (38400 bps)
6 (57600 bps)
7 (115200 bps)
Note: although the valid and default values in the table above are written with a prefix of "0x" (to indicate that they are
hexadecimal numbers), the module will not include the "0x" when reporting the value of a parameter, and you should
omit it when setting values.

Here are a couple more useful commands for configuring the XBee module (you'll need to prepend AT to these too).

Command Description

RE Restore factory default settings (note that like parameter changes, this is not permanent unless followed by the W R
command).

WR Write newly configured parameter values to non-volatile (long-term) storage. Otherwise, they will only last until the
module loses power.

CN Exit command mode now. (If you don't send any commands to the module for a few seconds, command mode w ill
timeout and exit even without a CN command.)
You can see all the AT commands in the XBee manual.
API mode
As an alternative to Transparent Operation, API (Application Programming Interface) Operations are available. API
operation requires that communication with the module be done through a structured interface (data is communicated in
frames in a defined order). The API specifies how commands, command responses and module status messages are sent
and received from the module using a UART Data Frame.

Read the manual if you are going to use the API mode.

Entering gateway mode in Raspberry Pi


To stablish UART connection with the module you can use several programs as cutecom in Raspbian graphical
environment or minicom in a terminal window in order to use it via SSH . For using minicom follow these steps:
1. Open a Terminal window on Raspberry Pi, or connect to Raspberry Pi through SSH. In order to enter via SSH change
here the IP from your Raspberry Pi. The default user is pi.
ssh -X pi@192.168.1.X
Now you will have to type your password. The default password is “raspberry”.
2. Install minicom (only if you haven't done it before):
sudo apt-get install minicom
3. Open comunication with the module UART with your correct baudrate. The default baudrate is usually 115200 or 9600:
minicom -b 9600 -o -D /dev/ttyAMA0
4. Then you can enter in configuration mode (without end of line characters so don't press Enter button) and wait a second:
+++
The module will respond with and "OK"
5. Now type for example "ATID" press Enter button and the module will responde with its ID.
6. To exit minicom press CTRL+A, then press X and Yes.
Step 5: Jumper settings (Only for Arduino)Go to index
The XBee shield has two jumpers (the small removable plastic sleeves that each fit onto two of the three pins labelled
XBee/USB). These determine how the XBee's serial communication connects to the serial communication between the
microcontroller (ATmega8 or ATmega168) and FTDI USB-to-serial chip on the Arduino board.

With the jumpers in the XBee position (i.e. on the two pins towards the interior of the board), the DOUT pin of the
XBee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX
pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from
the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the XBee module.
The microcontroller, however, will only be able to receive data from the XBee module, not over USB from the
computer.

With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the XBee
module is connected to the RX pin of the FTDI chip, and DIN on the XBee module is connected to the TX pin of the
FTDI chip. This means that the XBee module can communicate directly with the computer - however, this only works if
the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will
be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk
to the XBee module.
Step 6: Using Series 2 ZB XBee'sGo to index
Series 2 XBee's (ZigBee protocol) are quite different to 802.15.4 ones.
ZigBee networks are called personal area networks or PANs. Each network is defined with a unique PAN identifier
(PAN ID). XBee ZB supports both a 64-bit (extended) PAN ID and a 16-bit PAN ID.

The 16-bit PAN ID is used in all data transmissions. The 64-bit PAN ID is used during joining, and to resolve 16-bit
PAN ID conflicts that may occur.

ZigBee defines three different device types: coordinator, router, and end devices.

Coordinator
 Selects a channel and PAN ID (both 64-bit and 16-bit) to start the network
 Can allow routers and end devices to join the network
 Can assist in routing data
 Cannot sleep--should be mains powered.
Router
 Must join a ZigBee PAN before it can transmit, receive, or route data
 After joining, can allow routers and end devices to join the network
 After joining, can assist in routing data
 Cannot sleep--should be mains powered.
End device
 Must join a ZigBee PAN before it can transmit or receive data
 Cannot allow devices to join the network
 Must always transmit and receive RF data through its parent. Cannot route data.
 Can enter low power modes to conserve power and can be battery-powered.
In ZigBee networks, the coordinator must select a PAN ID (64-bit and 16-bit) and channel to start a network. After that,
it behaves essentially like a router. The coordinator and routers can allow other devices to join the network and can
route data.

After an end device joins a router or coordinator, it must be able to transmit or receive RF data through that router or
coordinator. The router or coordinator that allowed an end device to join becomes the "parent" of the end device. Since
the end device can sleep, the parent must be able to buffer or retain incoming data packets destined for the end device
until the end device is able to wake and receive the data.
See this article for more information about 802.15.4 vs ZigBee: http://sensor-
networks.org/index.php?page=0823123150
Step 7: Video-TutorialGo to index
Here's an explanatory video, which shows the whole process developed in this tutorial:
Fritzing LibrariesGo to index

Download Fritzing Arduino XBee Shield


The Arduino XBee shield allows your Arduino board to communicate wirelessly using Zigbee. It was developed in
collaboration with Arduino.
With this module it can be built low-power wireless communication applications, suchs as sensor networks.
You can download our Fritzing libraries from this area.

You might also like