1 of 195

Internet of Things

Hands-On

1

2 of 195

2

3 of 195

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 of 195

4

5 of 195

IoT for Sports

Before After (Generates Enough Data)

... fan engagement, audience engagement, training (Dangal !), fitness...

5

6 of 195

6

7 of 195

Activity Trackers

Fitbit helps you live a healthy, balanced life by tracking your all-day activity, exercise, sleep, and weight.

7

8 of 195

8

9 of 195

9

10 of 195

What is IoT?

  • The Internet of Things (IoT) is the network of physical objects—devices, vehicles, buildings and other items—embedded with electronics,software, sensors, and network connectivity that enables these objects to collect and exchange data
  • IoT allows objects to be sensed and controlled remotely across existing network infrastructure, creating opportunities for more direct integration of the physical world into computer-based systems, and resulting in improved efficiency, accuracy and economic benefit
  • The daily operation of IoT system requires that we collect right information about what’s going on.

10

11 of 195

11

12 of 195

12

Microcontroller-based devices are more constrained & your application code run directly on the processor without the support of an OS.

13 of 195

13

14 of 195

14

15 of 195

15

The ATmega328 is a single-chip microcontroller created by Atmel in the megaAVR family.

16 of 195

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.

17 of 195

analogReference()

Description

Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are:

  • DEFAULT: The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
  • INTERNAL: Built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8(not available on the Arduino Mega)
  • EXTERNAL: The voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Syntax

analogReference(type)

Parameters type: which type of reference to use (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, or EXTERNAL)

17

18 of 195

Arduino IDE - Download from https://www.arduino.cc/en/Main/Software

18

19 of 195

19

20 of 195

20

21 of 195

21

22 of 195

Built-in (Pin 13) LED Blink

void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

delay(500);

digitalWrite(13, LOW);

delay(500);

}

22

23 of 195

RGB - LED

23

24 of 195

1 - RGB Connections - Safer to connect via resistors

24

25 of 195

2 - RGB Connections - Safer to connect via resistors

25

26 of 195

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 );

}

}

27 of 195

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;

}

}

28 of 195

123d.circuits.io - Design, Compile, and Simulate your electronic projects Online – for Free

28

29 of 195

29

30 of 195

30

31 of 195

31

32 of 195

32

33 of 195

33

34 of 195

34

35 of 195

Sensors Bring IoT Projects to Life

Sensors are the nose, eyes and ears…Without sensors, there's no IoT. src

35

36 of 195

36

37 of 195

LM35 Analog Temperature Sensor

37

38 of 195

LM35 Features

  • Calibrated Directly in Celsius (Centigrade)
  • Linear + 10-mV/°C Scale Factor
  • Operates from 4 V to 30 V
  • Suitable for Remote Applications
  • Rated for Full −55°C to 150°C Range
  • Low Self-Heating, 0.08°C in Still Air

38

39 of 195

LM35 Applications

  • Power Supplies

  • Battery Management

  • HVAC

  • Temperature Sensitive Appliances

39

40 of 195

LM35 Analog Temperature Sensor Connections

40

Always connect LM35 on Arduino Board directly

41 of 195

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

42 of 195

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);

}

43 of 195

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 of 195

44

45 of 195

LDR - Light Dependent Resistor Sensor

45

46 of 195

LDR Sensor - Resistance vs Light Intensity

46

47 of 195

LDR Connections

47

48 of 195

//http://www.hobbytronics.co.uk/arduino-tutorial8-nightlight

int sensorPin = A0; // select the input pin for the ldrunsigned int sensorValue = 0; // variable to store the value coming from the ldrvoid setup()�{� pinMode(13, OUTPUT);� //Start Serial portSerial.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 onelse 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

49 of 195

DHT11 - Digital Humidity and Temperature

Safer to connect a resistor between pin 1 and 2

49

50 of 195

DHT11 Features

  • Low cost
  • 3 to 5V power and I/O
  • 2.5mA max current use during conversion (while requesting data)
  • Good for 20-80% humidity readings with 5% accuracy
  • Good for 0-50°C temperature readings ±2°C accuracy
  • No more than 1 Hz sampling rate (once every second)
  • Body size 15.5mm x 12mm x 5.5mm
  • 4 pins with 0.1" spacing

50

51 of 195

DHT11 Applications

  • Weather stations for providing humidity at cheaper cost
  • Sense temperature level of soil
  • Power Supplies
  • Battery Management
  • HVAC (stands for Heating, Ventilation and Air Conditioning)
  • Temperature Sensitive Appliances

