Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

IOT1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

MODULE:1

Introduction of Arduino Uno

Fig no. 1

Basically, the processor of the Arduino board uses the Harvard architecture where the program
code and program data have separate memory.
The Atmega328 microcontroller has 32kb of flash memory, 2kb of SRAM 1kb of EPROM and
operates with a 16MHz clock speed.
The Arduino Uno is a microcontroller board based on the ATmega328. It has 14 digital
input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz ceramic
resonator, a USB connection, a power jack, an ICSP header, and a reset button. It contains
everything needed to support the microcontroller; simply connect it to a computer with a USB
cable or power it with a AC-to-DC adapter or battery to get started.

1
Fig no. 2

 8BIT AVR RISC MICROCONTROLLER


 Microcontroller ATmega 328
 Operating voltage: 5 V
 Input voltage recommended : 7-12 V
 Digital I/O Pins: 14 ( of which 6 PWM output)
 Analog input Pins:6
 DC current per I/O Pin: 40 mA
 DC current for 3.3 V Pin: 50 mA
 Flash memory : 32 kB (Atmega 328) of which 0.5 kB used by bootloader
 SRAM: 2 kB
 EEPROM: 1 kB
 Clock speed : 16 MHz
 6 CHANNEL ,10 BIT ADC

2
MODULE:2
Bus Communication

3
Control an LED via Serial Communication:

Code for Master Arduino :


#include <SoftwareSerial.h>
SoftwareSerial softSerial(10, 11);
void setup()
{
softSerial.begin(9600);
Serial.begin(9600);
}
void loop()
{
softSerial.print(1);
Serial.print(1);
delay(5000);
softSerial.print(0);
Serial.print(0);
delay(5000);
}
Code for Slave Arduino:
#include <SoftwareSerial.h>
SoftwareSerial softSerial(10, 11);
char number = ' ';
int LED = 2;
void setup()
{
softSerial.begin(9600);
Serial.begin(9600);

4
pinMode(LED, OUTPUT);
}
void loop()
{
if (softSerial.available())
{
char number = softSerial.read();
if (number == '0')
{
digitalWrite(LED, LOW);
}
if (number == '1')
{
digitalWrite(LED, HIGH);
}
Serial.println(number);
}
}
----------------------------------------------------------------------------------------------------------------

Two-way communication between two Arduino using I2C:

Sketch for Master:


#include <Wire.h>
void setup() {
Serial.begin(9600); /* begin serial comm. */
Wire.begin(); /* join i2c bus as master */
Serial.println("I am I2C Master");
}
void loop() {

5
Wire.beginTransmission(8); /* begin with device address 8 */
Wire.write("Hello Slave"); /* sends hello string */
Wire.endTransmission(); /* stop transmitting */

Wire.requestFrom(8, 9); /* request & read data of size 9 from slave */


while(Wire.available()){
char c = Wire.read();/* read data received from slave */
Serial.print(c);
}
Serial.println();
delay(1000);
}
___________________________________________________________________________
___________________________________________________________________________

Sketch for Slave:


#include <Wire.h>
void setup() {
Wire.begin(8); /* join i2c bus with address 8 */
Wire.onReceive(receiveEvent); /* register receive event */
Wire.onRequest(requestEvent); /* register request event */
Serial.begin(9600); /* start serial comm. */
Serial.println("I am I2C Slave");
}
void loop() {
delay(100);
}
// function that executes whenever data is received from master
void receiveEvent(int howMany) {
while (0 <Wire.available()) {
char c = Wire.read(); /* receive byte as a character */

6
Serial.print(c); /* print the character */
}
Serial.println(); /* to newline */
}
// function that executes whenever data is requested from master
void requestEvent() {
Wire.write("Hi Master"); /*send string on request */
}

MODULE:3
Node MCU

7
Fig No. 3
 The development board equips the ESP-12E module containing ESP8266 chip
having Tensilica Xtensa® 32-bit LX106 RISC microprocessor which operates at 80
to 160 MHz adjustable clock frequency and supports RTOS.
 There’s also 128 KB RAM and 4MB of Flash memory (for program and data
storage) just enough to cope with the large strings that make up web pages,
JSON/XML data, and everything we throw at IoT devices nowadays.
 The ESP8266 Integrates 802.11b/g/n HT40 Wi-Fi transceiver, so it can not only
connect to a Wi-Fi network and interact with the Internet, but it can also set up a
network of its own, allowing other devices to connect directly to it.
 Power to the ESP8266 NodeMCU is supplied via the on- board MicroB USB
connector.
 You can also regulated 5V voltage source, the VIN pin can be used to directly supply
current the ESP8266 and its peripherals.
 As the operating voltage range of ESP8266 is 3V to 3.6V, the board comes with a
LDO(Low Dropout) voltage regulator to keep the voltage steady at 3.3V.
 It can reliably supply up to 600mA, which should be more than enough when
