0% found this document useful (0 votes)
6 views

Module 4

Uploaded by

avogadroangster
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module 4

Uploaded by

avogadroangster
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Module 4

Programming The Microcontroller For IoT


Working principles of sensors
• A sensor is able to measure a physical phenomenon (like
temperature, pressure, and so on) and transform it into an electric
signal.
• A sensor can be described using several properties, the most
important being:
• Range: It is the minimum and maximum value of physical variable
that the sensor can sense or measure.
• For example, a Resistance Temperature Detector (RTD) for the
measurement of temperature has a range of -200 to 800oC.
• Span: It is the difference between the maximum and minimum values
of input. In above example, the span of RTD is 800 – (-200) = 1000oC.
• Accuracy: The error in measurement is specified in terms of
accuracy.
• It is defined as the difference between measured value and true
value.

• Sensitivity: It is the ratio of change in output to change in input.


• Linearity: Linearity is the maximum deviation between the measured
values of a sensor from ideal curve.
• Resolution: It is the minimum change in input that can be sensed by
the sensor.
• Response Time: It is generally expressed as the time at which the
output reaches a certain percentage (for instance, 95%) of its final
value, in response to a step change of the input.
Classification of Sensors
• Active and Passive Sensors
• Active Sensors (also known as parametric sensors) are sensors that
require an external power source to operate.
• Examples of active sensors include GPS sensors and radar
sensors.
• Passive Sensors (also called self-generated sensors) generate their
own electric signal and do not require any external power source.
• Examples of passive sensors include thermal sensors, electric
field sensing, and metal detecting.
Contact and Non-Contact Sensors
• Contact Sensors are those that require physical contact with their
stimulus.
• Familiar examples of contact sensors are temperature and strain
gauge sensors.
• Non-Contact Sensors, on the other hand, require no physical
contact. These types of sensors include optical and magnetic
sensors, as well as infrared thermometers.
Absolute and Relative Sensors
• Absolute Sensors mimic its name by providing an absolute reading
of its stimulus.
For example, a thermistor always measures the exact, or
absolute, temperature reading.
• Relative Sensors provide measurement to a fixed or variable
measurement.
An example of a relative sensor would be a thermocouple, where
the temperature difference is measured, not the actual
temperature.
• Analog and Digital Sensors
• Analog Sensors produce continuous analog output signals,
proportional to its measurement.
• A few examples of analog sensors are: accelerometers,
pressure sensors, light, and sound sensors.
• Digital Sensors (also known as electronic or electrochemical
sensors) convert the data transmission, digitally.
• Examples include digital accelerometers, pressure, and
temperature sensors.
• The most common sensors are typically used for measuring physical
properties
• Temperature Sensor
• CO2 Sensor
• Proximity Sensor
• Accelerometer
• IR Sensor (Infrared Sensor)
• Pressure Sensor
• Light Sensor
• Smoke, Gas, and Alcohol Sensor
• Touch Sensor
• Temperature Sensor
• TMP36 is a low voltage, precision centigrade temperature sensor
• Temperature range -40°C to 125°C
• It is a chip that provides a voltage output that is linearly proportional to the
temperature in °C
• 0.1V (-40°C) to 1.75V (125°C)
• How to Measure Temperature
To convert the voltage to temperature, simply use the basic formula:
Temp (°C) = (Vout – 0.5) * 100

right pin to ground


left pin to power (2.7-5.5V)

middle pin will have an analog voltage that is directly propo


(linear) to the temperature in °C
• Gas Sensor
• Gas sensor suitable for sensing LPG, Smoke, Alcohol, Propane, Hydrogen,
Methane and Carbon Monoxide concentrations in the air.
• If you are planning on creating an indoor air quality monitoring system;
breath checker or early fire detection system, MQ2 Gas Sensor Module is a
great choice
enclosed in two layers of fine
It not only provides a binary indication of the presence of stainless steel mesh
combustible gases but also an analog representation of their
concentration in air.
• Ultrasonic sensors
• HC-SR04 Ultrasonic Distance Sensor that can report the range of objects up to
13 feet away

