This document provides an overview of sensor interfacing with microcontrollers, focusing on various types of sensors such as gas, obstacle, heartbeat, and ultrasonic sensors. It includes procedures for interfacing these sensors with microcontrollers like NodeMCU and Arduino, along with code snippets for reading data and uploading it to cloud services like Adafruit. The document emphasizes the importance of understanding sensor types and their applications in building IoT systems.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
35 views52 pages
Iot Unit 2 Book
This document provides an overview of sensor interfacing with microcontrollers, focusing on various types of sensors such as gas, obstacle, heartbeat, and ultrasonic sensors. It includes procedures for interfacing these sensors with microcontrollers like NodeMCU and Arduino, along with code snippets for reading data and uploading it to cloud services like Adafruit. The document emphasizes the importance of understanding sensor types and their applications in building IoT systems.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 52
COPTER TONS TN
Microcontrollers, and Their Interfacing
LEARNING OBJECTIVES
The chapter will help readers acquire an in-depth understanding of
Different types of sensors and their use.
Procedure to interface sensors to the microcontroller (computing boards).
Procedure to control the sensors through webpages.
Techniques to load the data
Fundamentals of the most frequently used microcontrollers (8051 and ARM 7)
-nsed to the cloud.
Introduction to Sensor Interfacing
There are numerous sensors available in the market and it is essential to know about these
sensors to build a complete/comprehensive IoT system. In this chapter, the reader shalll be
introduced to sensors that are frequently used towards building IoT applications. Also, the
procedure for interfacing with the sensors is presented along with the software code for
reference. It is recommended that readers have a hands-on experience with the code pre-
sented. Also, for some interfacing exercises, the codes for uploading the data to the cloud are
also presented. Readers need not worry much about the cloud part right now. It is covered in
depth as part of the subsequent chapters. Readers are expected to install the Arduino IDE
and follow the procedure as mentioned in Annexure Al, Arduino IDE supports most of the
available embedded boards in the market. Selection of board from the available menu is an
important step.
Types of Sensors
2.2.1 MQ-02/05 - Gas Sensor Interfacing with NodeMCU/Arduino.
Before getting
gas sensor.
-depth about how to interface, it is essential to also learn about MQ-02FREE SAIS AT SRG
In many malls we find smoke sensors on the ceilings which are designed in order to detect
smoke (fire) and sprinkle water during outbreak of fire accidents. MQ-02 is capable of
detecting H,, LPG, CH,, alcohol, and smoke. It is used vastly because of its quick and rapid
response, When any flammable gas flows through this sensor, the coil inside this sensor
burns and so the resistance of the coil decreases. Hence, the output voltage starts increasing,
which can be detected using a microcontroller. There is another sensor by name MQ-05 also
available in the market but it is not sensitive to smoke and hence is not preferred for smoke/
fire detection applications.
Figure 2.1 shows how MQ-02 looks like.
Figure 2.1 MQ-02 sensor.
Figure 2.2 illustrates how this sensor functions, Also do note the following points:
1. Greater the gas concentratioi
, greater is the output voltage.
2. Lower the gas concentration, lower is the output voltage.
_ ¢g-
Presence of smoke 1MQ-02 sensor ‘Voltage variation (output)
Figure 2.2 Schematic representing functioning of MQ-02.
Now, let us design a circuit using MQ-02 gas sensor to monitor the smoke percentage and
upload those values to the cloud. (Readers need not worry about the cloud part; Chapter 5
covers cloud in detail.)
MQ-02 generally has 4 pins. Figure 2.3 shows the pin layout of MQ-02.22 Typesotsensos EEE
ras
ee PUR-LED Ug
cd VCC (+5)
% ~ - Ground
(ume) ,
lg ait
od ad
“ ‘Analog output
on
Figure 2.3 Pin layout of MO-02 sensor.
As it can be seen from Fig. 2.3 that MQ-02 has VCC (power), Ground followed by Analog
and Digital pins. One can read the data as analog or digital based on the requirement and
necessity. The connection diagram with the NodeMCU is presented in Fig. 2.4. One can see
that AO pin is connected to Data (Analog pin) of MO-02. Also, Ground and VCC are con-
nected appropriately at both the ends. The code to read the analog data is also provided.
MQ-02 gas sensor
Figure 2.4 Connection diagram — NodeMCU to MQ-02 sensor.HEE rociction to sensors, Microcontars, and Ther nteracing
Code to interface AO of NodeMCU with MQ-02:
finclude
include
int val;
#define USE_SERIAL Serial
#define GAS SENSOR AO
// AO of NodeMCU is connected to Analog pin of MQ-02
void setup ()
{
Serial begin (115200);
// Baud rate. This has to be usiform in the IDB and Serial Monitor.
delay (10);
1
void loop()
{
val=analogRead (GAS_SENSOR) ;
7 Analog read for reading any analog input.
Serial.print (val);
// Here, we print the value read through the serial monitor.
Serial.printin(* ");
delay(100) +
1
‘The above code will read the sensory data and display the same through the serial monitor.
‘The compilation procedure is also summarized in Annexure A through which the reader can
understand the flow.
‘The next section of the code is presented to get the sensed data stored in the cloud. Readers
can choose any cloud service provider. Authors have chosen Adafruit as it is simple, easy
to use, and most importantly free to use (with constraints). The procedure for setting up
‘Adafruit account is presented elaborately in Chapter 5. Readers are expected to have a look22 WesotSensos ETE
at the same to derive better clarity. Also, the term MOTT is used in the code frequently. We
will explain this in depth with appropriate demo in later sections.
The following code snippets shall help in getting the data to the cloud.
Code snippet 2.1 shows the connection procedure to the Wi-Fi and the initialization steps.
#includecAdafruit MOTT Client.h>
#includecESPé266WiFi.h>
fdefine wifi_name “Your SSID”
define pswd “Your Wifi Password”
fdefine server “io.adafruit.com”
fdefine port 1883
define username “Your Adafruit User 1D”
fdefine aiokey “Your AIO Key”
Code Snippet 2.1 Initialization steps for connecting to the Intemet.
Code snippet 2.2 is for setting up Wi-Fi connection and Adafruit client initialization steps.
WiFiclient me;
Adafruit MQTT Client matt (sme, server, port username, aickey) +
Adafruit MOTT Publishgas_data~Adafruit MOTT Publish(smgtt, username” /feeds/
Gas_sensor”) ;
void setup() {
Serial begin (9600);
delay(10);
Serial.printin ("Connecting to “);
Serial.print (wifi_name);
WiFi -begin(wifi_name, pswa);
while (WiPi.status() != WL CONNECTED)
‘
delay (500);
Serial.print (".");
)
Code Snippet 2.2 Connecting to the Internet and initializing Adafruit cloud client.
Now, the final step is to upload the obtained data from the sensor to the feed inside the Ada-
fruit cloud. The following code does the above mentioned job. As seen in the simple analog
read code, here also, the AO port is read for the data through code snippet 2.3.
void loop() {
if (matt connected ())
{
int Gas_value= analogRead(A0);
Serial. print1n(Gas_value);
Code Snippet 2.3 Uploading the data into the cloud.HIRE itn sors esac ui
Serial print ("Trying");
)
delay (200)
Code Snippet 2.3 Continued.
The screenshot in Fig. 2.5 shows the data which is uploaded to cloud with the time of upload
and the corresponding sensor value (for this, the user should have already logged in with
corresponding Adafruit account; the procedure is presented in Chapter 5). With the same
code, one can interface any MQ sensors to the microcontroller with ease. There are many
MO sensors available in the market and the purpose of the sensors is the same: to detect the
smoke/gas, ete, Selection of sensors is difficult yet crucial and attention should be paid at this,
stage. Following are points one should consider before selecting any sensor:
1. Cost.
2. Precision and accuracy.
Understanding the environment.
4, Signal conditioning (removal of noise and other factors should be fea:
ADC/DAC support availability
6. Size of the sensor (form factor)
PRLS z Perey
Ea Ee eT
Ae 2018-06-24 3:01:03 pm
ee
Perr)
3:00:59 pm
oda
ee eal
ta
eto
eee
Figure 2.5 Uploaded cloud data.
J
predominantly used NodeMCU and Ardui
is remain the sare.
ards in this chapter. ¥
can use whichever y22 Types of Sensors
2.2.2 Interfacing the Obstacle Sensor
In real-time applications we use IR sensors for detecting the obstacles. A practical example
could be easier to understand. Assume that a robot is deployed to detect the obstacles in the
path, The robot has to detect and alert the presence of any obstacle on the way. So, here we
use IR sensors which give either zero or one as its digital output based on the presence of
the obstacle, The entire process through which the obstacle is sensed and the data is moved
to cloud is presented in the code written below. Code snippet 2.4 is meant for establishing
the connection to Adafruit client. An obstacle sensor is captured as a snap and is presented
as Fig. 2.6. Also, one can clearly understand the interfacing details by referring to Fig. 2.7,
Figure 2.7 Connection diagram for the IR sensor.Introduction to Sensors, Microcontrollers, and Their interfacing
WiFiclient mer
Adafruit_MOTT Client matt (Ame, server,port username, aiokey) +
Adafruit MOTT Publish gas_data = Adafruit_MorT_Publish(eatt, usernane"/feeds/
1R_data");
Code Snippet 2.4 Connection to Adafruit client.
In code snippet 2.5, the following line is used to obtain digital output data from the IR
sensor which is then processed to know whether an obstacle is present or not.
int TR_stat= digitalRead(IR sensor);
If the IR_stat value is equal to 1 then it depicts that the obstacle is pres-
ent else it is not present.
void loop () {
4£ (mgt .connected() }
(
//Read data from 7th digital pin
int TR_stat= analogRead (D3)
Serial.printin(IR-stat) :
Serial.print("...");
4£(IR_data.publish(IR_stat) )
{
Serial.printin ("success") ;
else
Serial print ("trying");
b
)
delay (2000);
,
Code Snippet 2.5 Read the data and uploading to the cloud.
Code snippet 2.6 is the code for acknowledging the presence of an obstacle in front of the sensor.
if(IR_stat =
t
vy
Serial.printin ("Something is present infront of me”);
}
else
{
Serial.printin ("The way is clear");
)
Code Snippet 2.6 Detecting the presence of the obstacle.22 Typesof Sensors
Now, et us understand how the IR sensor talks to us when it detects an obstacle present in front
of it. The sensor gives out an output voltage which is of an order of few millivolts. One has to
note that this generated voltage is digital, that is, either 1 or 0. So, we can just know whether an
obstacle is present or not, One can refer to Fig, 28 to understand the working of IR sensor.
—>
IR sensor in the Generates a digital
> robot voltage output
Figure 2.8 Working on an IR sensor.
One can also read the data as analog. However, we choose digital in this exercise as the target
isto just detect the presence of an obstacle and not the size of the obstacle or other parameters.
By now readers must be wondering: Why always Adafruit? Is there no other cloud service provider
available? The answer is that you can choose any cloud service provider and code. Only some minimal
‘modifications are to be carried out in the code based an which the cloud service provider is chosen.
2.2.3 Interfacing the Heartbeat Sensor
This is one of the very interesting interfacing exercises. Nowadays there are many applica-
tions that use this sensor like the wearable applications which monitor the heartbeat accu-
rately. The applications are mostly in the healthcare domain and the sensor is inexpensive.
Here, in this exercise, heartbeat sensor is interfaced with Arduino UNO board and data is
loaded onto the cloud. A heartbeat sensor is shown in Fig. 2.9 for the reader to have a look
at how it looks. It is really small in size and affordable as well.
35WEG iticton sear, icon nd Taran
Figure 2.9 Heartbeat sensor.
The interfacing diagrams presented in Fig. 2.10. Again,one could use NodeMCU or Arduino
versions based on the availability and comfort.
Figure 2.10 Connection diagram for heartbeat sensor.
Code snippets 2.7, 2.8, and 2.9 reveal the pin initializations and data uploading part to
the cloud
WiFiclient me;
Adafruit MOT? Client mgt (éme, server, port, username, aickey) :
Adafruit MOTT Publish gas_data =
Adafruit MOTT Publish (smgtt,username”/feeds/heartbeat_data”);
Code Snippet 2.7 First part - Initialization.22) est Si
By performing an analog Read on the pin AO of Arduino, one can obtain data from the
heartbeat sensor. Code snippet 2.8 shows the code snippet for implementing the above task.
(GB) readers shovid understand tht the reed has to be analog read (oot dial ead) as one has to measure
= the xact count of heat nstead of measung whether he parson sale ore
void 1loop() {
if (mgt connected () )
1
int heartheat= analogRead (Ad);
Serial.printin (heartbeat);
Serial.print (*...");
Af (heartbeat_data.publish (heartbeat) )
{
Serial.printin (“success”);
’
else
{
Serial.print ("frying"):
1
)
delay (2000);
}
Code Snippet 2.8 Data acquisition and data upload
Code snippet 2.8 is meant for the data acquisition and the data upload. Code snippet 2.9 is
meant to understand if the heartbeat is normal or not. This is done by comparing the thresh-
old value with the read data.
Lf (BPM >= 80)
(
Serial.printin ("Rapid Heart beat”);
'
else if(BPM <= 32)
i
Serial.printin ("tow heatbeat");
'
else
4
Serial.println ("You are PINE..1!");
'
Code Snippet 2.9 Thresholding the heartbeat values.[ERED todiction to Sensors, Micocontrolrs, and Ther interfacing
Figure 2.11 represents how the heartbeat sensor functions. This sensor outputs a signal
which must be analysed using a special method called Pulse Width Modulation (PWM).
Fortunately, all this PWM will be done by the Arduino using the analog read command and
the programmer need not do anything in addition,
— —-
Heartbeat sensor Generates adigtl Calcuates the BPM
‘on he finger square wave es output (Goats per minute)
Figure 2.11 Usage and measurement of BPM using sensor.
%
(GB one can atvays ask: Do | have to know about al the sensors to learn oT? The answer is yes. Only then
[L_ can one choose the right sensor for an application,
2.2.4 Interfacing the Ultrasonic Sound Sensor
‘These sensors are generally used to measure the distance of the objects surrounding us. The
principle of these sensors is that they emanate ultrasonic sound which travels and hits the
object surrounding us. The received ultrasonic pulse is captured by the sensor. By perform-
ing some math on the obtained value, we can get the distance of the object from the sensor.
This sensor can only measure the distance from the object and cannot determine which
type of object is present around it. Now, let us dive into the coding part for ultrasonic sensor
(code snippets 2.10-2.12). A simple application which one can connect to the ultrasonic
sound sensor is automated parking. Figure 2.12 depicts how an ultrasonic sensor looks like.
‘The interfacing diagram is presented as Fig. 2.13.
Figure 2.12 Ultrasonic sensor.22 Types of Sensors
SIoc\toe
tered
Figure 2.13 Connection diagram for ultrasonic sensor (HC-SR04).
fdefine Trigger Pin 11 //D11
fdefine Echo pin 12 //D12
void setup()
i
Serial. becin (9500);
pinMode (Trigger Pin, OUTPUT);
pinMode(Echo_pin, INPUT);
'
Code Snippet 2.10 Pin initialization for transmitter and receiver pins.
Code snippet 2.10 deals with the initialization whereas code snippet 2.11 reveals the process
of generating and receiving the ultrasonic pulses. Code snippet 2.12 shows how the data is
uploaded to the cloud.
double duration , distance;
digitalWrite (Trigger_pin, Low); //Get Start
delayMicroseconds (5); //stable the line
//sending 10 micro seconds pulse
digitalwrite (Trigger_pin, HIGH);
delayMicroseconds (10); //delay
//waiting to recieve signals
digitalWrite(Trigger_pin, Low);
duration = pulsetn (Echo pin,HIGH); //calculating time
distance =(duration/2)/29.1 //Distance measurement step
Code Snippet 2.11 Code for measuring the distance of the obstacle.inizoduction to Sensors, Microcorivallrs, and Their interfacing
if (mgtt connected ())
{
if (ultrasonic data.publish (distance) }
fl
Serial.printin(*Success”);
'
else
{
Serial.printin(*Trying”);
}
Code Snippet 2.12 Uploading the data to Adafruit cloud,
5 x=)
Receiver Calculate the time taken Measures the distance
Sonic waves trom by rellected waves of the object
the sensor
Figure 2.14 Working of an ultrasonic sensor in real time.
Asimple diagrammatic representation of how ultrasonic sensor works is presented in Fig, 2.14,
| iteosoric sensor and ut
‘ound sensor are both the same.
2.2.5 Interfacing the Gyro Sensor
Gyro sensor is one of the most prominent sensors of present wearable technologies. It is
mostly used to find the posture or angle of rotation of a body. These sensors can sense
1. Rotational motion
2. Changes in orientation
These are the motions that humans have difficulty in sensing, This sensor is fabricated with
PC bus which is the most sophisticated two-wire communication protocol. It is used to com-
municate with more number of devices (say 1000 devices) at a time. Rather than having 1000
microcontrollers at a time to control all the devices, instead we can do it with just one micro-
controller. This example demonstrates a simple implementation of 12C bus with cloud com-
puting, A gyro sensor is presented in Fig. 2.15. The interfacing diagram is presented in Fig.22 eset seni
Figure 2.16 Connections diagram for MPU-6050 sensor.
Codes provided in code snippets 2.13 and 2.14 are used to begin the communication with
the gyro sensor and set the sensor in order to write the data to the microcontroller. Now, all
the data we get from the sensor comprises the x-, y-, z-axis values altogether. So, we have a
need to parse them and process the values individually, Code shown in the code snippet 2.14
does this job.Introduction to Sensors, Microcontrollers, and Their interfacing
void setupMPu()
i
Wire-beginTransmission(0b1101000); //This is the 12C address of the MPU
(b1101000/b1101001 fer ACO low/high datasheet sec. 9.2)
Wire.write(0x6s); //Accessing the register 63 - Power Management (Sec.
4.28)
Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note
on p. 9)
Wire.end?ransmission();
Wire-beginfransmission(0b1101000); //12C address of the MPU
Wire.write(0x1B); //Accessing the register 18 - Gyroscope Configuration
(sec. 4.4)
Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
Wire.end?ransmission();
}
Code Snippet 2.13 Code for communicating with the gyro sensor.
void recordgyroegisters() {
Wire.begin?ransnission{0b1101000); //12¢ address of the MPU
Wire.write (0x43); //Starting register for Gyro Readings
Wire.end?rananission();
Wire.requestFrom(0b1101000, 6); //Request Gyro Registers (43 - 48)
while (Wize.available() < 6);
gyroX = Wire.read() << 8 | Wire.read(); //Store first two bytes into accelX
gyroY = Wire.read() << 8 | Wire.read(); //Store middle two bytes into accelY
gyroz = Wire.read{) << 8 | Wire.read(); //Store last two bytes into accelZ
processGyroData();
,
void processGyrodata ()
(
rotX = gyrok / 131.0;
rotY = gyroY / 131.03
rot = gyroz / 131.07
Code Snippet 2.14 Parsing and processing the gyro data.
Now, the data has to be uploaded to the cloud and this task is accomplished through code
snippets 2.15 and 2.16.
WiFiclient me;
Adafruit MOTT Client mgt (éme,server,port, username, aickey) +
Adafruit MOTT Publishgas data~Adafruit MOTT Publish(amgtt, username”/feeds/
Gas_sensor”);
Code Snippet 2.15 Initializing Wi-Fi and Adafruit client.22 TypesofSensors AEE)
i (matt .connected())
4
Serial. print ("Uploading. .");
{Upload all the three axis values
gyro_data.publish (rotX);
gyro_data-publish (rotY);
gyro_data.publish (rotz);
Code Snippet 2.16 Uploading the rotation angle data from the gyro sensor.
Now an interesting question is: Can someone detect the fall of an elderly person? The
answer may be simple that it can be recognized through visionary inputs, But when we want
to detect a fall with sensors and implement IoT, the task becomes complex. So the answer
to our question is that by monitoring the posture of the person’s body one can obtain better
insights into when will the elder fall. This is where the gyro sensors come into the play. Figure
2.17 illustrates how the gyro sensor works.
:
¥
wes Cpe ayers
Gamma or 3. S07 S046
ric — % y, Z 506 503616 —>
Beta x,y, 2504 503.617
x.y, 2506 508 618
Placed sensor for Obtained values of Determine the elevation
Inclination measurement X,Y, Zaxes Using the axes alignment
Figure 2.17 Working of a gyro sensor.TE SS Ra TS
‘Typical applications of gyro sensors include:
1;
Angular Velocity Sensing: Sense the amount of angular velocity produced.
Used in measuring the amount of motion itself. For example, checking athletic
movement.
Angle Sensing: Senses angular velocity produced by the sensor’s own movement.
Angles are detected via integration operations by a CPU. The angle moved is fed
to and reflected in an application. Examples include car navigation systems, game
controllers, cellular.
Control Mechanisms: Senses vibration produced by external factors, and trans-
mits vibration data as electrical signals to a CPU, Used in correcting the orienta
tion or balance of an object. Examples include camera-shake correction, vehicle
control
2.2.6 Interfacing the LDR Sensor
Light dependent resistor (LDR) is a component that has a (variable) resistance which
changes with the light intensity that falls upon it. This allows them to be used in light sens-
ing circuits, Hence LDRs are the sensors which are employed in the fields where we have
a necessity of monitoring the intensity of light. Since the resistance of the sensor changes
with the intensity of the light, hence the output voltage value changes. By putting a simple
analog read statement in the code one could observe the output voltage values It is shown
in the code snippets 2.18 and 2.18. An LDR is presented in Fig. 2.18 along with its symbol.
‘The interfacing diagram is presented in Fig. 2.19.
Figure 2.18 LDR and its symbol
Code snippets 2.17 and 2.18 enable the data read. Also, the code enables one to upload
the data on to the cloud. Code snippet 2.18 showcases how to set the threshold limit which
enables the user to understand if the light intensity is dark or bright.Figure 2.19 Connections for the LDR sensor.
void loop () {
if (mgt -connected() )
4
//sead data from 7th digital pin
int Light_intensity= analogRead(AQ);
Serial. printin(Light_intensity);
Serdal.print(™...)7_
if (LDR_sensor.publish(Light_intensity))
(
Serial.printin(*Success”);
else
i
Serial.print (“Trying”);
t
}
delay (2000) ;
Code Snippet 2.17 Obtaining and uploading the dataIntroduction to Sensors, Microcontrollers, and Their interfacing
if (Light_intensity < 300)
feerintiertey (spatter
tise £8 idgne lntensiay > 900)
t gadtaz\peliein 730 Beghe”)
:
Code Snippet 2.18 Thresholding the sensor values
‘Figure 2.20 shows the working of the LDR.
% @ FR
Light whose intensity has Light focused onto LOR, Calculate the INTENSITY of
to be measured the light
Figure 2.20 Working of LDR.
‘Typical applications of LDRs include:
1. Power Saving/Smart Lighting: A common application of LDR is smart lighting that
turns on when a person enters a cabin and turns off when he/she leaves it. This is
also a feature in most escalators in malls. Also, automatic urinal flushing systems use
LDR as the major component.
2. Lighting Switch: The most obvious application for an LDR js to automatically turn
on a light at a certain light level. An example of this could be a street light or a
garden light.2.2 Types of Sensors
3. Camera Shutter Control: LDRs can be used to control the shutter speed on a
camera. The LDR would be used to measure the light intensity which then adjusts
the camera shutter speed to the appropriate level.
2.2.7 Interfacing the GPS
GPS sensors are widely used for acquiring the location data about the place where
the sensor is present (think OLA or UBER app for tracking cars). The data from the
sensor is acquired in NMEA (National Marine Electronics Association) format, which
is used by the marine department for communication. One can use this module (Fig. 2.21)
in the places where location tag is to be added. This is a very economical method for
getting the GPS data. In this section we will explain the interfacing process and also
how to upload the data to the cloud. Multiple variants of the GPS sensors are avail-
able in the market with various packaging options. One can select the appropriate one
based on the cost and other technical requirements. Interfacing diagram is presented as
Fig, 2.21. Code snippet 2.19 is meant to acquire the location data and code snippet 2.20
for uploading the data to cloud
Figure 2.21 Connections diagram for the GPS module.Introduction to Sensors, Microcontrollers, and Their Interfacing
Finclude
a TinyGPSt++ (TinyGPSPlus) object. Tt requires the use of SoftwareSerial,
assumes that you have a 9600-haud serial GPs device hooked up on pins 8(rx)
and 9(tx).*/
static const int RXPin = 8, TXPin = 3;
static const uint32_t GPsBaud = 9600;
// Toe TinyGPst+ object
‘TinyGPsPlus gps;
// Te serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
void setup()
4
Serial begin (115200);
ss-begin(GPSBaud) ¢
)
void Loop()
‘
encoded,
while (ss.available() > 0)
if (gps-encode(ss.read()))
displayinfo();
Lf (millis() > $000 && gps.charsProcessed() < 10)
i
Serial.printIn(*No GPS detected: check wiring.”
while (true) ;
)
void displaytnto() {
Serial.print (“Location: “);
if (gps.location. isvalid())
(
Serial.print (gps. location.lat(), 67
Serial.print (*,");
Serial.print (gps. location.1ng(), 67
rial.printin ();
Finclude /*This sample sketch denonstrates the normal use of
and
/f This sketch displays information every time a new sentence is correctly
Code Snippet 2.19 Parsed NMEA data to get location values.22 Wwoesof Sensors ZEN
void Loop ()
(
if (nqtt connected ())
(
GPS_sensor.publish(gps.location.latitude() , 6):
GPS_sensor.publish (gps.location.longitude() , 6);
delay(2000); //Upload for every 2 seconds
)
,
Code Snippet 2.20 Uploading data to the GPS sensor.
GPS sensors are used majorly for purposes like person or vehicle tracking around the globe.
Refer Fig, 2.22 to understand the scheme,
latitude
longitude
GPS device with antenna Roturns itd and “Tracked cation
tor eommunicaton Tonatude as outout
Figure 2.22 Scheme for live tracking of a vehicle.
2.2.8 Interfacing the Colour Sensor
Colour sensors are generally used to detect the RGB coordinates of a particular colour.
‘The colour sensor works by shining a white light on an object and then recording the
reflected colour. Through red, green, and blue colour filters the photodiode converts the
amount of light to current. These RGB values are further processed to find the exact colour
combination. The interfacing diagram is presented in Fig. 2.23.Introduction to Sensors, Microcontrollers, and Their interfacing
8
(Ola)
Figure 2.23 Connections diagram for colour sensor.
In code snippet 2.21,S2, and $3 pins are set to LOW, where LOW indicates red colour. Sim-
ilarly, for getting the blue and green values, these pins has to be set to HIGH, HIGH and
LOW, HIGH, respectively. Code snippet 2.22 helps the data read to be done on the cloud.
digitalWrite(s2, HIGH);
digitalWrite(s3, HIGH);
// Reading the output frequency
frequency = pulseIn(sensorOut, LOW)
//Remapping the value of the frequency to the RGB Model of 0 to 255
frequency = map(frequency, 30,90,255,0);
// Printing the value on the serial monitor
Serial.print("G= ");//printing name
Serial.print (frequency);//printing RED colour frequency
Serial.print(* ”);
delay (100);
// Setting Blue filtered photo diodes to be read
Code Snippet 2.21 Sample code for calculating the red colour.22 TypesofSonsors ERA
digitalnrite(S2,Low);
digitalWrite(s3,ATGH) +
// Reading the output frequency
frequency = pulseIn(sensorOut, LOW);
//Remapping the value of the frequency to the RGB Model of 0 to 255
frequency = map(frequency, 25, 70,255, 0)
Code Snippet 2.21 Continued.
if (matt.connected ())
‘
Colour_value.publish(Red_value) ;
Colour_value.publish(Green_value) ;
Colour_value-publish(Blue value);
Code Snippet 2.22 Uploading to the Adafruit cloud.
Colour sensors are mostly employed to detect the colour of the objects. These sensors give
the ability to a robotic eye to detect the colour and perform actions according to it. The
functioning of the RGB sensor is presented in Fig. 2.24.
asap
|
SS
~ Sy —
SEs
|
Colour sensor with ‘Output AGB colour Determine the
photodiodes atthe centre ‘coordinates ‘complexion of surface
Figure 2.24 Functioning of an RGB sensor.MRR sis sors irri ara art
2.2.9 Interfacing the pH Sensor
A pH sensoris used to detect hydrogen ion (H+) concentration of a liquid indicating its acidity
or alkalinity. When this sensor is immersed in a solution, the smaller ions are able to penetrate
the boundary area of the glass membrane and the larger ions remain in the solution which
creates a potential difference. The pH meter measures the difference in electrical potential
between the pH electrodes. It returns different analog values for different liquids. By knowing
the analog value of a known pH value liquid (like water, KC! solution), pH value for other
fluids can be determined. The interfacing diagram is presented in Fig. 2.25. Code snippets 2.23
and 2.24 reveal code for connections and uploading the same to the cloud.
Figure 2.25 Connections diagram for the pH sensor.
id Loop (void) {
static unsigned long samplingTime = millis();
unsigned long printTime = millis();
float plValue, voltage;
(millis()-samplingTime > si
pilArzay [pHArrayIndex++]=analogRead (
Lf (pHArrayIndex=-ArrayLenth) pHArrayIndex=0;
avergearray(pHArray, ArrayLenth)*
nsorPin) ;
/1024;
Code Snippet 2.23 Code for using pH sensor.23 Controlng Sensors trough Webpages
pValue = 3.5*voltage+offset;
samplingTimesmillis();
)
if(millis() - printTime > printinterval) //Every 800 milliseconds, print a
numerical, convert the state of the LED indicator
{
Serial.print (*Voltage:”);
Serial.print (voltage, 2);
Serial.print(* pi value:
Serial.printin (pivalue, 2);
digitalwrite(LEp, digitalnead (LED) ~1);
printTime=millis();
Code Snippet 2.23 Continued.
void loop) {
if (mgtt.connected())
{
//Uploading the pH value
ph_sensor.publish (pHvalue) ;
if (pvalue > 7.0)
{
Serial.print1n(*Alkaline");
)
else
{
Serial.printin ("Acidic");
)
Code Snippet 2.24 Thresholding the acidity of the fluid
pH sensors are mostly used in chemistry laboratories where acidity test is necessary to be
performed in order to determine the nature of any liquid. Acidity test consumes a lot of time
in done without the pH sensors. Figure 2.26 explains how pH value can be determined with
pH sensor.
Having learnt about sensors and their interfacing, itis also essential to know how to control
elements like the sensor, LED through a webpage.
Controlling Sensors through Webpages
Starting with the gas sensor (MQ series), Section 2.2 explained the interfacing procedure
with code and guidelines to upload data onto the cloud. Sensors like Obstacle sensor,introduction to Sensors, Microcontrolers, and Their Interfacing
acidic
5 6 7 8 9
—_ Py —
neutral
10 11-12 13 14
SEBuB
alkaline
Outputs voltage
Determine the alkalinity
pH sensor with electrodes corresponding to He ins nena
Figure 2.26 Determining the pH value using pH sensor.
heartbeat sensor, ultrasonic sound sensor, gyro sensor, GPS, LDR, colour sensor, and pH
sensor have been interfaced with computing boards. The next section talks about controlling
the LED through a webpage. This can be seen as an automation exercise. One can take this
forward to control the functioning of motor/fan through a webpage.
2.3.1 Controlling LED with a Webpage
In this section, we will discuss how to create a webpage which is used to remotely control
an LED with the help of NodeMCU. Follow the below steps for connections and creating
a webpage. Instead of LED, it can be any other sensor or actuator. Since LED is easy to
understand and simple to test, it has been chosen.
Before running the code, it is important to know the following that guide the reader to con-
nect the LED to NodeMCU and to set up the necessary steps:
1. Connect an LED on any Digital pin you prefer and change the number in the code
(D0, D1, etc. has to be properly updated).
2. Feed the SSID, password of the available and accessible Wi-Fi network.
3. Inthe Arduino IDE, Go to Tools > Boards Select NodeMCU 1.0 (ESP-12E Module).
‘Then upload the code with the regular procedure.
4. One should open the serial monitor in the Arduino IDE after which RST button in
the NodeMCU should be pressed and one could see an IP assigned and displayed.
It is the IP assigned for NodeMCU. Also, one shall get the following messages out in
the serial monitor:
Connecting to *#**
Wi-Fi connected
Server started2.2 Controling Sensors through Webpage
Use this URL to connect: http://192.168.43.121/ (This could vary)
new client
GET /HTTP/LL
Client disconnected
5. One can open any browser from the phone or PC and type http://192.168.43.121/
(this could certainly vary from time to time.)
6 One would see ON/OFF buttons on the screen. On pressing them, one can see the
LEDs glowing/closing.
‘The complete code is presented below for easier understanding,
#include
const char* ssid = “#*#**«"; // Type your WiFi username
const char* password = “*#*#*"; // Type your WiFi Password
int ledPin = D0;
// Change the digital pin to which LED is connected. (Heze, NodeMCU DO Pin is
// used)
wiFiserver server (80);
void setup() {
Serial begin (115200);
// Bs usual, this is just to set up the baud rate. Make sure you have the same
// baudrate in your serial monitor.
delay(50)7
pinMode(ledPin, OVTPUT); // Contiqure LED as output
digitalWrite(ledPin, LOW); // Initially, OFF.
// Connect to WiFi network. All these will appear in the screen.
Serial.println();
Serial.println()s
Serial.print (“Connecting to “)7
Serial.print1n (ssid);
WiFi begin (ssid, password);
// Connect! You shall have the TETHERING REPORT as 1 device connected.
while (WiFi.status()
delay (500);
Serial.print(*.");
}
CONNECTED) {Introduction to Sensors, Microcontrollers, and Their Interfacing
Serial.printin(™);
Serial.println("Wifi connected”);
J) Stazt the server
server.begin();
Serial.printin ("Server started”);
// exint the IP address
Serial.print("Use this URL to connect: “);
Serial.print (“http://") 7
Serial.print(WiFi.localIP()); // Watchout, this is an important step!
serial.printin("/”);
}
void loop () {
// Check if a client has connected
WiFiclient client = server.available();
if (Iclient) [
return;
'
// Wait until the client sends some data
Serial.printin(*new client”);
while (!client .available()) (
delay (1);
'
// Read the first line of the request
string request - client.readStringuntil(*\r');
Serial.printin(request) ;
elient.flush(};
J/ Match the request
int value = Low;
if (request. indexof (*/LE!
digitalWrite(ledPin, HIGH);
value = HIGH;
i
£ (request. indexof ("/LED=OFF”)
digitalWrite(ledPin, LOW);
value = LOW;
:
IN") t= -1) {
-1)
// Set ledPin according to the request
// digitalWrite(ledPin, value);
// Return the response
elient.println("HTTP/1.1 200 0K");24 Wie A Rag
client.printin(*Content~Type: text/ntml”);
client.printin(™");
client.printin("”) ;
client.printin(*chtml>");
client.print("Led is now:
if(value == RIGH) {
client.print (“on”);
} else {
client.print ("Off");
client.printin(*