NS2 Communication Network Experiments
NS2 Communication Network Experiments
DEPARTMENT OF
ELECTRONICS AND TELE-COMMUNICATION ENGINEERING
Co-Workers:
3. INTRODUCTION TO NETWORK
1.C LAYER
Verification of Distance Vector Routing
Protocol using NS2
4. INTRODUCTION TO TRANSPORT
1.D LAYER
To Study the performance of UDP
using NS2
To Study the performance of TCP
using NS2
To Study the performance of UDP
and TCP together using NS2
2. Implementation of PC to PC Serial
Communication using RS-232C Serial
Port
3.A CRYPTOGRAPHY
Implementation of RSA Algorithm
3.B CRYPTOGRAPHY
Implementation of RC4 Algorithm
First of all, you need to create a simulator object. This is done with the command
Now we open a file for writing that is going to be used for the nam trace data.
The next step is to add a 'finish' procedure that closes the trace file and starts nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec [Link]&
exit 0
}
The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of
simulation time.
$ns run
In this section we are going to define a very simple topology with two nodes that are
connected by a link. The following two lines define the two nodes.
A new node object is created with the command '$ns node'. The above code creates two
nodes and assigns them to the handles 'n0' and 'n1'.
This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with
the bandwidth 1Megabit, a delay of 10ms and a DropTail queue.
Now you can save your file and start the script with 'ns [Link]'. nam will be started
automatically and you should see an output that resembles the picture below.
Sending data
In ns, data is always being sent from one 'agent' to another. So the next step is to create an
agent object that sends data from node n0, and another agent object that receives the data
on node n1.
These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic
generator to the UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-
explaining. The packetSize is being set to 500 bytes and a packet will be sent every 0.005
seconds (i.e. 200 packets per second).
The next lines create a Null agent which acts as traffic sink and attach it to node n1.
And now we have to tell the CBR agent when to send data and when to stop sending. Note:
It's probably best to put the following lines just before the line '$ns at 5.0 "finish"'.
Now you can save the file and start the simulation again. When you click on the 'play' button in
the nam window, you will see that after 0.5 simulation seconds, node 0 starts sending data
packets to node 1. You might want to slow nam down then with the 'Step' slider.
Problem Statement
Create two Nodes with duplex link,naming as Node 0 and Node 1, with
Bandwidth 1 Megabit, a delay of 10ms and a Drop Tail queue. Create UDP
agents and attach it to Node 0 and Node 1. Attach CBR traffic to UDP agent.
Set the packet size to 500 bytes and packet interval at0.005 s. In the time
interval, t = 0.05s to t= 2.0s Node 0 sends packets to Node 1 and similarly from
time interval t= 2.5 s to 5.0 s Node 1 sends packets to Node 0(keeping all
parameters same). Simulation stops at t = 5.5 s.
Solution to Problem
$ns run
Exercise:
ODD groups
Set packet size = 1000
Interval = .006
Node 0 to Node 1 time interval = 0.3 s to 3 s
Node 1 to Node 0 time interval = 3.5 s to 5s
Stop the simulation at
5s. EVEN groups
Set packet size = 800
Interval = .008
Node 0 to Node 1 time interval = 0.6 s to 2s
Node 1 to Node 0 time interval = 2.5 s to 5s
Stop the simulation at 5.5 s.
1.1 Conclusion
You have learned to create Nodes, links, define link type, setting time intervals
as per the requirement, starting and stopping of the simulation.
1.2 Reference
[a] TEL-WIMAX-NS2 project documentation [[Link]]
[b] [Link]
[c] Tutorial for the Network Simulator “ns” by Marc Greis
Introduction to Data Link layer
2.1 CSMA/CD
This protocol, known as CSMA/CD (Carrier Sense Multiple Access with Collision
Detection), is the basis of the classic Ethernet LAN. It is important to realize that collision
detection is an analog process.
The station‟s hardware must listen to the channel while it is transmitting. If the signal it
reads back is different from the signal it is putting out, it knows that a collision is occurring.
The implications are that a received signal must not be tiny compared to the transmitted
signal (which is difficult for wireless, as received signals may be 1,000,000 times weaker
than transmitted signals) and that the modulation must be chosen to allow collisions to be
detected (e.g., a collision of two 0- volt signals may well be impossible to detect).
CSMA/CD, as well as many other LAN protocols, uses the conceptual model of Fig. At the
point marked t 0, a station has finished transmitting its frame.
Any other station having a frame to send may now attempt to do so. If two or more stations
decide to transmit simultaneously, there will be a collision. If a station detects a collision, it
aborts its transmission, waits a random period of time, and then tries again (assuming that
no other station has started transmitting in the meantime). Therefore, our model for
CSMA/CD will consist of alternating contention and transmission periods, with idle periods
occurring when all stations are quiet (e.g., for lack of work).
#Create Simulator
set ns [new Simulator]
#Create 6 nodes
for {set i 0} {$i< 6} {incr i} {
set n($i) [$ns node]
}
BEGIN {
recvdSize = 0;
startTime = 400;
stopTime = 0;
}
{
event = $1;
time = $2;
node_id = $3;
pkt_size = $8;
level = $4;
#Store start time
if(level ==”AGT” && event ==”s” &&pkt_size>= 512)
{ if (time <startTime) {
startTime = time;
}
}
#Update total received packet’s size ans store
packet’s arrival time
if(level ==”AGT” && event ==”r” &&pkt_size>= 512)
{ if (time >stopTime) {
stopTime = time;
}
#Rip off the header
hdr_size = pkt_size %512;
pkt_size -= hdr_size;
#store received packet’s size
recvdSize += pkt_size;
}
}
END {
printf("Average Throughput[kbps] = %0.2f \t\t StartTime = %0.2f
StopTime = %0.2f \n”, recvdSize/(stopTime- startTime)) *(8/1000),
startTime, stopTime);
}
Introduction to Network Layer
In distance vector routing, each router maintains a routing table indexed by, and containing
one entry for each router in the network. This entry has two parts: the preferred outgoing
line to use for that destination and an estimate of the distance to that destination. The
distance might be measured as the number of hops or using another metric, as we discussed
for computing shortest paths. The router is assumed to know the „„distance‟‟ to each of its
neighbors. If the metric is hops, the distance is just one hop. If the metric is propagation
delay, the router can measure it directly with special ECHO packets that the receiver just
timestamps and sends back as fast as it can.
As an example, assume that delay is used as a metric and that the router knows the delay to
each of its neighbors. Once every T msec, each router sends to each neighbor a list of its
estimated delays to each destination. It also receives a similar list from each neighbor.
Imagine that one of these tables has just come in from neighbor X, with Xi being X‟s
estimate of how long it takes to get to router i.
If the router knows that the delay to X is m msec, it also knows that it can reach router i via
X in Xi + m msec. By performing this calculation for each neighbor, a router can find out
which estimate seems the best and use that estimate and the corresponding link in its new
routing table.
Table1 : Initial distance stored at each node(Global view)
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
[Link]&
exit 0
}
============================================================
Introduction to Transport layer
4.1 UDP
The User Datagram Protocol (UDP) provides a connectionless service for application-level
procedures.
Thus, UDP is basically an unreliable service; delivery and duplicate protection are not
guaranteed. However, this does reduce the overhead of the protocol and may be adequate in
many cases. An example of the use of UDP is in the context of network management.
The strengths of the connection-oriented approach are clear. It allows connection- related
features such as flow control, error control, and sequenced delivery.
Connectionless service, however, is more appropriate in some contexts. At lowerlayers
(internet, network), a connectionless service is more. In addition, it represents a “least
common denominator” of service to be expected at higher layers. Further, even at transport
and above there is justification for a connectionless [Link] are instances in which the
overhead of connection establishment and termination is unjustified or even
counterproductive.
4.2 TCP
TCP is designed to provide reliable communication between pairs of processes (TCP users)
across a variety of reliable and unreliable networks and internets. TCP provides two useful
facilities forlabeling data: push and urgent.
TCP Mechanisms
We can group TCP mechanisms into the categories of connection establishment, data
transfer, and connection termination.
Experiment 1D :
(i) To Study the Performance of UDP using NS2
###############################TCL CODE################################
#Create a simulator object
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
setnf [open [Link] w]
$ns namtrace-all $nf
proc finish {} {
global ns nfnd
$ns flush-trace
#Close the NAM trace file
close $nf
close $nd
#$ns attach-agent
$n1 $null0
$ns attach-agent
$n3 $null1
$ns connect $udp0 $null0
$ns connect $udp1 $null1
$ns run
global ns nfnd
$ns flush-trace
close $nf
close $nd
exit 0
$ns run
===================================================================
1. E. Assignment / Exercise
2. Taking the number of nodes as 6 for ODD groups and 8 for EVEN groups
, packet size 500 for ODD groups and 800 for EVEN groups ,simulate all
three programs of experiment 1D with full explanation of each code used.
3. Explain the relevance of TRACE file with explaining all its parameters.
4. Explain the effect of Changing the packet size, bit rate etc.
National Semiconductor's 8250B UART
The UART chip has a total of 12 different registers that are mapped into 8 different Port I/O
locations.
IIR, interrupt identification register FCR, FIFO control register , LCR, line control register
MCR, modem control register , LSR, line status register , MSR, modem status register
SCR, scratch register , DLL, divisor latch LSB , DLM, divisor latch MSB
For a "typical" PC system, the following are the Port I/O addresses and IRQs for each serial
COM port:
To use the UART in different environments, registers are accessible to set or review the
communication parameters. Settable parameters are for example the communication speed,
the type of parity check, and the way incoming information is signalled to the running
software.
The 16450 was capable of handling a communication speed of 38.4 kbs without problems.
The demand for higher speeds led to the development of newer series which would be able to
release the main processor from some of its tasks. The main problem with the original series
was the need to perform a software action for each single byte to transmit or receive. To
overcome this problem, the 16550 was released which contained two on-board FIFO buffers,
each capable of storing 16 bytes. One buffer for incoming, and one buffer for outgoing bytes.
A marvellous idea, but it didn't work out that way. The 16550 chip contained a firmware bug
which made it impossible to use the buffers. The 16550A which appeared soon after was the
first UART which was able to use its FIFO buffers. This made it possible to increase
maximum reliable communication speeds to 115.2 kbs. This speed was necessary to use
effectively modems with on-board compression. A further enhancement introduced with the
16550 was the ability to use DMA, direct memory access for the data transfer. Two pins were
redefined for this purpose. DMA transfer is not used with most applications. Only special
serial I/O boards with a high number of ports contain sometimes the necessary extra circuitry
to make this feature work.
The 16550A is the most common UART at this moment. Newer versions are under
development, including the 16650 which contains two 32 byte FIFO's and on board support
for software flow control. Texas Instruments is developing the 16750 which contains 64 byte
FIFO's.
Registers
Eight I/O bytes are used for each UART to access its registers. The following table shows, where each
register can be found. The base address used in the table is the lowest I/O port number assigned.
The switch bit DLAB can be found in the line control register LCR as bit 7 at I/O address base + 3.
The transmitter holding register is not used to transfer the data directly. The byte is first
transferred to a shift register where the information is broken in single bits which are sent one
by one.
Interrupts are not generated, unless the UART is told to do so. This is done by setting bits in
the IER, interrupt enable register. A bit value 1 indicates, that an interrupt may take place.
The FCR, FIFO control register is present starting with the 16550 series. This register
controls the behaviour of the FIFO's in the UART. If a logical value 1 is written to bits 1 or 2,
the function attached is triggered. The other bits are used to select a specific FIFO mode.
The LCR, line control register is used at initialisation to set the communication parameters.
Parity and number of data bits can be changed for example. The register also controls the
accessibility of the DLL and DLM registers. These registers are mapped to the same I/O port
as the RBR, THR and IER registers. Because they are only accessed at initialisation when no
communication occurs this register swapping has no influence on performance.
The UART is capable of generating a trailing bit at the end of each dataword which can be
used to check some data distortion. Because only one bit is used, the parity system is capable
of detecting only an odd number of false bits. If an even number of bits has been flipped, the
error will not be seen.
When even parity is selected, the UART assures that the number of high bit values in the sent
or received data is always even. Odd parity setting does the opposite. Using stick parity has
very little use. It sets the parity bit to always 1, or always 0.
The MCR, modem control register is used to perform handshaking actions with the attached
device. In the original UART series including the 16550, setting and resetting of the control
signals must be done by software. The new 16750 is capable of handling flow control
automatically, thereby reducing the load on the processor.
The two auxiliary outputs are user definable. Output 2 is sometimes used in circuitry which
controls the interrupt process on a PC. Output 1 is normally not used, however on some I/O
cards, it controls the selection of a second oscillator working at 4 MHz. This is mainly for
MIDI purposes.
The LSR, line status register shows the current state of communication. Errors are reflected in
this register. The state of the receive and transmit buffers is also available.
Bit 5 and 6 both show the state of the transmitting cycle. The difference is, that bit 5 turns
high as soon as the transmitter holding register is empty whereas bit 6 indicates that also the
shift register which outputs the bits on the line is empty.
The MSR, modem status register contains information about the four incoming modem
control lines on the device. The information is split in two nibbles. The four most significant
bits contain information about the current state of the inputs where the least significant bits
are used to indicate state changes. The four LSB's are reset, each time the register is read.
MSR : Modem status register
Bit Description
0 change in Clear to send
1 change in Data set ready
2 trailing edge Ring indicator
3 change in Carrier detect
4 Clear to send
5 Data set ready
6 Ring indicator
7 Carrier detect
The SCR, scratch register was not present on the 8250 and 8250B UART. It can be used to
store one byte of information. In practice, it has only limited use. The only real use I know of
is checking if the UART is a 8250/8250B, or a 8250A/16450 series. Because the 8250 series
are only found in XT's even this use of the register is not commonly seen anymore.
For generating its timing information, each UART uses an oscillator generating a frequency
of about 1.8432 MHz. This frequency is divided by 16 to generate the time base for
communication. Because of this division, the maximum allowed communication speed is
115200 bps. Modern UARTS like the 16550 are capable of handling higher input frequencies
up to 24 MHz which makes it possible to communicate with a maximum speed of 1.5 Mbps.
On PC's higher frequencies than the 1.8432 MHz are rarely seen because this would be
software incompatible with the original XT configuration. This 115200 bps communication
speed is not suitable for all applications. To change the communication speed, the frequency
can be further decreased by dividing it by a programmable value. For very slow
communications, this value can go beyond 255. Therefore, the divisor is stored in two
seperate bytes, the divisor latch registers DLL and DLM which contain the least, and most
significant byte. For error free communication, it is necessary that both the transmitting and
receiving UART use the same time base. Default values have been defined which are
commonly used. The table shows the most common values with the appropriate settings of
the divisor latch bytes. Note that these values only hold for a PC compatible system where a
clock frequency of 1.8432 MHz is used.
Introduction
MQTT stands for Message Queuing Telemetry [Link] was invented by Dr Andy Stanford-
Clark of IBM, and Arlen Nipper of Arcom (now Eurotech), in 1999. It is a publish/subscribe, extremely
simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-
latency or unreliable networks. The design principles are to minimise network bandwidth and device
resource requirements whilst also attempting to ensure reliability and some degree of assurance of
delivery. These principles also turn out to make the protocol ideal of the emerging “machine-to-machine”
(M2M) or “Internet of Things” world of connected devices, and for mobile applications where bandwidth
and battery power are at a premium.
Theory
The protocol uses a publish/subscribe architecture in contrast to HTTP with its request/response
paradigm. Publish/Subscribe is event-driven and enables messages to be pushed to clients. The central
communication point is the MQTT broker, it is in charge of dispatching all messages between the senders
and the rightful receivers. Each client that publishes a message to the broker, includes a topic into the
message. The topic is the routing information for the broker. Each client that wants to receive messages
subscribes to a certain topic and the broker delivers all messages with the matching topic to the client.
Therefore, the clients don’t have to know each other, they only communicate over the topic. This
architecture enables highly scalable solutions without dependencies between the data producers and the
data consumers.
The difference to HTTP is that a client doesn’t have to pull the information it needs, but the broker pushes
the information to the client, in the case there
is something new. Therefore, each MQTT
client has a permanently open TCP
connection to the broker. If this connection is
interrupted by any circumstances, the MQTT
broker can buffer all messages and send them
to the client when it is back online. As
mentioned before the central concept in
MQTT to dispatch messages are topics.
Because MQTT decouples the publisher from the subscriber, client connections are always handled by a
broker.
Client
MQTT client: Both publishers and subscribers are MQTT clients. The publisher and subscriber labels
refer to whether the client is currently publishing messages or subscribing to messages (publish and
subscribe functionality can also be implemented in the same MQTT client). An MQTT client is any
device (from a micro controller up to a full-fledged server) that runs an MQTT library and connects to an
MQTT broker over a network. For example, the MQTT client can be a very small, resource-constrained
device that connects over a wireless network and has a bare-minimum library. The MQTT client can also
be a typical computer running a graphical MQTT client for testing purposes. Basically, any device that
speaks MQTT over a TCP/IP stack can be called an MQTT client. The client implementation of the
MQTT protocol is very straight forward and streamlined. The ease of implementation is one of the
reasons why MQTT is ideally suited for small devices. MQTT client libraries are available for a huge
variety of programming languages. For example, Android, Arduino, C, C++, C#, Go, iOS, Java,
JavaScript, and .NET.
Broker
The counterpart of the MQTT client is the MQTT broker. The broker is at the heart of any
publish/subscribe protocol. Depending on the implementation, a broker can handle up to thousands of
concurrently connected MQTT clients. The broker is responsible for receiving all messages, filtering the
messages, determining who is subscribed to each message, and sending the message to these subscribed
clients. The broker also holds the sessions of all persisted clients, including subscriptions and missed
messages (more details). Another responsibility of the broker is the authentication and authorization of
clients. Usually, the broker is extensible, which facilitates custom authentication, authorization, and
integration into backend systems. Integration is particularly important because the broker is frequently the
component that is directly exposed on the internet, handles a lot of clients, and needs to pass messages to
downstream analyzing and processing systems. In brief, the broker is the central hub through which every
message must pass.
Here we use HiveMQ as a broker and MQTTBox to set-up and manage clients.
MQTT Client Settings:
When creating new MQTT client from MQTTBox app, there are wide range of connection settings one
can specify. Most of the settings are set by default to most used values, however they are customisable
and the terms are explained below:
1. MQTT Client Name:
Name to identify MQTT client and display on dashboard. It can be any string value.
e.g.: client_test_1
2. Client Id:
The client identifier is an identifier of each MQTT client connecting to a MQTT broker. It should be
unique per client for given broker. The broker uses it for identifying the client and the current state of the
client. It is auto generated by default. Trying to connect two MQTT clients with same client identifier,
connection will be rejected by broker. If 2 instances of MQTTBox app are open, it must be made sure
they have unique client id's otherwise the clients will be rejected by broker and may show offline.
e.g.: client_id_1
3. Append timestamp to MQTT client id?
If checked, timestamp will be appended to client Id. This is enabled by default. Many a times, users open
multiple instances of MQTTBox app on same or different machines with same MQTT client settings
including same client id unknowingly. This causes both client connections to be rejected by broker
because of same client id. If this option is enabled, MQTTBox will append timestamp to every client id
making it almost unique which helps save time debugging unnecessary issues.
4. Broker is MQTT v3.1.1 compliant?
If you are connecting to a MQTT broker that only supports older versions of MQTT protocol 3.1 or less
(v3.1.1 is latest and current standard), you should un-check this option. By default, it is checked and
assumes MQTT broker is compliant with current MQTT standard v3.1.1 (or higher).
5. Protocol:
Network protocol used by MQTT client to connect with MQTT broker.
MQTTBox supports TCP, SSL/TLS, MQTT, MQTTS, WebSockets (WS) and Secure WebSockets
(WSS). Depending on the platform, all Protocol may not be supported because of platform limitations.
(For this experiment, TCP/IP will be used.)
6. Host:
MQTT host to connect. One needs to specify right host and port number depending on MQTT connection
protocol selected. MQTT client may not get connected if wrong port number is mentioned or port
numbers are interchanged.
e.g.: [Link]
7. Clean Session?
The clean session flag indicates the broker whether the client wants to establish a persistent session or not.
If you need a persistent session, meaning, that the broker will store all subscriptions for the client and also
all missed messages, when subscribing with Quality of Service (QoS) 1 or 2, un-check/No this option. By
default, this is checked or Yes, which means broker will start new session, won’t store anything for the
client and will also purge all information from a previous persistent session.
8. Auto connect on app launch?
If you check Yes, this option, client will try to connect to broker automatically when MQTTBox app is
launched and can be in "Connected", or "Connection Error" state depending on if client was connected to
broker or not. If un-checked/No this option, client will be in "Not connected" state and you need to
manually connect client to broker.
9. Username:
Username required by broker, if any. MQTT allows to send username for authenticating and authorization
of client.
10. Password:
Password required by broker, if any. MQTT allows to send password for authenticating and authorization
of client. Please note, all passwords are saved in plain text. Make sure you never save production
passwords inside MQTTBox app. In fact, all fields are saved as plain text, make sure you never save any
sensitive information/settings inside MQTTBox app.
11. Reschedule Pings?
If checked/yes, reschedules ping messages after sending packets.
12. Queue outgoing QoS zero messages:
If checked yes, if connection is broken between client and broker, client queue's outgoing QoS zero
messages. All these messages will be published when connection is established.
13. Reconnect Period (in milliseconds):
Interval between two reconnections
14. Connect Timeout (in milliseconds):
Time to wait before a CONNACK is received
15. KeepAlive (in seconds):
The keep alive is a time interval, the clients commits to by sending regular PING Request messages to the
broker. The broker response with PING Response and this mechanism will allow both sides to determine
if the other one is still alive and reachable. By default, it is set to 10 seconds. Set to 0 to disable.
16. Will Settings:
The will message is part of the last will of MQTT Client. It allows to notify other clients, when a client
disconnects ungracefully. A connecting client will provide his will in form of an MQTT message and
topic in the CONNECT message. If the client gets disconnected ungracefully, the broker sends this
message on behalf of the client automatically.
16.1 Will Settings - Topic: The topic to publish will payload. A simple string, which can have
hierarchically structured with forward slashes as delimiters.
e.g.: topic_test_1 or home/kitchen/humidity
16.2 Will Settings - QoS: Publish payload with QoS set. By default, it is 0.
16.3 Will Settings - Retain: Retain flag for will payload.
16.4 Will Settings - Payload: The message to publish when the client disconnects badly.
Publisher Settings:
1. Topic to publish: is the topic to publish to. A simple string, which can have hierarchically structured
with forward slashes as delimiters.
e.g.: topic_test_1 or home/kitchen/humidity
2. QoS: A Quality of Service Level (QoS) for this message. The level (0,1 or 2) determines the guarantee
of a message delivered.
3. Retain: This flag determines if the message will be saved by the broker for the specified topic as last
known good value. New clients that subscribe to that topic will receive the last retained message on that
topic instantly after subscribing.
To delete retain message of topic, send a retained message with a zero byte payload on that topic.
4. Payload: This is the actual content of the message to publish to topic.
Subscriber settings:
Topic: is a String topic to subscribe to. You can specify Single Level(+) and Multilevel(#) subscription to
topics.
e.g.: topic_test_1 or home/+/humidity or home/#
QoS: A Quality of Service Level (QoS) for this message. The level (0,1 or 2) determines the guarantee of
a message delivered.
For further reading:
[Link]
Software Requirements
Although the hardware requirements for this does not extend beyond a simple PC running Windows or
Linux and an internet connection, there are a few software requirements to get started.
1. Environment: Java - OpenJDK JRE/JDK 11 or newer is required.
2. MQTT Broker: HiveMQ is being used in this case. (Some alternatives are Mosquitto, Mosca, emqttd,
Python Test Broker, VerneMQ)
3. MQTTBox: This helps create MQTT clients to publish or subscript topics, create MQTT virtual device
networks, load test MQTT devices or brokers and offers some additional features.
Setting up and testing:
1. Java Runtime Environment: Download and install a compatible version of JRE
2. HiveMQ broker:
2.1. Download the HiveMQ zip file from [Link]
2.2. Unzip the file
2.3. Open the “[Link]” file in the directory ~\hivemq-4.1.0\hivemq-4.1.0\conf (using any standard
text editors)
2.4. Change the IP under “bind-address” from <[Link]> to the IP of your computer
2.5. Go to ~\hivemq-4.1.0\hivemq-4.1.0\bin and run the “[Link]” as administrator
3. MQTTBox app:
3.1. It can be installed from the Windows Store itself. Alternatively one can download the installer
file from their website [Link] which comes
with instructions to install for non-Windows systems as well.
3.2. Once installed, launch the app and click on “Create MQTT Client” inside the app and follow the
steps given below for a basic setup with minimal customization:
3.2.1. Fill in a name under “MQTT Client Name”
3.2.2. Change the protocol to “mqtt/tcp” from the drop-down menu
3.2.3. Fill in a topic name under “Will-Topic” (optional)
3.2.4. Change the “Host” to the IP of your machine (or in the case of multiple machines, the
machine acting as “publisher” will put their own IP and the machines acting as
“subscribers” will put the IP of the “publisher”) and click on save
3.3. Once a MQTT client is created, two boxes will appear one for the publisher and one for the
subscriber.
3.4. Publisher setup:
3.4.1. Give a topic name in the box designated to “topic to publish”
3.4.2. Check the “retain” box
3.4.3. Under “Payload” type the message you wish to send
3.4.4. Before hitting “publish” make sure at least one person is subscribed to the same topic as
you are publishing in order to verify that it is working
3.5. Subscriber setup:
3.5.1. Under “topic” fill in the topic of interest and set the corresponding QoS accordingly and
click on “Subscribe”.
3.5.2. You may type a message from the publisher window and check if it is working now.
An example flow diagram:
Observations:
Conclusions:
Assignments:
1. Publish DHT sensor data using Arduino Uno through MQTT.
2. Publish Ultrasonic sensor data using Node MCU through MQTT.
Ex. No. 5 Sending SMS using GSM module and Arduino Uno Board
Introduction
Arduino:
The Arduino UNO is an open-source microcontroller board based on the Microchip ATmega328P
microcontroller and developed by [Link]. The board is equipped with sets of digital and analog
input/output (I/O) pins that may be interfaced to various expansion boards (shields) and other circuits.
The board has 14 digital pins, 6 analog pins, and programmable with the Arduino IDE (Integrated
Development Environment) via a type B USB cable. It can be powered by the USB cable or by an
external 9-volt battery, though it accepts voltages between 7 and 20 volts.
GSM module:
SIM900A is a miniature cellular module which allows for GPRS transmission, sending and receiving
SMS and making and receiving voice calls. Low cost and small footprint and quad band frequency
support make this module perfect solution for any project that require long range connectivity. After
connecting power module boots up, searches for cellular network and login automatically. On board
LED displays connection state (no network coverage - fast blinking, logged in - slow blinking).
NOTE: Power consumption peeks up to 2A. Maximum voltage on UART in this module is 2.8V.
Higher voltage will kill the module. So, an external power supply is provided using an AC adapter.
Note: This may not be identical to the board in the laboratory. Only the TX, RX and Gnd need to be
connected to the Arduino. Power is to be supplied externally.
Hardware requirements:
1. Arduino Uno board
2. GSM Module
3. Jumper wires
4. SIM card (adapters too in case the SIM card is a micro or nano type)
5. Power adapter for the GSM module
Software requirements:
1. Arduino IDE
A GSM Module is basically a GSM Modem (like SIM 900) connected to a PCB with
different types of output taken from the board – say TTL Output (for Arduino, 8051 and other
microcontrollers) and RS232 Output to interface directly with a PC (personal computer). The
board will also have pins or provisions to attach mic and speaker, to take out +5V or other
values of power and ground connections. These type of provisions vary with different
modules.
Lots of varieties of GSM modem and GSM Modules are available in the market to choose
from. For our project of connecting a gsm modem or module to arduino and hence send and
receive sms using arduino – its always good to choose an arduino compatible GSM
Module – that is a GSM module with TTL Output provision.
1. We use SIM900 GSM Module – This means the module supports communication in
900MHz band. We are from India and most of the mobile network providers in this country
operate in the 900Mhz band. If you are from another country, you have to check the mobile
network band in your area. A majority of United States mobile networks operate in 850Mhz
band (the band is either 850Mhz or 1900Mhz). Canada operates primarily on 1900 Mhz
band.
2. Check the power requirements of GSM module – GSM modules are manufactured by
different companies. They all have different input power supply specs. You need to double
check your GSM modules power requirements. In this tutorial, our gsm module requires a 12
volts input. So we feed it using a 12V,1A DC power supply. Some gsm modules which
require 15 volts and some other types which needs only 5 volts input. They differ with
manufacturers. If you are having a 5V module, you can power it directly from Arduino‟s 5V
out.
Note:- GSM Modules are manufactured by connecting a particular GSM modem to a PCB
and then giving provisions for RS232 outputs, TTL outputs, Mic and Speaker interfacing
provisions etc. The most popular modem under use is SIM 900 gsm modem from
manufacturer SIMCom. They also manufacture GSM Modems in bands 850, 300 and other
frequency bands.
3. Check for TTL Output Pins in the module – You can feed the data from gsm module
directly to Arduino only if the module is enabled with TTL output pins. Otherwise you have
to convert the RS232 data to TTL using MAX232 IC and feed it to Arduino. Most of the
gsm modules in market are equipped with TTL output pins.
Setup:
Hardware connections:
1. Connect the Arduino Uno Board to the PC using the USB connector cable.
2. Without connecting the Arduino and GSM module, insert the SIM card in the GSM
module.
3. Connect the GSM module to power source using the power adapter, and power up the
device. (The connection can be checked via the LED as well as calling the number whose
SIM card is inserted in the module.)
[(a) Now wait for some time (say 1 minute) and see the blinking rate of „status LED‟ or „network
LED‟ (GSM module will take some time to establish connection with mobile network)
(b) Once the connection is established successfully, the status/network LED will blink
continuously every 3 seconds. You may try making a call to the mobile number of the sim card
inside GSM module. If you hear a ring back, the gsm module has successfully established
network connection].
3. Open Arduino IDE and write the required program, select the correct board (Arduino
Genuino Uno in this case) and port (COM2/COM5/COM6/whichever is applicable)
under “Tools” menu.
4. Compile and then Upload the sketch (code) to the Arduino.
Note: The problem with this connection is that, while programming, Arduino uses serial ports
to load program from the Arduino IDE. If these pins are used in wiring, the program will not
be loaded successfully to Arduino. So you have to disconnect wiring in Rx and Tx each time
you burn the program to arduino. Once the program is loaded successfully, you can reconnect
these pins and have the system working!
5. Now connect the Tx pin of the GSM module to the D8 pin of the Arduino board (Rx)
and Rx pin of the GSM module to the D7 pin of the Arduino board (Tx)using the
jumper wires. Connect the Ground pins of the two boards as well.
6. You can check the output in the “Serial Monitor”. Click on Serial Monitor, Then
Press “1” followed by “Enter ⅃” to see the output of the Program. Also, the check
that the SMS delivered to the intended recipient Mobile #.
____________________________________
Optional Procedure:
7. Click on the serial monitor and select the Baud rate specified in the program (9600 in
this case) from the bottom right corner to view the output. Verify with the recipient‟s
phone.
Note:
a. Remember to change the recipient‟s phone number in the Program.
b. Adjust the antenna on the GSM module for better cellular network receptivity.
c. If you wish to send text messages in a loop, it can be done simply by
copying/cutting the code in “void setup()” and inserting the code in “void
loop()”.
ARDUINO Code Required For The Implementation:
void setup()
{
[Link](9600); //Set baud rate to 9600 Setting the baud rate of Serial Monitor (Arduino)
}
void loop()
{
//You can skip the first three lines if you are sure your sim900 gsm setup is
//perfect and there is no error in circuit connection and power requirements.
//delay(1200);
//[Link]("AT"); “AT” This will check if the module is connected properly and its
functioning, the module will reply with an acknowledgment.
//delay(3000);
[Link]();
delay(3000);
[Link]();
[Link]("AT+CMGS="); // Write the Mobile number, To whom the message is to be
sent to (ie. the Receiver mobile #)
[Link]("\"+91XXXXXXXXXX\"");
[Link]();
delay(3000);
[Link]("Hello Sir"); // SMS-Message body
delay(4000);
[Link]();
[Link](26); //CTRL+Z key combination indicating the end of the text message
Conclusions:
Assignments:
1. Send the Roll number of any of your group members, instead of test message in the
example.
2. Write a Program for sending an SMS, if any movement is detected by a PIR sensor
using Arduino Uno.