Ultrasound is high-pitched sound waves with


frequencies higher than the audible limit of
human hearing.
• It use a single transducer to send a pulse and to receive the echo.
• The sensor determines the distance to a target by measuring time
lapses between the sending and receiving of the ultrasonic pulse.
• It sends an ultrasonic pulse out at 40kHz which travels through the
air and if there is an obstacle or object, it will bounce back to the
sensor.
• By calculating the travel time and the speed of sound, the distance
can be calculated.
• Soil Moisture Sensor
• With this type of system, you can water your plants only when needed and
avoid over-watering or under-watering.
• The fork-shaped probe with two exposed conductors, acts as a variable
resistor (just like a potentiometer) whose resistance varies according to the
water content in the soil.
For example, when the moisture level in the soil crosses a
threshold, you can activate a relay to start pumping water.
• Water Level Sensor
• The sensor has a series of ten exposed copper traces, five of which
are power traces and five are sense traces.
The sensor produces an output voltage according to the
resistance, which by measuring we can determine the water
level.
• Rain sensor
• Sound Sensor
Note - Conductor resistance
• electrical conductivity and resistivity are inversely proportional,
meaning that the more conductive something is the less resistive it is.
• The resistance of a conductor can be calculated at a temperature
of 20°C using
For programming

• Analog Sensors
• Analog Sensors produce a continuous output signal or voltage
which is generally proportional to the quantity being measured.
• Physical quantities such as Temperature, Speed, Pressure,
Displacement, Strain etc. are all analog quantities as they tend to
be continuous in nature.
• For example, the temperature of a liquid can be measured using a
thermometer or thermocouple (e.g. in geysers) which
continuously responds to temperature changes as the liquid is
heated up or cooled down.
• Digital Sensors
• Digital Sensors produce discrete digital output signals or voltages
that are a digital representation of the quantity being measured.
• Digital sensors produce a binary output signal in the form of a logic
“1” or a logic “0”, (“ON” or “OFF”).
• Digital signal only produces discrete (non‐continuous) values,
which may be output as a single “bit” (serial transmission), or by
combining the bits to produce a single “byte” output (parallel
transmission).
• Scalar Sensors
• Scalar Sensors produce output signal or voltage which is generally
proportional to the magnitude of the quantity being measured.
• Physical quantities such as temperature, color, pressure, strain,
etc. are all scalar quantities as only their magnitude is sufficient to
convey an information.
• For example, the temperature of a room can be measured using a
thermometer or thermocouple, which responds to temperature
changes irrespective of the orientation of the sensor or its
direction.
• Vector Sensors
• Vector Sensors produce output signal or voltage which is generally
proportional to the magnitude, direction, as well as the
orientation of the quantity being measured.
• Physical quantities such as sound, image, velocity, acceleration,
orientation, etc. are all vector quantities, as only their magnitude
is not sufficient to convey the complete information.
• For example, the acceleration of a body can be measured using an
accelerometer, which gives the components of acceleration of the
body with respect to the x,y,z coordinate axes.
Actuator
• An actuator is a component of a machine or system that moves or
controls the mechanism or the system.
• An actuator is the mechanism by which a control system acts upon an
environment
• An actuator requires a control signal and a source of energy.
• Upon receiving a control signal is received, the actuator responds by
converting the energy into mechanical motion.
• The control system can be simple (a fixed mechanical or electronic
system), software‐based (e.g. a printer driver, robot control system), a
human, or any other input.
Arduino
• Arduino is a prototype platform (open-source) based on an easy-to-
use hardware and software.
• It consists of a circuit board, which can be programed (referred to as a
microcontroller) and a ready-made software called Arduino IDE
(Integrated Development Environment), which is used to write and
upload the computer code to the physical board.
• key features
• read analog or digital input signals from different sensors and turn it into an
output such as activating a motor, turning LED on/off, connect to the cloud
and many other actions
• sending a set of instructions to the microcontroller on the board via Arduino
IDE
Board
Software
• Download the software - https://www.arduino.cc
Program structure
• Sketch − The first new terminology in the Arduino program called “sketch”
• Arduino programs can be divided in three main parts: Structure, Values (variables and constants),
and Functions.
• Software structure consist of two main functions −
• Setup( ) function
• Loop( ) function
• The setup() function is called when a sketch starts. Use it to initialize the variables, pin modes,
start using libraries, etc. The setup function will only run once, after each power up or reset of the
Arduino board.
• After creating a setup() function, which initializes and sets the initial values, the loop() function
does precisely what its name suggests, and loops consecutively, allowing your program to change
and respond.
• Data types