ESP8266 pulls as much as 80mA during RF transmissions.
The ESP8266 NodeMCU has total 17 GPIO pins :
 ADC channel – A 10-bit ADC channel.
 UART interface – UART interface is used to load code serially.
 PWM outputs – PWM pins for dimming LEDs or controlling motors.
 SPI, I2C & I2S interface – SPI and I2C interface to hook up all sorts of sensors and
peripherals.
 I2S interface – I2S interface if you want to add sound to your project.

8
Fig no. 4

MODULE:4
NODE MCU Based IoT
4.1 IoT based Temperature and Humidity and Light Intensity Monitoring
and control devices using Thing Speak cloud server.

Fig no. 5

#include <ESP8266WiFi.h>;
#include <WiFiClient.h>;
#include <ThingSpeak.h>;
#include <DHT.h>;
WiFiClient client;
const char* ssid = "Redmi"; //Your Network SSID
const char* password = "12345678"; //Your Network Password

unsigned long myChannelNumber = 2045473;


const char * myWriteAPIKey = "CDVUNQL9CCOTSUGB";
const char * myReadAPIKey = "C86E152W4AMV3TGP";

9
#define DHTPIN D2 //pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
int temp;
int hum;
int light;
int led1 = D6;
int led2 = D7;
int led3 = D8;
int ldr = A0;
int val =0;
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
dht.begin();
ThingSpeak.begin(client);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
}
void loop(){

float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.println(h);
Serial.println(t);
val = analogRead(ldr);
Serial.println(val);

10
ThingSpeak.setField(1, h);
ThingSpeak.setField(2, t);
ThingSpeak.setField(3, val);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
hum = ThingSpeak.readIntField(myChannelNumber, 1, myReadAPIKey);
temp = ThingSpeak.readIntField(myChannelNumber, 2, myReadAPIKey);
light = ThingSpeak.readIntField(myChannelNumber, 3, myReadAPIKey);
Serial.println(hum);
if(hum<100)
{
digitalWrite(led1,HIGH);
}
else
{
digitalWrite(led1,LOW);
}
Serial.println(temp);
if(temp<40)
{
digitalWrite(led2,HIGH);
}
else
{
digitalWrite(led2,LOW);
}
Serial.println(light);
if(light<200)

11
{
digitalWrite(led3,HIGH);
}
else
{
digitalWrite(led3,LOW);
}
delay(15000);
}

4.2 IoT based Light Intensity Monitoring and control devices using
UBIDOTS cloud server (MQTT Protocol Based).

#include "UbidotsESPMQTT.h"
#include <ESP8266WiFi.h>
int ldrPin = A0;
/**************
* Define Constants
**************/
#define TOKEN "BBFF-x5e4HGEd4oiVIl6M34KiuJqD6qU3Cx" // Your
Ubidots TOKEN
#define WIFINAME "Redmi" //Your SSID
#define WIFIPASS "12345678" // Your Wifi Pass

Ubidots client(TOKEN);
int LED = D5;
char* variable1 = "led";
char* variable2 = "ldr";

12
/**************
* Auxiliar Functions
**************/

void callback(char* topic, byte* payload, unsigned int length) {


Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
if ((char)payload[0]=='1'){
digitalWrite(D5, HIGH);
}
else{
digitalWrite(D5, LOW);
}
Serial.println();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
client.setDebug(true); // Pass a true or false bool value to activate debug
messages
client.wifiConnection(WIFINAME, WIFIPASS);
client.begin(callback);

13
pinMode(D5, OUTPUT);
client.ubidotsSubscribe("MQTT",variable1);
}
void loop() {
// put your main code here, to run repeatedly:
if(!client.connected()){
client.reconnect();
}
int ldrValue = analogRead(ldrPin);
Serial.println(ldrValue);
client.add(variable2, ldrValue);
client.ubidotsPublish("MQTT");
client.loop();
delay(6000);
}

4.3 IoT based Temperature and Humidity Monitoring and control devices
using FireBase cloud server.

#include "FirebaseESP8266.h" // Install Firebase ESP8266 library


#include <ESP8266WiFi.h>
#include <DHT.h> // Install DHT11 Library and Adafruit Unified Sensor
Library
#define FIREBASE_HOST "https://subhajit-7af42-default-rtdb.asia-
southeast1.firebasedatabase.app//" //Without http:// or https:// schemes
#define FIREBASE_AUTH
"AIzaSyA6gMCNCc82nnRy5mfD51nr9ViPYc6LVWs"
#define WIFI_SSID "Redmi"
#define WIFI_PASSWORD "12345678"
14
#define DHTPIN D4 // Connect Data pin of DHT to D2
int led = D5; // Connect LED to D5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

//Define FirebaseESP8266 data object


FirebaseData firebaseData;
FirebaseData ledData;

//FirebaseJson json;
void setup()
{
Serial.begin(9600);
dht.begin();
pinMode(led,OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
}
void sensorUpdate(){
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t) ) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.println(h);

