Internet of Things
Hands-On
1
The Internet of Everything (IoE) brings together people, process, data, and things to make networked connections more relevant and valuable than ever before-turning information into actions that create new capabilities, richer experiences, and unprecedented economic opportunity for businesses, individuals, and countries.
3
4
Before After (Generates Enough Data)
... fan engagement, audience engagement, training (Dangal !), fitness...
5
6
Activity Trackers
Fitbit helps you live a healthy, balanced life by tracking your all-day activity, exercise, sleep, and weight.
7
9
What is IoT?
10
12
Microcontroller-based devices are more constrained & your application code run directly on the processor without the support of an OS.
13
14
Arduino Pinout - https://www.arduino.cc/en/Main/FAQ
15
The ATmega328 is a single-chip microcontroller created by Atmel in the megaAVR family.
Arduino Uno Specifications
16
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off.
For example, we can use PWM to change the brightness of an LED; the wider the “ON” pulses, the brighter the LED glows.
Description
Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are:
Syntax
analogReference(type)
Parameters type: which type of reference to use (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, or EXTERNAL)
17
Arduino IDE - Download from https://www.arduino.cc/en/Main/Software
18
19
20
Built-in (Pin 13) LED Blink
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
22
RGB - LED
23
1 - RGB Connections - Safer to connect via resistors
24
2 - RGB Connections - Safer to connect via resistors
25
If you want to use it for common cathode leds you'll have to change all the "analogWrite( COLOR, 255 - colorVal );" lines to "analogWrite( COLOR, colorVal );" (without the "255 - "), then it should work (i didn't test it). http://www.instructables.com/id/Fading-RGB-LED-Arduino/?ALLSTEPS
#define GREEN 3
#define BLUE 5
#define RED 6
#define delayTime 20
void setup() {
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
pinMode(RED, OUTPUT);
digitalWrite(GREEN, HIGH);
digitalWrite(BLUE, HIGH);
digitalWrite(RED, HIGH);
}
int redVal;
int blueVal;
int greenVal;
void loop() {
int redVal = 255;
int blueVal = 0;
int greenVal = 0;
for( int i = 0 ; i < 255 ; i += 1 ){
greenVal += 1;
redVal -= 1;
analogWrite( GREEN, 255 - greenVal );
analogWrite( RED, 255 - redVal );
delay( delayTime );
}
26
Fading RGB
redVal = 0;
blueVal = 0;
greenVal = 255;
for( int i = 0 ; i < 255 ; i += 1 ){
blueVal += 1;
greenVal -= 1;
analogWrite( BLUE, 255 - blueVal );
analogWrite( GREEN, 255 - greenVal );
delay( delayTime );
}
redVal = 0;
blueVal = 255;
greenVal = 0;
for( int i = 0 ; i < 255 ; i += 1 ){
redVal += 1;
blueVal -= 1;
analogWrite( RED, 255 - redVal );
analogWrite( BLUE, 255 - blueVal );
delay( delayTime );
}
}
int ledcolor = 0; //http://www.instructables.com/id/Arduino-Examples-1-Make-An-RGB-Led-Randomly-Flash/?ALLSTEPS
int a = 1000; //this sets how long the stays one color for
int red = 11; //this sets the red led pin
int green = 12; //this sets the green led pin
int blue = 13; //this sets the blue led pin
void setup() { //this sets the output pins
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}
void loop() {
int ledcolor = random(7); //this randomly selects a number between 0 and 6
switch (ledcolor) {
case 0: //if ledcolor equals 0 then the led will turn red
analogWrite(red, 204);
delay(a);
analogWrite(red, 0);
break;
case 1: //if ledcolor equals 1 then the led will turn green
digitalWrite(green, HIGH);
delay(a);
digitalWrite(green, LOW);
break;
case 2: //if ledcolor equals 2 then the led will turn blue
digitalWrite(blue, HIGH);
delay(a);
digitalWrite(blue, LOW);
break;
case 3: //if ledcolor equals 3 then the led will turn yellow
analogWrite(red, 160);
digitalWrite(green, HIGH);
27
RGB Random Colors
delay(a);
analogWrite(red, 0);
digitalWrite(green, LOW);
break;
case 4: //if ledcolor equals 4 then the led will turn cyan
analogWrite(red, 168);
digitalWrite(blue, HIGH);
delay(a);
analogWrite(red, 0);
digitalWrite(blue, LOW);
break;
case 5: //if ledcolor equals 5 then the led will turn magenta
digitalWrite(green, HIGH);
digitalWrite(blue, HIGH);
delay(a);
digitalWrite(green, LOW);
digitalWrite(blue, LOW);
break;
case 6: //if ledcolor equals 6 then the led will turn white
analogWrite(red, 100);
digitalWrite(green, HIGH);
digitalWrite(blue, HIGH);
delay(a);
analogWrite(red, 0);
digitalWrite(green, LOW);
digitalWrite(blue, LOW);
break;
}
}
123d.circuits.io - Design, Compile, and Simulate your electronic projects Online – for Free
28
29
30
33
34
Sensors Bring IoT Projects to Life
Sensors are the nose, eyes and ears…Without sensors, there's no IoT. src
35
36
LM35 Analog Temperature Sensor
37
LM35 Features
38
LM35 Applications
39
LM35 Analog Temperature Sensor Connections
40
Always connect LM35 on Arduino Board directly
const int groundpin = A0;
const int powerpin = A2;
int tempPin = A1;
float tempC;
float reading;
void setup() {
Serial.begin(9600);
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
analogReference(INTERNAL);
}
void loop() {
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.print("Temperature: ");
Serial.println(tempC);
delay(1000);
}
41
const int groundpin = A0;
const int powerpin = A2;
int tempPin = A1;
float tempC;
int reading;
int led=13;
int con=0;
void setup() {
Serial.begin(9600);
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
pinMode(led, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
analogReference(INTERNAL);
}
42
void loop() {
if(Serial.available() > 0) {
con = Serial.read();
}
if(con == '1') {
digitalWrite(led, HIGH);
} else {
digitalWrite(led, LOW);
}
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.println(tempC);
delay(1000);
}
Analog-to-Digital Converter (ADC)
Analog pins might have access to an on-board Analog-to-Digital Converter (ADC) circuit.
When we read the value of a digital I/O pin in code, the value must be either HIGH or LOW, where an analog input pin at any given moment could be any value in a range.
The range depends on the resolution of ADC. For example an 8-bit ADC can produce digital values from 0 to 255, while a 10-bit ADC can yield a wider range of values, from 0 to 1023. More values manes higher resolution and thus a more faithful digital representation of any given analog signal.
43
44
LDR - Light Dependent Resistor Sensor
45
LDR Sensor - Resistance vs Light Intensity
46
LDR Connections
47
//http://www.hobbytronics.co.uk/arduino-tutorial8-nightlight
int sensorPin = A0; // select the input pin for the ldr�unsigned int sensorValue = 0; // variable to store the value coming from the ldr�void setup()�{� pinMode(13, OUTPUT);� //Start Serial port� Serial.begin(9600); // start serial for output - for testing�}�void loop()�{� // read the value from the ldr:� sensorValue = analogRead(sensorPin);
Serial.println(sensorValue); � if(sensorValue>500) digitalWrite(13, HIGH); // set the LED on� else digitalWrite(13, LOW); // set the LED on � // For DEBUGGING - Print out our data, uncomment the lines below� //Serial.print(sensorValue, DEC); // print the value (0 to 1024)� //Serial.println(""); // print carriage return � //delay(500); �}
48
Blink the LED if LDR crosses 500
DHT11 - Digital Humidity and Temperature
Safer to connect a resistor between pin 1 and 2
49
DHT11 Features
50
DHT11 Applications
51
#include "DHT.h"
#define DHTPIN 2 // what pin we're connected to
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity
//takes about 250 milliseconds!
// Sensor readings may also be up to
//2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
52
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hi);
Serial.println(" *F");
}
DHT Full Device
#include "DHT.h"
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
int luxPin = A5;
int relay_pin = 13;
int cloud_in;
float tempC;
int intensity;
const int tempPin = A1;
const int groundPin = 14;
const int powerPin = 16;
void setup() {
Serial.begin(9600);
pinMode(relay_pin, OUTPUT);
dht.begin();
}
void loop() {
intensity = analogRead(luxPin);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
53
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
//Serial.print("Humidity: ");
//Serial.print(h);
//Serial.print(" %\t");
//Serial.print("Temperature: ");
Serial.print(t);
Serial.print("-");
Serial.print(h);
Serial.print("-");
//Serial.print(" *C ");
//Serial.print(f);
//Serial.print(" *F\t");
//Serial.print("Heat index: ");
//Serial.print(hi);
//Serial.println(" *F\t");
//Serial.println("Intensity: ");
Serial.println(intensity/200);
if(Serial.available() > 0) {
cloud_in = Serial.read();
if(cloud_in == '0') {
digitalWrite(relay_pin, LOW);
}
if(cloud_in == '1') {
digitalWrite(relay_pin, HIGH);
}
}
delay(2000);
}
54
ADXL335 Accelerometer
55
ADXL335 Features
56
ADXL335 Applications
57
Connections
58
Code is available in Arduino IDE’s Examples
HC - SR04 Ultrasonic Range Sensor
59
HC - SR04 Ultrasonic Range Sensor - Details
Product features: Ultrasonic ranging module HC - SR04 provides 2cm - 400cm non-contact measurement function, the ranging accuracy can reach to 2mm.
The module includes ultrasonic transmitter, receiver and control circuit. The basic principle of working is:
(1) IO trigger for at-least 10μs high level signal
(2) The Module automatically sends eight 40 kHz and detects whether there is a pulse signal back
(3) If the signal is back, through high level, then the time of high output IO duration is the time from sending ultrasonic to returning
Test distance = (high level time×velocity of sound (340ms-1) / 2
60
/* HC-SR04 Sensor
https://www.dealextreme.com/p/hc-sr04-ultrasonic-sensor-distance-measuring-module-133696
This sketch reads a HC-SR04 ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor.
The circuit:
* VCC connection of the sensor attached to +5V
* GND connection of the sensor attached to ground
* TRIG connection of the sensor attached to digital pin 2
* ECHO connection of the sensor attached to digital pin 4
Original code for Ping))) example was created by David A. Mellis
Adapted for HC-SR04 by Tautvidas Sipavicius
This example code is in the public domain.*/
const int trigPin = 2;
const int echoPin = 4;
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
61
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose duration is the time (in microseconds) from the sending of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
�
cntd - Details here
long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
�
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
62
63
64
65
If the soil is homogeneous & receives similar watering over an area then a single probe will give a representative reading for that area. If regions of soil are different in composition, for example sandy or loamy, then you may want to use a probe for each type of soil region, and for areas that receive different watering. Src
/* Connection pins:
Arduino Soil Moisture Sensor YL-69
A0 Analog A0
5V VCC
GND GND
*/
void setup()
{
Serial.begin(9600);
pinMode(A0, INPUT); //set up analog pin 0 to be input
// pinMode(2, OUTPUT); // red led
// pinMode(3, OUTPUT); // yellow led
//pinMode(4, OUTPUT); // green led
}
66
void loop()
{
int s = analogRead(A0); //take a sample
Serial.print(s);
Serial.print(" - ");
if(s >= 1000) {
Serial.println("Sensor is not in the Soil or DISCONNECTED");
}
if(s < 1000 && s >= 600) {
Serial.println("Soil is DRY");
}
if(s < 600 && s >= 370) {
Serial.println("Soil is HUMID");
}
if(s < 370) {
Serial.println("Sensor in WATER");
}
delay(1000);
}
67
Controlling DC Motor from Arduino using LM293D
68
Specifications:
//2-Way motor control
int motorPin1 = 9; // One motor wire connected to digital pin 9
int motorPin2 = 10; // One motor wire connected to digital pin 10
// The setup() method runs once, when the sketch starts
void setup() {
// initialize the digital pins as an output:
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
}
// the loop() method runs over and over again,as long as the Arduino has power
void loop()
{
rotateLeft(150, 500);
rotateRight(50, 1000);
rotateRight(150, 1000);
rotateRight(200, 1000);
rotateLeft(255, 500);
rotateRight(10, 1500);
}
69
void rotateLeft(int speedOfRotate, int length){
analogWrite(motorPin1, speedOfRotate); //rotates motor
digitalWrite(motorPin2, LOW); // set the Pin motorPin2 LOW
delay(length); //waits
digitalWrite(motorPin1, LOW); // set the Pin motorPin1 LOW
}
void rotateRight(int speedOfRotate, int length){
analogWrite(motorPin2, speedOfRotate); //rotates motor
digitalWrite(motorPin1, LOW); // set the Pin motorPin1 LOW
delay(length); //waits
digitalWrite(motorPin2, LOW); // set the Pin motorPin2 LOW
}
/* http://www.arduinoeletronica.com.br */ Codebender Link
int PIR = 2;
int led = 13;
void setup(){
Serial.begin(9600);
pinMode(PIR, INPUT);
pinMode(led,OUTPUT);
}
void loop(){
int lerPIR = digitalRead(PIR);
if(lerPIR == LOW){ //was motion detected
digitalWrite(led,HIGH);
Serial.println("Motion Detected!");
// delay(2000);
}
else{
digitalWrite(led,LOW);
Serial.println("No Motion!");
}
}
71
HC05 Bluetooth Module
72
HC05 Bluetooth Features
73
HC05 Bluetooth Module
74
Setting up Name and Password with AT Commands
75
ArduDroid - Reading Input using Bluetooth from Android
76
int ledPin = 13;
int state = 0;
//int flag = 0;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600); // Default connection
//rate for my BT module
}
void loop() {
if(Serial.available() > 0){
state = Serial.read();
//flag=0;
}
77
if (state == '0') {
digitalWrite(ledPin, LOW);
// if(flag == 0) {
Serial.println("LED: off");
//flag = 1;
}
else if (state == '1') {
digitalWrite(ledPin, HIGH);
//if(flag == 0){
Serial.println("LED: on");
//flag = 1;
}
}
Code for controlling built-in LED using Bluetooth Module
Single Channel Relay Switch
78
Custom App
80
ESP8266 Wifi Serial Module
81
Always connect VCC, CH_PD to 3.3V only
82
83
ESP8266 Wifi Serial Module
84
ESP8266 Wifi Serial Module
85
86
On-device processing
After data is collected from a sensor, the device can provide data processing functionality before sending the data to the cloud to enable more information to be transmitted in a smaller data footprint. Details are here
87
Processing includes things like:
88
ThingSpeak API with LM35 sensor
#include<stdlib.h>
const int groundpin = A0;
const int powerpin = A2;
const int receiver = 0;
float tempC;
int reading;
int tempPin = A1;
int led=13; int con=0;
String apiKey = "27RPRHYGBJ335YGE";
void setup() {
Serial.begin(115200);
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
pinMode(led, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
analogReference(INTERNAL);
// reset ESP8266
Serial.println("AT+RST");
Serial.println("AT+CIPMUX=0");
}
void loop() {
reading = analogRead(tempPin);
tempC = reading / 9.31;
// convert to string
char buf[16];
String strTemp = dtostrf(tempC, 5, 2, buf);
Serial.println(tempC);
// TCP connection
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "api.thingspeak.com"; // api.thingspeak.com
cmd += "\",80";
Serial.println(cmd);
89
if(Serial.find("Error")){
Serial.println("AT+CIPSTART error");
return;
}
// prepare GET string
String getStr = "GET /update?key=";
getStr += apiKey;
getStr +="&field1=";
getStr += String(strTemp);
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
Serial.println(cmd);
if(Serial.find(">")){
Serial.print(getStr);
}
else{
// alert user
Serial.println("AT+CIPCLOSE");
}
// thingspeak needs 15 sec delay between updates
delay(5000);
}
ThingSpeak API with LDR sensor
#include<stdlib.h>
int reading;
int led=13; int con=0;
String apiKey = "N3EC0RWRM8JJG0RD";
void setup() {
Serial.begin(115200);
pinMode(led, OUTPUT);
analogReference(INTERNAL);
// reset ESP8266
Serial.println("AT+RST");
Serial.println("AT+CIPMUX=0");
}
void loop() {
reading = analogRead(A0);
// convert to string
Serial.println(reading);
// TCP connection
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "api.thingspeak.com"; // api.thingspeak.com
cmd += "\",80";
Serial.println(cmd);
90
if(Serial.find("Error")){
Serial.println("AT+CIPSTART error");
return;
}
// prepare GET string
String getStr = "GET /update?key=";
getStr += apiKey;
getStr +="&field1=";
getStr += String(reading);
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
Serial.println(cmd);
if(Serial.find(">")){
Serial.print(getStr);
}
else{
// alert user
Serial.println("AT+CIPCLOSE");
}
// thingspeak needs 15 sec delay between updates
delay(5000);
}
#include<stdlib.h>
int reading;
int led=13; int con=0;
String apiKey = "N3EC0RWRM8JJG0RD";
void setup() {
Serial.begin(115200);
pinMode(led, OUTPUT);
analogReference(INTERNAL);
// reset ESP8266
Serial.println("AT+RST");
Serial.println("AT+CIPMUX=0");
}
void loop() {
reading = analogRead(A0);
// convert to string
Serial.println(reading);
// TCP connection
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "api.thingspeak.com"; // api.thingspeak.com
cmd += "\",80";
Serial.println(cmd);
if(Serial.find("Error")){
Serial.println("AT+CIPSTART error");
return;
}
// prepare GET string
String getStr = "GET /update?key=";
getStr += apiKey;
getStr +="&field1=";
getStr += String(reading);
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
Serial.println(cmd);
if(Serial.find(">")){
Serial.print(getStr);
}
else{
// alert user
Serial.println("AT+CIPCLOSE");
}
// thingspeak needs 15 sec delay between updates
delay(5000);
}
91
92
93
94
95
96
NodeMCU - An open-source firmware and development kit that helps you to prototype your IoT product within a few Lua script lines
97
In NodeMCU use GPIO numbers in Arduino Code...Connect long pin of LED/Relay to 5V TTL & short one to D4
98
Simple LED Blink using NodeMCU
void setup() {
// initialize digital pin 2 as an output.
pinMode(2, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
99
Try Connecting External LED
NodeMCU + ThingSpeak
/* * This sketch sends data via HTTP GET requests to data.sparkfun.com service. * * You need to get streamId and privateKey at data.sparkfun.com and paste them * below. Or just customize this script to talk to other HTTP servers.* */
#include <ESP8266WiFi.h>
const char* ssid = "das";
const char* password = "TCSTCSTCS";
const char* host = "api.thingspeak.com";
//const char* streamId = "....................";
const char* privateKey = "FERH0WIO017KTZ3F";
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
100
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 20;
void loop() {
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/update?key=";
url += privateKey;
url += "&field1=";
url += value;
Serial.print("Requesting URL: ");
Serial.println(url);
cntd...
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
101
102
Output in ThingSpeak
103
Explore Embedded - The module goes into programming mode with a single reset switch.
104
Explore Embedded - Connect with CP2102
105
Hard press RESET switch to reprogram the module
Same code as NodeMCU
106
107
Output in Serial Monitor
IoT Protocols
108
MQTT (formerly MQ Telemetry Transport) is an ISO standard (ISO/IEC PRF 20922) publish-subscribe based "light weight" messaging protocol for use on top of the TCP/IP protocol. It is designed for connections with remote locations where a "small code footprint" is required or the network bandwidth is limited. It is ideal for mobile applications because of its small size, low power usage, minimised data packets, and efficient distribution of information to one or many receivers.
109
Public MQTT Brokers
110
111
Controlling Relay Switch using MQTT from Cloud/App
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// setup WiFi & MQTT details
const char* ssid = "GovindAP";
const char* pass = "*************";
const char* mqtt_server = "test.mosquitto.org”;
int status = WL_IDLE_STATUS;
String topic_1 = "sdmcetcse/light1";
int builtin_led = 2;
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void setup() {
// setup serial
Serial.begin(115200);
// setup & initialize gpio
pinMode (builtin_led, OUTPUT);
digitalWrite(builtin_led, HIGH);
// setup wifi
setup_wifi();
// setup mqtt
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
112
void loop() {
if (!client.connected()) mqtt_reconnect();
client.loop();
client.publish("sdmcetcse/light1", "SDMCET Dwd");
delay(5000);
}
// for MQTT callback
void callback(char* topic, byte* payload, unsigned int length) {
// get topic as a string
String strTopic = String(topic);
// get payload as a string
char charPayload[length];
for (int i = 0; i < length; i++) charPayload[i] = (char)payload[i];
String strPayload = (String(charPayload)).substring(0, length);
Serial.println(strPayload);
if (topic_1.equals(strTopic)) {
if (strPayload.equals("off")) {
client.publish("sdmcetcse/light1", "Light-1 OFF");
light_off(builtin_led);
} else if (strPayload.equals("on")) {
client.publish("sdmcetcse/light1", "Light-1 ON");
light_on(builtin_led);
}
}
Code Credits: NBN RIOT Workshop, Pune
else {
client.publish("NJMZuDbYxt_err", "mistake in topic error");
}
}
void light_on (int light) {
digitalWrite(light, LOW);
}
void light_off (int light) {
digitalWrite(light, HIGH);
}
void setup_wifi() {
delay(10);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void mqtt_reconnect() {
while (!client.connected()) {
if (client.connect("Sw_Cub1_ESPClient")) {
client.subscribe("sdmcetcse/#");
client.publish("sdmcetcse/light1", "Connected");
delay(100);
} else {
delay(5000);
}
}
}
113
115
Connect 3.3 & GND of NodeMCU to TTL Logic...5 volt of TTL to relay switch and D4 of NodeMCU to relay..
Web Controlled LED
116
Installing Additional Boards on Arduino [Offline]
117
Uploading code directly to ESP8266
118
Built-in LED Blink using ESP8266
/* ESP8266 Blink by Simon Peter Blink the blue LED on the ESP-01 module This example code is in the public domain The blue LED on the ESP-01 module is connected to GPIO1 (which is also the TXD pin; so we cannot use Serial.print() at the same time) Note that this sketch uses LED_BUILTIN to find the pin with the internal LED */
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
delay(1000); // Wait for a second
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
delay(2000); // Wait for two seconds (to demonstrate the active low LED)
}
119
120
NodeMCU Code on ESP8266
Code same as NodeMCU except below change:
121
GSM Module for Arduino
Features:
122
Applications of GSM Module
123
Sending SMS via GSM Module
#include <GSM.h>
#define PINNUMBER ""
// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) ; // wait for serial port to connect (Leonardo only)
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while(notConnected) {
if(gsmAccess.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop() {
Serial.print("Enter a mobile number: ");
char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
Serial.println(remoteNum);
Serial.print("Now, enter SMS content: ");
124
char txtMsg[200];
readSerial(txtMsg);
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
sms.beginSMS(remoteNum);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
/*Read input serial*/
int readSerial(char result[]) {
int i = 0;
while(1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result[i] = '\0';
Serial.flush();
return 0;
}
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
}
}
}
Student’s Projects: Railway Security Monitoring System Using GSM Module
125
Arduino Ethernet Shield
126
Ethernet Shield Features
You can bridge the internet connection between your laptop with wifi/hotspot access and ethernet cable (which is plugged to Ethernet shield) and try code to send sensor value to Thingspeak...
127
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
EthernetClient client;
void setup() {
Serial.begin(9600);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for (;;) ;
}
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(Ethernet.localIP()[thisByte], DEC);
}
Serial.println();
}
void loop() {
}
128
Display DHCP IP Address
129
130
Codenvy.com + Google App Engine Code
The program is developed using codenvy.com IDE and HTML/Java Servlets. This program sends temperature value from LM35 to Google App Engine using ESP8266
131
index.html
<!DOCTYPE html>
<html>
<head>
<title>Temp Sensors Demo</title>
</head>
<center>
<h3>
LM35 Analog Temperature values being stored on Google Datastore.
</h3>
<body>
<form action="/TempSense" method="GET">
<input type="Submit" value="Refresh" name="btn">
</form>
</body>
</center>
</html>
132
package arduino;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.google.appengine.api.datastore.*;
public class TempSenseServelt extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/html");
String temp = req.getParameter("temperature");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
if (temp == null)
temp = "999";
Key dbKey = KeyFactory.createKey("Sensor_DB", temp);
133
Entity tempObj = new Entity("Sensor_DB", dbKey);
tempObj.setProperty("temperature", temp);
datastore.put(tempObj);
//if (btn.equals("Refresh"))
Query q = new Query("Sensor_DB") ;
PreparedQuery pq = datastore.prepare(q);
resp.getWriter().println("<center><table>");
resp.getWriter().println("<th>Temp</th>");
for (Entity result : pq.asIterable()) {
temp = result.getProperty("temperature").toString();
resp.getWriter().println("<tr><H1>");
resp.getWriter().println("<td>" + temp + "</td></td>");
resp.getWriter().println("</H1></tr>");
}
resp.getWriter().println("</table></center>");
}
}
Arduino code to turn on/off pin-13 LED from local - Telnet & Browser - 192.168.4.1/?pin=1
[Ensure you have connected your mobile/laptop to the WiFi Module]
#include<stdlib.h>
int led=13;
void setup() {
Serial.begin(115200);
pinMode(led, OUTPUT);
Serial.println("AT+CIPMUX=1"); /* this is required */
delay(500); /* delay is required */
Serial.println("AT+CIPSERVER=1,1336");
/* incase of connection refused, press RESET button */
}
134
void loop() {
if(Serial.available()) {
delay(500);
if(Serial.find("+IPD,")) {
delay(500);
Serial.find("pin=");
int status = Serial.read()-48;
if(status == 1) {
digitalWrite(led, HIGH);
Serial.println("LED is ON");
} else {
digitalWrite(led, LOW);
Serial.println("LED is OFF");
}
}
}
}
#include<stdlib.h>
const int groundpin = A0;
const int powerpin = A2;
const int receiver = 0;
float tempC;
int reading;
int tempPin = A1;
int led=13; int con=0;
void setup() {
Serial.begin(115200);
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
pinMode(led, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
analogReference(INTERNAL);
// reset ESP8266
//Serial.println("AT+RST");
Serial.println("AT+CWMODE=3");
delay(500);
Serial.println("AT+CIPMUX=1");
delay(500);
}
void loop() {
reading = analogRead(tempPin);
tempC = reading / 9.31;
// convert to string
char buf[16];
String strTemp = dtostrf(tempC, 5, 2, buf);
Serial.println(tempC);
// TCP connection
String cmd = "AT+CIPSTART=4,\"TCP\",\"";
cmd += "9.xd09spz04.appspot.com"; // url
cmd += "\",80";
Serial.println(cmd);
135
if(Serial.find("Error")){
Serial.println("AT+CIPSTART error");
return;
}
// prepare GET string
String getStr = "GET /TempSense?";
getStr +="temperature=";
getStr += String(strTemp);
getStr += " HTTP/1.1\nHost: 9.xd09spz04.appspot.com\n";
getStr += "Connection: close";
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=4,";
cmd += String(getStr.length());
Serial.println(cmd);
if(Serial.find(">")){
Serial.print(getStr);
}
else{
// alert user
Serial.println("AT+CIPCLOSE");
}
delay(16000);
}
Step by Step Guide
136
139
Hands-On PPT by Tanaji Patil
140
ArduinoDroid
Android IDE for Arduino
141
142
Why integrate Cloud with IoT ?
Various stages of IoT data management in Google Cloud Platform. Details are here.
143
Building Internet of Things solutions involves solving challenges across a wide range of domains. Cloud Platform brings scale of infrastructure, networking, and a range of storage and analytics products you can use to make the most of device generated data.
144
Mobile Data Analytics Using IBM IoT Real-Time Insights
.when the mobile device begin sending events, the rules will analyze the data in real time and take action when a threshold is broken
In this example, the IoT Real-Time Insights service, in the Bluemix, is used to demonstrate the analysis of mobile data that is being sent to the IBM Watson IoT Platform Connect.
Software: IBM Bluemix account with IBM Watson IoT Platform and RTI service
Hardware : Smart phone connected to the Internet
IBM IoT Real-Time Insights – Analytics designed for the Internet of Things
145
Expected hands-on time: 20 Mins
How to Register Devices in IBM Watson IoT Platform
146
Battery Less Sensors
EnOcean’s energy harvesting wireless sensor technology collects energy out of air. The energy existing in our environment, for example kinetic motion, pressure, light, differences in temperature, is converted into energy for wireless communication.
Energy from Light, Energy from Motion, Energy from Temperature - Buy Here
https://www.enocean.com/en/products/enocean-link
148
LiFi (Wireless data from every light) is a wireless optical networking technology that uses Light-Emitting Diodes (LEDs) for data transmission. LiFi is designed to use LED light bulbs similar to those currently in use in many energy-conscious homes and offices.
Researchers at the University of Oxford have reached a new milestone in networking by using light fidelity (Li-Fi) to achieve bi-directional speeds of 224 gigabits per second (Gbps)
149
150
151
152
153
154
155
Source: PubNub
156
Formatting an SD Card (Source: GitHub)
The following steps are done on your computer.
157
Installing Raspbian on Raspberry Pi (Source: GitHub)
From now on you are working directly on your Raspberry Pi.
158
After connecting to a monitor:
The default login for Raspbian is username pi with the password raspberry.
When you see a prompt, start the GUI.
pi@raspberrypi ~$ startx
159
160
Update and Upgrade Raspbian
First, update your system's package list, by using this command on a terminal:
sudo apt-get update
Next, upgrade all your installed packages to the latest versions:
sudo apt-get upgrade
When you do not have an access to work directly on your Pi, you may need to access to your Pi from another computer.
Getting Pi's IP Address
First, open LXTerminal:
Obtain an IP address of your Pi:
$ hostname -I
161
162
# Import the GPIO and time libraries
import RPi.GPIO as GPIO
import time
�# Set the pin designation type.
# In this case, we use BCM- the GPIO number- rather than the pin number itself.
GPIO.setmode (GPIO.BCM)
�
# So that you don't need to manage non-descriptive numbers,
# set "LIGHT" to 4 so that our code can easily reference the correct pin.
LIGHT = 4
�# Because GPIO pins can act as either digital inputs or outputs,
# we need to designate which way we want to use a given pin.
# This allows us to use functions in the GPIO library in order to properly send and receive signals.
GPIO.setup(LIGHT,GPIO.OUT)
�
# Cause the light to blink 7 times and print a message each time.
# To blink the light, we call GPIO.output and pass as parameters the pin number (LIGHT) and the state we want.
# True sets the pin to HIGH (sending a signal), False sets it to LOW.
# To achieve a blink, we set the pin to High, wait for a fraction of a second, then set it to Low.
# Adding keyboard interrupt with try and except so that program terminates when user presses Ctrl+C.
try:
while True:
GPIO.output(LIGHT,True)
time.sleep(0.5)
GPIO.output(LIGHT,False)
time.sleep(0.5)
print("blink")
except KeyboardInterrupt:
GPIO.cleanup()
163
Hands-ON
“Hello World” with PubNub Python APIs - Detailed steps are here
o World with PubNub Python APIs
164
165
Source Code - remote-led.py
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode (GPIO.BCM)
LED_PIN = 23
GPIO.setup(LED_PIN,GPIO.OUT)
STATUS = 'ON'
pubnub = Pubnub(publish_key='pub-c-ef38b8f7-26ee-4ea7-9ed0-f2cc6b384f95', subscribe_key='sub-c-79cd1830-2ef0-11e6-9327-02ee2ddab7fe')
channel = 'weblednew'
GPIO.output(LED_PIN, True)
def _callback(m, channel):
print(m)
if m["led"] == 1:
GPIO.output(LED_PIN, True)
print('on-led')
STATUS = 'ON'
else:
GPIO.output(LED_PIN, False)
print('off-led')
STATUS = 'OFF'
def _error(m):
print(m)
pubnub.subscribe(channels=channel, callback=_callback, error=_error)
#pubnub.publish(channel='weblednew', message=STATUS, error=_error)
OUTPUT
>>> {u'led': 2}
off-led
{u'led': 1}
on-led
{u'led': 2}
off-led
{u'led': 1}
on-led
{u'led': 1}
on-led
{u'led': 2}
off-led
{u'led': 1}
on-led
166
DHT Sensor with the Raspberry Pi
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
pin = 23
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
167
Monitor DHT Values on Cloud - using PubNub
168
Working with other Sensors
169
Working with PiCamera
The camera module is a great accessory for the Raspberry Pi, allowing users to take still pictures & record video in full HD.
170
Steps to install latest OpenCV build with Python 3.0+ in Windows OS
Step 1 : Since, there's lot of difference between Python 2.* and Python 3.*, It's your choice to work with any version you want. Python 3+ is recommended since it supports Machine Learning frameworks like panda, theanos etc. Uninstall each python 2+ if installed.
Step 2: Install Python Latest version (present is 3.6.3) https://www.python.org/downloads (32 bit) 64 bit, custom > install it with checking all the boxes in advanced installation options (make sure to check environment variable box).
Step 3: You've to download following libraries from https://www.lfd.uci.edu/~gohlke/pythonlibs/
1. Latest Opencv 2. Latest Numpy 3. Latest Matplotlib 4. Latest Scipy 5. Latest dateutils
Step 4: Search for above mentioned binaries and download the .whl file considering your system configuration, that is 32bit or 64bit. Binaries should match the version of python installed in your machine. for eg. opencv_python‑3.3.1‑cp36‑cp36m‑win_amd64.whl
In the above example, 3.3.1 is opencv version, cp36 is c python 3.6.*. If you've installed python 3.6.* then you should download the above mentioned library in 64 bit machine
Step 5: Download .whl files of all above mentioned binaries considering the versions
Step 6: open cmd with administrative privileges and type "pip install <path to respective .whl files>" (Don't add quotes). Run pip command for all other binaries. install opencv at last, First you've to install numpy, dateutils, matplotlib, scipy and then opencv.
For eg. : pip install C:\Users\Aprameya\Downloads\opencv_python‑3.3.1‑cp36‑cp36m‑win_amd64.whl
Step 7. open python 3.6 idle type "import numpy" and do the same with all other binaries, for opencv it's "import cv2", if all of 'em works fine then everything is installed perfectly.
173
Courtesy: Aprameya Bhat, 7th sem, CSE, SDMCET
Download sample code from git, run python demo.py to test all examples
174
Install guide: Raspberry Pi 3 + Raspbian Jessie + OpenCV 3
175
The Raspberry Pi Zero is half the size of a Model A+, with twice the utility.
Identical pinout to Model A+/B+/2B
176
Connecting Internet on Raspberry Pi ZERO
177
Vehicle telematics analytics using IoT Real-Time Insights
IBM Watson IoT Platform Analytics Real-Time Insights enables you to perform analytics on real-time data from your IoT devices and gain diagnostic insights.
178
179
A visual tool for wiring the Internet of Things
A tool for wiring together hardware devices, APIs and online services in new and interesting ways
180
Bring cognitive technology to your app
The Watson Developer Cloud is a library of Watson APIs that you can use to create Powered by Watson apps.
From gaining insights from text to analyzing images and video, you can tap into the power of Watson APIs to build cognitive apps
181
IoT Sensor data and Big Data ?
IoT and Cloud based projects
Data collected by the device is called telemetry. This is the eyes-and-ears data that IoT devices provide to applications. Telemetry is read-only data about the environment, usually collected through sensors.
Although each device might send only a single data point every minute, when you multiply that data by a large number of devices, you quickly need to apply big data strategies and patterns. Details are here
182
183
RPi Cam Image Analysis using Visual Recognition method
184
186
187
Image Credits: Google
188
189
Temboo - Put the IoT to work for you
190
191
3D Printed Lord Ganesha using Attrobot Mini
192
193
194
Random & Fading RGB simulation using 123d.circuits.io [Hands-on]
Random RGB:
Fading RGB:
195