void Boolean char Unsigned byte int Unsigned word


char int
long Unsigned short float double array String-char String-
long array object

• void
• The void keyword is used only in function declarations. It indicates that the
function is expected to return no information to the function from which it
was called.
Blinking LED
• Task: Get a LED to blink.
• Required equipment: Just the microcontroller board with the USB
cable.
• First part of the program: Name variables
• Second part of the program: Setup
• We only have one output – Pin 13 should put out voltage (The LED should
light up.)
void setup() //The setup begins here
{ //opening curly bracket – A program part begins here

} //closing
• Now we are going to write the setup information between the curly
brackets.
• In this case: “pin 13 is supposed to be an output” :
void setup()
{
pinMode(13, OUTPUT); //Pin 13 is supposed to be an output.
}
• Third part of the program: Loop (main part):
void loop()
{
digitalWrite(13, HIGH); //Turn on the voltage on pin 13 (LED on)
delay(1000); //Wait for 1000 milliseconds (one second)
digitalWrite(13, LOW); //Turn off the voltage on pin 13 (LED off)
delay(1000); //Wait for 1000 milliseconds (one second)
}
• Suppose if you want the LED to blink really fast then set delay to 200
Introduction to Arduino Programming

• Operators in Arduino
• Control Statement
• Loops
• Arrays
• String
• Math Library
• Random Number
• Interrupts
• Example Program
Arduino IDE
• Program coded in Arduino IDE is called a SKETCH
• To create a new sketchFile -> New
• To open an existing sketch
• File -> open ->
• There are some basic ready-to-use sketches available in the
EXAMPLES section
• File -> Examples -> select any program
• Verify: Checks the code for compilation errors
• Upload: Uploads the final code to the controller board
• New: Creates a new blank sketch with basic structure
• Open: Opens an existing sketch
• Save: Saves the current sketch
• Serial Monitor: Opens the serial console
• All the data printed to the console are displayed here
Sketch Structure
• A sketch can be divided into two parts:
• Setup ()
• Loop()
• The function setup() is the point where the code starts, just like the
main() function in C and C++
• I/O Variables, pin modes are initialized in the Setup() function
• Loop() function, as the name suggests, iterates the specified task in
the program
Supported Datatype
Arduino supports the following data types
• Void Long • Unsigned long
• Int • Float
• Char • Double
• Boolean • Array
• String-char array
• Unsigned
• String-object Short
• Char
• Byte
• Unsigned int
• Word
Arduino Function Libraries

• Input/Output Functions
• The arduino pins can be configured to act as input or output pins
using the pinMode() function

Void setup ()
{
pinMode (pin , mode);
}

Pin- pin number on the Arduino board