51

52 of 195

#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");

}

53 of 195

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 of 195

54

55 of 195

ADXL335 Accelerometer

55

56 of 195

ADXL335 Features

  • 3-axis sensing
  • Small, low-profile package
  • Low power - 350 μA (typical)
  • Single-supply operation
  • 1.8 V to 3.6 V
  • 10,000 g shock survival
  • Excellent temperature stability
  • BW adjustment with a single capacitor per axis
  • RoHS Restriction of Hazardous Substances /WEEE Waste Electrical and Electronic Equipment Directive lead-free compliant

56

57 of 195

ADXL335 Applications

  • Cost sensitive, low power, motion and tilt-sensing applications
  • Mobile devices
  • Gaming systems
  • Disk drive protection
  • Image stabilization
  • Sports and health devices

57

58 of 195

Connections

58

Code is available in Arduino IDE’s Examples

59 of 195

HC - SR04 Ultrasonic Range Sensor

59

60 of 195

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

61 of 195

/* 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);

}

62 of 195

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 of 195

63

64 of 195

64

65 of 195

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

66 of 195

/* 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 of 195

67

68 of 195

Controlling DC Motor from Arduino using LM293D

68

  • This module is a medium powered motor driver perfect for driving DC motors and Stepper motors.
  • It uses the popular Motor Driver Board H-bridge motor driver IC.
  • It can drive 4 DC motors in one direction, or drive 2 DC motors in both the directions with speed control.
  • The driver greatly simplifies and increases the ease with which you may control motors, relays, etc from microcontrollers.
  • It can drive motors up to 12 V with a total DC current of up to 600mA.

Specifications:

  • Operating Voltage: 7 V to 12V DC.
  • 4 channel output (can drive 2 DC motors bidirectionally).
  • 600mA output current capability per channel.
  • PTR connectors for easy connections.

69 of 195

//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

}

70 of 195

PIR Sensor

70

71 of 195

/* 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

72 of 195

HC05 Bluetooth Module

72

73 of 195

HC05 Bluetooth Features

  • 2.45GHz Frequency
  • Asynchronous Speed 2.1Mbps (max) 160 Kbps
  • Security: Authentication
  • Profile: Bluetooth Serial Port
  • Power Supply: +3.3 VDc
  • Working Temperature: >20C
  • Cost : Around INR 300

73

74 of 195

HC05 Bluetooth Module

74

75 of 195

Setting up Name and Password with AT Commands

  • VCC Pin ➝ 5V
  • GND Pin ➝ GND
  • RX Pin ➝ RX
  • TX Pin ➝ TX
  • Key Pin/State Pin ➝ 5V
  • Baud Rate: 9600
      • Press RESET BUTTON of your Bluetooth [if available]
  • In Serial Monitor, type:
    • Type “AT”, Check for response “OK”
    • AT+NAME=”name_of_your_interest”
    • AT+PSWD=”4_digit_password”
  • Password must be 4-digit

75

76 of 195

ArduDroid - Reading Input using Bluetooth from Android

76

77 of 195

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

78 of 195

Single Channel Relay Switch

78

79 of 195

79

80 of 195

Custom App

80

81 of 195

ESP8266 Wifi Serial Module

81

82 of 195

Always connect VCC, CH_PD to 3.3V only

82

83 of 195

83

84 of 195

ESP8266 Wifi Serial Module

  • 802.11 b/g/n protocol
  • Wi-Fi Direct (P2P), Soft-AP- SoftAP is an abbreviated term for "software enabled access point." This is software enabling a computer which hasn't been specifically made to be a router into a wireless access point. It is often used interchangeably with the term "virtual router".
  • Integrated TCP/IP Protocol Stack
  • Integrated TR switch, balun, LNA, power amplifier and matching network
  • Integrated PLL, regulators &power management units

84

85 of 195

ESP8266 Wifi Serial Module

85

86 of 195

86

87 of 195

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:

  • Converting data to another format
  • Packaging data in a way that's secure and combines the data into a practical batch
  • Validating data to ensure it meets a set of rules
  • Sorting data to create a preferred sequence
  • Enhancing data to decorate the core value with additional related information
  • Summarizing data to reduce the volume and eliminate unneeded or unwanted detail
  • Combining data into aggregate values

88 of 195

88

89 of 195

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);

}

90 of 195

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);

}

91 of 195

#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 of 195

92

93 of 195

93

94 of 195

94

95 of 195

95

96 of 195

96

97 of 195

NodeMCU - An open-source firmware and development kit that helps you to prototype your IoT product within a few Lua script lines

97

98 of 195

In NodeMCU use GPIO numbers in Arduino Code...Connect long pin of LED/Relay to 5V TTL & short one to D4

98

99 of 195

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

100 of 195

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);

101 of 195

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 of 195

102

Output in ThingSpeak

103 of 195

103

104 of 195

Explore Embedded - The module goes into programming mode with a single reset switch.

104

  • Fits on a breadboard!
  • Single button 'Reset' switch for programming. Uses MOSFET's to put the module in programming mode.
  • All pins of ESP12E taken out
  • Separate serial pins breakout compatible with FTDI cable layout.
  • On-board LM1117-3.3V regulator
  • Works with Arduino IDE for ESP8266
  • ESP8266 ESP12E features
    • 802.11 b/g/n protocol
    • Wi-Fi Direct (P2P), soft-AP
    • Integrated TCP/IP protocol stack
    • Integrated TR switch, balun, LNA, power amplifier and matching network
    • Integrated PLL, regulators, and power management units
    • +19.5dBm output power in 802.11b mode
    • Integrated temperature sensor
    • Supports antenna diversity
    • Power down leakage current of < 10uA
    • Integrated low power 32-bit CPU could be used as application processor
    • SDIO 2.0, SPI, UART
    • STBC, 1×1 MIMO, 2×1 MIMO
    • A-MPDU & A-MSDU aggregation & 0.4ï�­s guard interval
    • Wake up and transmit packets in < 2ms
    • Standby power consumption of < 1.0mW (DTIM3)
    • Resources

105 of 195

Explore Embedded - Connect with CP2102

105

Hard press RESET switch to reprogram the module

106 of 195

Same code as NodeMCU

106

107 of 195

107

Output in Serial Monitor

108 of 195

IoT Protocols

108

109 of 195

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

110 of 195

Public MQTT Brokers

110

111 of 195

111

112 of 195

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);

}

}

113 of 195

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

114 of 195

114

115 of 195

115

Connect 3.3 & GND of NodeMCU to TTL Logic...5 volt of TTL to relay switch and D4 of NodeMCU to relay..

116 of 195

Web Controlled LED

116

117 of 195

Installing Additional Boards on Arduino [Offline]

  • Offline Arduino IDE is required for writing code directly on ESP8266
  • Goto “File” ⇒ “Preferences”, paste in “Additional Boards Manager URL”: http://arduino.esp8266.com/stable/package_esp8266com_index.json
  • Go-to “Tools” ⇒ “Board” ⇒ “Boards Manager
  • Search for ESP8266 and select the version (2.1.0 current version) and click on “Install” button
  • Once installed, select “Generic ESP8266 Module” from “Tools” ⇒ “Board

117

118 of 195

Uploading code directly to ESP8266

  • Connect GPIO0 pin to GND
  • Connect GPIO2 pin to 3.3V and disconnect
  • Connect RESET pin to GND3.3VGND and disconnect

118

119 of 195

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 of 195

120

121 of 195

NodeMCU Code on ESP8266

Code same as NodeMCU except below change:

  • int builtin_led = 2; ⇒ use LED_BUILTIN option available in ESP8266WiFi.h

121

122 of 195

GSM Module for Arduino

Features:

  • Send/Receive SMS
  • Make/Receive Calls
  • Place to insert SIM
  • On-board 3.5 mm jack to connect a headphone to answer calls
  • Uses AT commands to configure and communicate with the shield

122

123 of 195

Applications of GSM Module

  • Home Automation
  • Vehicle Tracking
  • Remote Monitoring and Control
  • Agricultural Automation
  • Industrial Automation
  • GPRS Data Logging

123

Image Credits 1 2 3 4 5

124 of 195

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++;

}

}

}

}

125 of 195

125

126 of 195

Arduino Ethernet Shield

126

127 of 195

Ethernet Shield Features

  • Based on W51000 chip
  • It has internal 16K buffer
  • Connection speed upto 10/100Mb
  • Comes bundled with Arduino Ethernet Library
  • Contains on-board micro SD slot (requires use of external SD card library)

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

128 of 195

#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 of 195

129

130 of 195

130

131 of 195

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

132 of 195

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

133 of 195

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>");

}

}

134 of 195

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");

}

}

}

}

135 of 195

#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);

}

136 of 195

Step by Step Guide

136

137 of 195

137

138 of 195

138

139 of 195

139

Hands-On PPT by Tanaji Patil

140 of 195

140

141 of 195

ArduinoDroid

Android IDE for Arduino

141

142 of 195

142

143 of 195

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 of 195

144

145 of 195

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

Click here for recipe

IBM IoT Real-Time Insights – Analytics designed for the Internet of Things

145

Expected hands-on time: 20 Mins

146 of 195

How to Register Devices in IBM Watson IoT Platform

146

147 of 195

147

148 of 195

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

149 of 195

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 of 195

150

151 of 195

151

152 of 195

152

153 of 195

153

154 of 195

154

155 of 195

155

Source: PubNub

156 of 195

156

Formatting an SD Card (Source: GitHub)

The following steps are done on your computer.

  1. Download SD Formatter 4.0 and install on your computer.
  2. Insert it in SD card reader in the computer. If you need, use a MicroSD adapter (photo).
  3. Run the SD Card Formatter.

157 of 195

  1. Download the Noobs zip file from raspberrypi.org and extract to a desired location.
  2. Open up the SD card drive, and drag-drop the unzipped Noobs contents (not the entire folder!) you just downloaded, into the SD card. Then eject the SD card.

157

158 of 195

Installing Raspbian on Raspberry Pi (Source: GitHub)

From now on you are working directly on your Raspberry Pi.

  1. Insert the formatted SD card in Pi.
  2. Plug in your USB keyboard, USB mouse, and HDMI monitor cables.
  3. Plug in your Wi-Fi adapter.
  4. Plug a USB power, and turn your Pi on.

158

159 of 195

After connecting to a monitor:

  1. Your Raspberry Pi will boot, and a window will appear with a list of operating systems that you can install. Select Raspbian by ticking the box next to Raspbian and click on Install.
  2. Raspbian will run through its installation process. Just wait. This takes a while.
  3. When the install process has completed, the Raspberry Pi configuration menu (raspi-config) will load. You can exit this menu by using Tab on your keyboard to move to Finish.

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 of 195

160

161 of 195

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 of 195

Hands-ON

Pi-Light LED: A "Hello World" of Hardware (Detailed Steps are Here)

162

163 of 195

# 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

164 of 195

Hands-ON

“Hello World” with PubNub Python APIs - Detailed steps are here

o World with PubNub Python APIs

164

165 of 195

IoT-fying Your LED

Remote-controlling LED from Web Interface

GitHub Source Code

165

166 of 195

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

167 of 195

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

168 of 195

Monitor DHT Values on Cloud - using PubNub

https://www.pubnub.com/console

168

169 of 195

Working with other Sensors

169

170 of 195

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

171 of 195

171

172 of 195

172

173 of 195

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

174 of 195

Download sample code from git, run python demo.py to test all examples

174

175 of 195

Install guide: Raspberry Pi 3 + Raspbian Jessie + OpenCV 3

175

176 of 195

The Raspberry Pi Zero is half the size of a Model A+, with twice the utility.

  • Single-core CPU - 1GHz ARM11 core (40% faster than Raspberry Pi 1)
  • Mini HDMI and USB On-The-Go ports
  • Composite video and reset headers
  • A Broadcom BCM2835 application processor
  • 512MB of LPDDR2 SDRAM
  • A micro-SD card slot
  • A mini-HDMI socket for 1080p60 video output
  • Micro-USB sockets for data and power
  • An unpopulated 40-pin GPIO header

Identical pinout to Model A+/B+/2B

  • An unpopulated composite video header
  • Our smallest ever form factor, at 65mm x 30mm x 5mm

176

177 of 195

Connecting Internet on Raspberry Pi ZERO

177

  1. Click here for Details

178 of 195

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 of 195

Vehicle telematics analytics using IoT Real-Time Insights

http://connected-car.mybluemix.net

179

180 of 195

Node-RED

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

181 of 195

IBM Watson Developer Cloud

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

182 of 195

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

IoT with Agriculture

Smart Workplace

182

183 of 195

183

184 of 195

RPi Cam Image Analysis using Visual Recognition method

184

185 of 195

185

186 of 195

186

187 of 195

187

188 of 195

Image Credits: Google

188

189 of 195

189

190 of 195

Temboo - Put the IoT to work for you

190

191 of 195

191

192 of 195

3D Printed Lord Ganesha using Attrobot Mini

192

193 of 195

193

194 of 195

194

195 of 195

Random & Fading RGB simulation using 123d.circuits.io [Hands-on]

195