15
Serial.println(t);
if (Firebase.pushFloat(firebaseData, "/FirebaseIOT/temperature", t))
{
Serial.println("PASSED");
}
else
{
Serial.println("FAILED");
}
if (Firebase.pushFloat(firebaseData, "/FirebaseIOT/humidity", h))
{
Serial.println("PASSED");
}
else
{
Serial.println("FAILED");
}
}
void loop() {
sensorUpdate();
if (Firebase.getString(ledData, "/FirebaseIOT/led")){
Serial.println(ledData.stringData());
if (ledData.stringData() == "1") {
digitalWrite(led, HIGH);
}
else if (ledData.stringData() == "0"){
digitalWrite(led, LOW);

16
}
}
delay(100);
}

MODULE: 5
Introduction to Raspberry Pi

Fig no. 6

The Raspberry Pi is a small computer (which includes the processor, graphics card, and
memory in a single package.), about the size of a credit card which was developed in UK by
the Raspberry Pi Foundation. Name of Raspberry Pi is combination of Raspberry and Pi, where
raspberry is fruit name and pi stand for Python.

17
Fig no. 7

Control Led using RPi


import time
#import RPi.GPIO as GPIO
from RPi import GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(21,GPIO.OUT)

try:
while True:
18
GPIO.output(21,GPIO.HIGH)
time.sleep(1)
print("On")

GPIO.output(21,GPIO.LOW)
time.sleep(1)
print("Off")

except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()

MODULE: 6
RPi Based IoT
6.1 IoT based Temperature and Humidity Monitoring using Thing Speak
cloud server.
import sys
import urllib.request
from time import sleep
import Adafruit_DHT as dht

# Enter Your API key here


myAPI = 'T0RGBR7N1ARD9XWB'
# URL where we will send the data, Don't change it
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

19
def DHT11_data():
# Reading from DHT11 and storing the temperature and humidity
humi, temp = dht.read_retry(dht.DHT11, 21)
return humi, temp

while True:
try:
humi, temp = DHT11_data()

# If Reading is valid
if isinstance(humi, float) and isinstance(temp, float):
# Formatting to two decimal places
humi = '%.2f' % humi
temp = '%.2f' % temp
print(humi)
print(temp)

# Sending the data to thingspeak


conn = urllib.request.urlopen(baseURL + '&field1=%s&field2=%s'
% (temp, humi))
conn.read()
# Closing the connection
conn.close()

else:
print ('Error')

20
# DHT11 requires 2 seconds to give a reading, so make sure to add delay of
above 2 seconds.
sleep(20)

except:
break

6.2 Human Motion Detection and post to UBIDOTS cloud server.


from gpiozero import MotionSensor
import json,requests
import time
PIR = MotionSensor(21)

url = "http://things.ubidots.com"
TOKEN = "BBFF-x5e4HGEd4oiVIl6M34KiuJqD6qU3Cx" # Put your
TOKEN here
DEVICE_LABEL = "pir"
url = "{}/api/v1.6/devices/{}".format(url, DEVICE_LABEL)
headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
#VARIABLE_LABEL_1 = "dust-sensor" # Put your first variable label here
#VARIABLE_LABEL_2 = "alcohol" # Put your second variable label here
VARIABLE_LABEL_3 = "PIR"

def value (PIR):


payload = {
VARIABLE_LABEL_3 : PIR}
status = 400
attempts = 0

21
while status >= 400 and attempts <= 5:
req = requests.post(url=url, headers=headers, json=payload)
status = req.status_code
attempts += 1
time.sleep(1)
if status >= 400:
print("[ERROR] Could not send data after 5 attempts, please check \
your token credentials and internet connection")
return
while True:
PIR.wait_for_motion()
print("You moved")
value(1)
PIR.wait_for_no_motion()
print("Don't Moved")
value(0)

6.3 Data gets from UBIDOTS cloud server. (IoT based Automation)
import time
import requests
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(21,GPIO.OUT)
DEVICE ="LED"
VARIABLE1 ="BLINK"
TOKEN = "BBFF-x5e4HGEd4oiVIl6M34KiuJqD6qU3Cx"

22
try:
while True:
light1 =
requests.get("http://things.ubidots.com/api/v1.6/devices/"+DEVICE+"/"+VARIA
BLE1+"/lv?token="+TOKEN)
print(light1.content) # Returns the content of the response, in bytes
print(light1.json()) # Returns a JSON object of the result
data = light1.json()
print(type(data))
if data==1.0:
GPIO.output(21,GPIO.HIGH)
#GPIO.output(26,GPIO.LOW)
print("On")
#time.sleep(3)
if data==0.0:
GPIO.output(21,GPIO.LOW)
#GPIO.output(26,GPIO.HIGH)
print("Off")
#time.sleep(3)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
light1 = ''

23

You might also like