Mode- INPUT/OUTPUT
Arduino Function Libraries
• digitalWrite() : Writes a HIGH or LOW value to a digital pin
• digitalRead() : Read value from digital pin (ON/OFF)
• analogRead() : Reads from the analog input pin i.e., voltage applied
across the pin
• Character functions such as isdigit(), isalpha(), isalnum(), isxdigit(),
islower(), isupper(), isspace() return 1(true) or 0(false)
• Delay() function is one of the most common time manipulation
function used to provide a delay of specified time. It accepts integer
value (time in miliseconds)
Alternately blinking LED
void setup()
{
pinMode(7, OUTPUT); //Pin 7 is defined as output
pinMode(8, OUTPUT); //Pin 8 is defined as output
}
void loop()
{
digitalWrite(7, HIGH); //turn on the LED on pin 7
delay(1000); //wait for 1000 milliseconds
digitalWrite(7, LOW); //turn off the LED on pin 7
digitalWrite(8, HIGH); //turn on the LED on pin 8
delay(1000); //wait for 1000 milliseconds
digitalWrite(8, LOW); //turn off the LED on pin 8
}
Fading LED
• Task: A LED should pulsating get brighter and darker (fade).
• Arduino is a digital microcontroller and it knows only 5V ON.
• To vary the brightness of the LED – vary the voltage of the output
• i.e 5 Volts if the LED shines bright, 4 Volts if it shines a bit darker and
so on
• But, how can we do this in digital pins?
• Pulse width modulation (PWM)
• When to use PWM?
• Not all pins are PWM only pins marked with ~ is PWM pins.
Code – fading LED

//name variable
int LED=9; // rename the pin this is optional
int brightness=0;
int fading=5;
void setup()
{
pinMode(LED, OUTPUT);
}
void loop()
{
analogWrite(LED, brightness); // you are starting it from 0
brightness = brightness + fading; // modify the value of brightness
delay(25); // LED should stay bright for a short duration

if(brightness == 0 || brightness == 255) // how long brightness should increase/decreas


(
fading= -fading;
}
}
Light and sound
• Task: A LED and a piezo speaker are supposed to blink and beep.

i.e When LED is glowing, the


speaker also should beep
When the LED is not glowing, the
speaker should be in off state
int LED = 4;
int beep = 5;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(beep, OUTPUT);
}
void loop()
{
digitalWrite(LED, HIGH); //turn on the LED
digitalWrite(beep, HIGH); //turn on the speaker
delay(1000); //wait for 1000 milliseconds (sound and light)
digitalWrite(LED, LOW); //turn off the LED
digitalWrite(beep, LOW); //turn off the speaker
delay(1000); //wait for 1000 milliseconds (no sound and no light)
}
Giving input and producing output
Push button and LED
• Task: After pushing the button an LED is supposed to light up for 5
seconds.
int LEDblue = 6; // giving names to the pins
int button = 7;

int buttonstatus = 0;

void setup()
{
pinMode(LEDblue, OUTPUT);
pinMode(button, INPUT);
}
void loop()
{
buttonstatus = digitalRead(button);
if (buttonstatus == HIGH)
{
digitalWrite(LEDblue, HIGH);
delay(5000);
digitalWrite(LEDblue, LOW);
}
else
{
digitalWrite(LEDblue, LOW);
}
}
RGB Light
• Task: We want a RGB LED to light up in different colours
Using sensor library
• Humidity sensor (DHT22)
• The DHT-22 (also named as AM2302) is a digital-output, relative humidity,
and temperature sensor.
• It uses a capacitive humidity sensor and a thermistor to measure the
surrounding air, and sends a digital signal on the data pin.
// Initialize DHT sensor
DHT22 dht(A0);
void setup()
{
Serial.begin(9600);
Serial.println("DHT22 Humidity Value");
dht.begin();
}
void loop()
{
dht.readHumidity();
Serial.print(dht.humidity);
delay(3000);
}
Actuators
• Servo motor
• Servo is a general term for a closed loop control system.
• A closed loop system uses the feedback signal to adjust the speed and
direction of the motor to achieve the desired result.
• The length of the pulse determines the position of the servo motor.

Pulses ranging between 1ms and


2ms will move the servo shaft
through the full 180 degrees of its
travel.
• Servo motors typically have three connections and are as follows:
• Check notepad for code
Temperature Sensor LM35 - used to measure temperature in (°C)
The output voltage range of this sensor is from -55˚ to +150˚C.
float temp;
int tempPIN = A0;

void setup()
{
Serial.begin(9600);
}
void loop()
{
temp = analogRead(tempPin);
temp = temp * 0.48
Serial.print(“Temperature = ”)
Serial.print(temp);
}
• Water Sensor
• Connecting a water sensor to an Arduino is a great way to detect a leak, spill,
flood, rain, etc.
• It can be used to detect the presence, the level, the volume and/or the
absence of water.
• While this could be used to remind you to water your plants, there is a better
Grove sensor for that.
• The sensor has an array of exposed traces, which read LOW when water is
detected.
int Grove_Water_Sensor = 8
int LED = 9
void setup()
{
pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input
pinMode(LED, OUTPUT); // The LED is an Output
}

void loop()
{
if( digitalRead(Grove_Water_Sensor) == LOW)
{
digitalWrite(LED,HIGH);
}
else
{
digitalWrite(LED,LOW);
}
• Measure a distance with the HC-SR04 ultrasonic sensor and show the
result on the serial monitor. If the distance is less than 80cm, the
piezo speaker should beep.
• Check the notepad for program
• Passive Infra Red sensors can detect movement of objects that radiate
IR light.
• The output of PIR motion detection sensor can be connected directly
to one of the Arduino (or any microcontroller) digital pins. If any
motion is detected by the sensor, this pin value will be set to “1”.
• That means when a human or animal body will get in the range of the
sensor it will detect a movement because the human or animal body
emits heat energy in a form of infrared radiation
Communication
• IoT devices require a mechanism to send or receive data
• Connecting devices to the Internet - wired and wireless options,
Bluetooth, cellular networks, Wifi
• Factors for choosing the connectivity
• Scale and size of the network where the application will run
• Amount of data that needs to be processed and transferred
• Physical location of the device
Wired connectivity
• Attach an Ethernet shield to your Arduino Uno

Connect an Ethernet cable from Arduino to the LAN (Local


Area Network) port of your router. The router should already
be connected to the Internet.
Wireless connectivity
• Bluetooth module
• HC-05 is a Bluetooth device used for wireless communication with Bluetooth
enabled devices (like smartphone). It communicates with microcontrollers
using serial communication (USART).
• Default settings of HC-05 Bluetooth module can be changed using certain AT
commands.
• Key/EN: It is used to bring Bluetooth module in AT commands mode. If Key/EN
pin is set to high, then this module will work in command mode. Otherwise by
default it is in data mode. The default baud rate of HC-05 in command mode is
38400bps and 9600 in data mode.
• HC-05 module has two modes,
1. Data mode: Exchange of data between devices.
2. Command mode: It uses AT commands which are used to change
setting of HC-05. To send these commands to module serial (USART)
port is used.
• VCC: Connect 5 V or 3.3 V to this Pin.
• GND: Ground Pin of module.
• TXD: Transmit Serial data (wirelessly received data by Bluetooth module
transmitted out serially on TXD pin)
• RXD: Receive data serially (received data will be transmitted wirelessly by
Bluetooth module).
• State: It tells whether module is connected or not.
• It is used for many applications like wireless headset, game
controllers, wireless mouse, wireless keyboard and many more
consumer applications.
• It has range up to <100m which depends upon transmitter and
receiver, atmosphere, geographic & urban conditions.
• It is IEEE 802.15.1 standardized protocol, through which one can build
wireless Personal Area Network (PAN). It uses frequency-hopping
spread spectrum (FHSS) radio technology to send data over air.
• It uses serial communication to communicate with devices. It
communicates with microcontroller using serial port (USART).
• As HC-05 Bluetooth module has 3.3 V level for RX/TX and
microcontroller can detect 3.3 V level.
• we need to shift the transmit voltage level from microcontroller to RX
of HC-05 module.
Bluetooth communication between Devices
• E.g. Send data from Smartphone terminal to HC-05 Bluetooth module
and see this data on PC serial terminal and vice versa.
• When we want to communicate through smartphone with HC-05
Bluetooth module, connect this HC-05 module to the PC via serial to
USB converter.
• Before establishing communication between two Bluetooth devices,
1st we need to pair HC-05 module to smartphone for communication.
• Search for new Bluetooth device from your phone. You will find Bluetooth
device with “HC-05” name.
• Click on connect/pair device option; default pin for HC-05 is 1234 or 0000.
• After pairing two Bluetooth devices, open terminal software in PC,
and select the port where we have connected USB to serial module.
Also select default baud rate of 9600 bps.
• In smart phone, open Bluetooth terminal application and connect to
paired device HC-05.
• Find the module's serial port name in "devices and printers"
• In the Arduino IDE, choose serial port of Bluetooth module (e.g
COM10). Open the serial monitor as normal to view incoming
information
Example
Transmit data from Smartphone via Bluetooth to the Arduino Uno and display it on
#include<SoftwareSerial.h>
SoftwareSerial bt(2,3);
void setup()
{
bt.begin(9600);
Serial.begin(9600);
}
void loop()
{
if (bt.available()) /* If data is available on serial port */
{
Serial.write(bt.read()); /* Print character received on to the serial monitor */
}
}
Wifi Module
• ESP8266 wifi module is low cost standalone wireless transceiver that
can be used for end-point IoT developments.
• ESP8266 wifi module enables internet connectivity to embedded
applications. It uses TCP/UDP communication protocol to connect
with server/client.
• ESP8266 is strictly powered only to 3.3 V. More than that will destroy
the module.
• VCC: It is the power pin through which 3.3V is supplied.
• GND: It is the ground pin.
• TX: This pin is used to transmit serial data to other devices.
• RX: The RX pin is used to receive serial data from other devices.
• RST: It is the Reset Pin and it is an active LOW Pin. (ESP8266 will reset
if the RST pin receives LOW signal).
• CH_PD: This is the chip enable pin and it is an active HIGH Pin. It is
usually connected to 3.3V.
• GPIO0: The GPIO0 (General Purpose I/O) Pin has dual functions – one
for normal GPIO Operation and other for enabling the Programming
Mode of ESP8266.
• GPIO2: This is GPIO Pin.
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX
void setup()
{
Serial.begin(115200); // communication with the host computer
// Start the software serial for communication with the ESP8266
ESPserial.begin(115200);
Serial.println("");
Serial.println("Ready");
Serial.println("");
}
void loop()
{
// listen for communication from the ESP8266 and then write it to the serial monitor
if ( ESPserial.available() )
{ Serial.write( ESPserial.read() ); }
// listen for user input and send it to the ESP8266
if ( Serial.available() )
{ ESPserial.write( Serial.read() ); }
}
Cooja Network Simulator
• Contiki is an operating system for IoT that specifically targets
small IoT devices with limited memory, power, bandwidth, and
processing power.
• It uses a minimalist design while still packing the common tools
of modern operating systems.
• It provides functionality for management of programs,
processes, resources, memory, and communication.
• Contiki only requires a few kilobytes to run, and within a space
of under 30KB, it fits its entire operating system

Dheeba. J/VIT, Vellore 88


What does a Contiki does?

Dheeba. J/VIT, Vellore 89


• Using Cooja proves simple. Simply create a new mote type by
selecting the Motes menu and Add Motes → Create New
Mote Type

Dheeba. J/VIT, Vellore 90


Dheeba. J/VIT, Vellore 91
• Thank YOU

You might also like