Vous êtes sur la page 1sur 45

TABLE OF

CONTENTS
01 Color Detection Using Arduino
02 Connect And Control Led Strips Via Raspberry Pi
03 Door Alarm
04 Home Automation (Web)
05 Home Automation Android App
06 Live Feed Using Pi Camera
07 Missile Control
08 Motor Control Using Accelerometer
09 Posture Detection
10 Weather Station
|2
01 Color Detection using Arduino
In this project we are going to interface TCS3200 color sensor with Arduino UNO. TCS3200 is
a color sensor which can detect any number of colors. TCS3200 contains RGB (Red Green Blue)
arrays. As shown in figure on microscopic level one can see the square boxes inside the eye on
sensor. These square boxes are arrays of RGB matrix. Each of these boxes contain Three sensors,
One is for sensing RED light intensity, One is for sensing GREEN light intensity and the last in for
sensing BLUE light intensity.

How TCS230 Color Sensor Works:


The TCS230 senses color light with the help
of an 8 x 8 array of photodiodes. Then using
a Current-to-Frequency Converter the
readings from the photodiodes are converted
into a square wave with a frequency directly
proportional to the light intensity. Finally,
using the Arduino Board we can read the
square wave output and get the results for
the color.
Components Required:
01 ARDUINO UNO 03 LED, 05 TCS3200 color sensor
02 Power supply (5v) 04 LCD (16*2LCD)

Circuit Diagram:

|3
The connections which are done for color sensor are given below:
zz VDD to +5V zz S1 to UNO pin 3
zz GND to GROUND zz S2 to UNO pin 4
zz OE (output Enable) to GND zz S3 to UNO pin 5
zz S0 to UNO pin 2 zz OUT to UNO pin 10

The color which needs to be sensed by the color sensor is selected by two pins S2 and S3. With
these two pins logic control we can tell sensor which color light intensity is to be measured.
Say we need to sense the RED color intensity we need to set both pins to LOW. Once that is done
the sensor detects the intensity and sends the value to the control system inside the module.

S2 S3 Photodiode Type

L L Red

L H Blue

H L Clear (no filter)

H H Green

Code:

int OutPut= 10;//naming pin10 of uno as output

unsigned int frequency = 0;

void setup()

// set up the LCD’s number of columns and rows

pinMode(2,0 OUTPUT);

pinMode(3, OUTPUT);//PINS 2, 3,4,5 as OUTPUT

pinMode(4, OUTPUT);

pinMode(5, OUTPUT);

pinMode(10, INPUT);//PIN 10 as input

digitalWrite(2,HIGH);

|4
digitalWrite(3,LOW);//setting frequency selection to 20%

void loop()

Serial.print(“R=”);//printing name

digitalWrite(4,LOW);

digitalWrite(5,LOW);//setting for RED color sensor

frequency = pulseIn(OutPut, LOW);//reading frequency

Serial.print(frequency);//printing RED color frequency

Serial.print(“ “);

delay(500);

Serial.print (“B=”);// printing name

digitalWrite(4,LOW);

digitalWrite(5,HIGH);// setting for BLUE color sensor

frequency = pulseIn(OutPut, LOW);// reading frequency

Serial.print (frequency);// printing BLUE color frequency

Serial.print (“ “);

delay(500);

Serial.print (“G=”);// printing name

digitalWrite(4,HIGH);
digitalWrite(5,HIGH);// setting for GREEN color sensor

frequency = pulseIn(OutPut, LOW);// reading frequency

Serial.print (frequency);// printing GREEN color frequency

Serial.print (“ “);

delay(500);

Serial.println(“****************************”);

|5
02 Connect and Control WS2812 RGB
LED Strips via Raspberry Pi
In this project we are going to interface WS2812 RGB led with raspberry
pi. These LED strips are very different, but both can be controlled with the
Raspberry Pi. The models WS2812B and WS2811 are also compatible and
can be addressed with this guide.
It must be said that one should not be fooled by the “smaller” model number
of the WS2801. This has – apart from the price – a few advantages, which will
be discussed in more detail below.

Components:
Anyone who has already used an RGB LED strip (such as Ambilight) can
continue to use the accessories. This includes the following in addition to a
Raspberry Pi:

01 For beginners: power supply + connector


02 For experienced: switching power supply 5V 10A + power cord
03 Jumper cable
04 Breadboard

The maximum power of the power supply depends on the number of LEDs.
According to the data sheet, an LED under full load (= maximum brightness)
needs about 60mA. At 5m and 30 LEDs / m, this is 9 amps. So, a power supply,
which has up to 10A is suitable. If you have more LEDs in use, you may need
more than one power supply (more on that later).
In addition, of course, the actual RGB LED strip of the type WS2812 (B)
or WS2811 (also called NeoPixel) is required. These are available in three
different versions, which differ in the number of LEDs per meter:

zz LED Strip mit 30 LEDs per meter


zz LED Strip mit 60 LEDs per meter
zz LED Strip mit 144 LEDs per meter

The length should be chosen depending on the project to be implemented.


But mostly 5m rolls are a bit cheaper. My recommendation is the middle

|6
version with 60 LEDs/m. These have a higher density of lights and thus a higher brightness. In
terms of price, however, they are still cheaper than a similarly long WS2801 strip with only 32
LEDs.

Connecting the NeoPixel WS2812 to the Raspberry Pi


Before we connect the Raspberry Pi to the WS2812 LED Strip, we finish the power supply. If your
strip has less than 20-30 LEDs, external power is not required. If it has more LEDs, the power of
the Pi, however, is no longer enough and an external power supply is required.
The power supply itself depends on the selected type. For a power adapter with additional DC
adapter (beginners), only the DC adapter needs to be connected, which will be followed by the
power cables of the WS2812B. Once you have chosen this method, you can jump to the next
point. A switched-mode power supply (for experienced users), however, is a little more complex.
Before, however, the note: When working with 230V caution is necessary because of mortal
danger! Get help from an electrician or get back to the safe version of the normal power supply!
Perform all work with a separate network connection.
First, we need a standard power cable that can handle 10A. Mostly on the bottom of the plug
is a corresponding note (230V, 10A). We cut this cable carefully with a utility knife or similar.It
contains two or three cables with different colors. These cables must also be carefully stripped.

My cable has only two inner cables, but


that’s enough. For connection to the
switching power supply, the colors of
the inner cables serve as orientation.
The switching power supply has the
connections “L”, “N” and “PE” or a
grounding symbol.

The black or brown inner cable comes to the outer conductor “L”.
The blue inner cable comes to the neutral conductor “N”.
The green-yellow inner cable is connected to the protective conductor “PE” or earthing symbol.
Multimeter am Schaltnetzteil des WS2801 LED Strip

|7
After the locking screws have been tightened, the power cord can be plugged into the socket
and the voltage at the power supply can be measured with a multimeter. Although this is not
mandatory, but can be made as a hedge. VCC is connected to V+ and GND to COM. If the voltage
is not exactly 5V, this is not a problem.
Theoretically, it is also possible to power the Raspberry Pi from this power supply. Some users
(according to comments in the WS2801 tutorial) also have done this. For reasons of space, this
will not be discussed here.

Connection between Raspberry Pi and WS2812 NeoPixel stripes


If the power supply is set up so far, we connect the Raspberry Pi to the WS2812 RGB LED strip.
The (switching) power supply must first be disconnected from the power.
Since there is only one data line, we only need one pin (GPIO 18). It is important that the ground
connections of the Raspberry Pi and the switching power supply are connected, but not the 5V
voltages! Overall, only two cables run from the Raspberry Pi to the WS2812 LED Strip: GPIO 18
(to DIN) and GND to COM of the PSU and GND of the strip.

Depending on the length of the LED strip, the external power connection should be installed in
several places. Ideally, the VCC and GND will be connected in parallel with the switching power
supply on approximately every meter (so that many cables will lead to the power supply input).

Note: For lengths less than 1m, the power supply can also be omitted and
the input voltage from the RV 5V pin of the Raspberry Pi come.

|8
Preparation & Installation
Before we install the Raspberry Pi library for the WS2812 LEDs, some preparations have to be
made:

01 The package sources are updated:


sudo apt-get update

02 We install the required packages (confirm with Y):


sudo apt-get install gcc make build-essential python-dev git scons swig

03 The audio output must be deactivated. For this we edit the file
sudo nano /etc/modprobe.d/snd-blacklist.conf

04 Here we add the following line:


blacklist snd_bcm2835

Then the file is saved by pressing CTRL + O and CTRL + X closes the editor.

05 We also need to edit the configuration file:


sudo nano /boot/config.txt

Below are lines with the following content (with Ctrl + W you can search):
06 # Enable audio (loads snd_bcm2835)
dtparam=audio=on

07 This bottom line is commented out with a hashtag # at the beginning of the line:
#dtparam=audio=on

10010101000110001010001100101010100100100
08 We restart the system
sudo reboot 100101001001100111001010101001100010100101
10010101000110001010001100101010100100100
Now we can download the library.
100101001001100111001010101001100010100101
git clone https://github.com/jgarff/rpi_ws281x 10010101000110001010001100101010100100100
In this directory are on the one hand some C files
included, which can be easily compiled. The example
100101001001100111001010101001100010100101
code for this is easy to understand. In order to use 10010010110010101000110001010001100101010
them in Python, we need to compile them:
001010010100101001001100111001010101001100
cd rpi_ws281x/ 0110
sudo scons
However, in this tutorial we are mainly interested 10010101000110001010001100101010100100100
in the Python variant and therefore switch to the 100101001001100111001010101001100010100101
Python folder:
1001

|9
cd python
Here we carry out the installation:

sudo python setup.py build


sudo python setup.py install
This will allow us to carry out a first test in the next step.

Test the Raspberry Pi WS2812 RGB LED Strip


In the example folder are some
example files, with which the LED
strips can be tested. In addition,
even two WS2801 LED strips can
be independently controlled by
Raspberry Pi (multistrandtest.py).
We are initially interested in the
simple version. For this we have to
complete a few details before the test
and therefore we edit the sample file.

sudo nano examples/strandtest.py


The file looks like this, where we have to state LED_COUNT (number of LEDs to be addressed)
and LED_PIN (18 us).
#!/usr/bin/env python3
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.

import time
from neopixel import *
import argparse

# LED strip configuration:


LED_COUNT = 16 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
#LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to ‘1’ for GPIOs 13, 19, 41, 45 or 53

| 10
Code:

# Define functions which animate LEDs in various ways.

def colorWipe(strip, color, wait_ms=50):

“””Wipe color across display a pixel at a time.”””

for i in range(strip.numPixels()):

strip.setPixelColor(i, color)

strip.show()

time.sleep(wait_ms/1000.0)

def theaterChase(strip, color, wait_ms=50, iterations=10):

“””Movie theater light style chaser animation.”””

for j in range(iterations):

for q in range(3):

for i in range(0, strip.numPixels(), 3):

strip.setPixelColor(i+q, color)

strip.show()

time.sleep(wait_ms/1000.0)

for i in range(0, strip.numPixels(), 3):

strip.setPixelColor(i+q, 0)

def wheel(pos):

“””Generate rainbow colors across 0-255 positions.”””

if pos < 85:

return Color(pos * 3, 255 - pos * 3, 0)

elif pos < 170:

pos -= 85

return Color(255 - pos * 3, 0, pos * 3)

else:

pos -= 170

return Color(0, pos * 3, 255 - pos * 3)

def rainbow(strip, wait_ms=20, iterations=1):

“””Draw rainbow that fades across all pixels at once.”””

| 11
for j in range(256*iterations):

for i in range(strip.numPixels()):

strip.setPixelColor(i, wheel((i+j) & 255))

strip.show()

time.sleep(wait_ms/1000.0)

def rainbowCycle(strip, wait_ms=20, iterations=5):

“””Draw rainbow that uniformly distributes itself across all pixels.”””

for j in range(256*iterations):

for i in range(strip.numPixels()):

strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) &


255))

strip.show()

time.sleep(wait_ms/1000.0)

def theaterChaseRainbow(strip, wait_ms=50):

“””Rainbow movie theater light style chaser animation.”””

for j in range(256):

for q in range(3):

for i in range(0, strip.numPixels(), 3):

strip.setPixelColor(i+q, wheel((i+j) % 255))

strip.show()

time.sleep(wait_ms/1000.0)

for i in range(0, strip.numPixels(), 3):

strip.setPixelColor(i+q, 0)

# Main program logic follows:

if __name__ == ‘__main__’:

# Process arguments

parser = argparse.ArgumentParser()

parser.add_argument(‘-c’, ‘--clear’, action=’store_true’, help=’clear the


display on exit’)

args = parser.parse_args()

| 12
# Create NeoPixel object with appropriate configuration.

strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,


LED_BRIGHTNESS, LED_CHANNEL)

# Intialize the library (must be called once before other functions).

strip.begin()

print (‘Press Ctrl-C to quit.’)

if not args.clear:

print(‘Use “-c” argument to clear LEDs on exit’)

try:

while True:

print (‘Color wipe animations.’)

colorWipe(strip, Color(255, 0, 0)) # Red wipe

colorWipe(strip, Color(0, 255, 0)) # Blue wipe

colorWipe(strip, Color(0, 0, 255)) # Green wipe

print (‘Theater chase animations.’)

theaterChase(strip, Color(127, 127, 127)) # White theater chase

theaterChase(strip, Color(127, 0, 0)) # Red theater chase

theaterChase(strip, Color( 0, 0, 127)) # Blue theater chase

print (‘Rainbow animations.’)

rainbow(strip)

rainbowCycle(strip)

theaterChaseRainbow(strip)

except KeyboardInterrupt:

if args.clear:

colorWipe(strip, Color(0,0,0), 10)

Then we save (CTRL + O) and return to the terminal (CTRL + X). Now the file can be executed
(passing the path to the compiled files is important):

sudo PYTHONPATH=”.:build/lib.linux-armv7l-2.7” python examples/strandtest.py


The LEDs of the WS2812 strip should light

| 13
03 Door Bell using RF module
In this project every time a bell switch at
door is pressed alarm will be generated and
also an email will be sent to a specific person.
An RF modules are 433 MHz RF transmitter
and receiver modules. The transmitter draws
no power when transmitting logic zero while
fully suppressing the carrier frequency thus
consume significantly low power in battery
operation. When logic one is sent carrier is
fully on to about 4.5mA with a 3volts power
supply. The data is sent serially from the
transmitter which is received by the tuned
receiver. Transmitter and the receiver are
duly interfaced to two microcontrollers for
data transfer.
In order to send e-mails from ESP8266 Module, you need to follow the SMTP protocol. Hence, an
SMTP Server is required to send the e-mails and the ESP8266 will act as an SMTP Client. In this
project we will be using SMTP2GO server.

Components:
01 NodeMCU
02 RF module pair 433MHZ
03 Push button

Circuit Diagram:

| 14
Steps for sending Email:
In order to send e-mails from ESP8266 Module, you need to follow the SMTP protocol. Hence, an
SMTP Server is required to send the e-mails and the ESP8266 will act as an SMTP Client.
I have tried the Gmail’s SMTP Settings several times to send email using ESP8266 but it was not
fruitful. So, I have decided to use a third-party SMTP Server and I found “SMTP2GO” as a reliable
choice.

So, go to the SMTP2GO website and register with a free account. After creating an account, the
first step is to create the SMTP Username and SMTP Password. In fact, the moment you confirm
your e-mail address and first login to SMTP2GO, this is the information that you’ll get.
Leave the username as it is i.e. the e-mail address and change the SMTP Password with your own

| 15
choice. Note that this is SMTP Password and is different from the SMTP2GO Login Password.
Make a note of the two i.e. SMTP Username and SMTP Password.  
Now, enter the dashboard of the SMTP2GO app and on the left access bar, click on “Settings” and
then on “Users”.
In that, you can see the information regarding the SMTP Server and PORT number. It is usually as
follows:
SMTP Server: mail.smtp2go.com
SMTP PORT: 2525

Note down this information as you need to use this data in the code.

Encoding Username and Password


You need to encode your SMTP Username and SMTP Password to Base64 format
with ASCII Character Set. For this, you can either use an Arduino Library or a website
called BASE64ENCODE.

| 16
Enter your SMTP Username and Password separately and note the
encoded content. For example, if your email address is test@gmail.com,
it would be encoded as dGVzdEBnbWFpbC5jb20=.
And if your password is “testpassword” (excluding the quotes), it would
be encoded as dGVzdHBhc3N3b3Jk.  

Explanation of the Code


The initial section of the code is simple used to connect the ESP8266
WiFi Module to the Internet. If the connection is successful, you will get
an IP Address.
Next is the actual code for sending the e-mail. The code can be divided
into 8 stages.

In stage 1, you will be connecting to the SMTP Server


Stage on a PORT. This is done using the command client.
01 connect(SMTP_SERVER, SMTP_PORT). In response, you
will get a 220 code.

Greet the SMTP Server with EHLO Command (Previously


Stage HELO Command). The command is client.println(“EHLO
02 www.example.com”);
If the connection is successful, you will get a 250
Response Code.

Stage 3 is to authorize the user with AUTH LOGIN


Stage Command. The command is client.println(“AUTH
03 LOGIN”);. You will get a Response 334 for success.

Send the encoded SMTP Username and Password one


Stage after the other. The commands are client.println(“Base64,
ASCII encoded username”); and client.println(“Base64,
04 ASCII encoded password”);.
If the authentication is success, you will get a 235
Response.

Now its time to send the mail from string where you have
Stage to enter the sender’s email address using the format MAIL
05 FROM:<”+String(from)+’>’;.
The command is client.println(“MAIL From: sender@
gmail.com”);

| 17
Then send the rcpt to string using the format RCPT TO:<”+String(to)+’>’;. The
Stage command is client.println(“RCPT To: receiver@gmail.com”);.
06

Send the “DATA” followed by the Message body of the e-mail. The commands are
Stage
07
client.println(“DATA”);
client.println(“To: receiver@gmail.com”);
client.println(“From: sender@gmail.com”);
client.println(“Subject: ESP8266 test e-mail\r\n”);
client.println(“This is is a test e-mail sent from ESP8266.\n”);
client.println(“Second line of the test e-mail.”);
stage 8: Finally, terminate the mail with “.” and send the quit command.
client.println(“.”);
client.println(“QUIT”);

All these commands and responses will be shown in the serial monitor of the Arduino IDE.

| 18
04 Smart switch (home automation)
over web browser
In this project, we will be using the ESP8266 – 01 Wi-Fi Development board to make asmall home
automation that has Wi-Fi featured in it. The system operates on a local web server and is easy to
use for the novice. With this project, we can control at most two AC appliances which suit best for
your small IoT projects.
On a local web server, we do not require Internet and handling everything over Wi-Fi is possible.
Here, we will be handling the two Input & Output pins and switching relays on a web page of the
local server. We can connect our home appliances with the Relay Module that will be driven by
ESP8266 – 01.

Components:
01 ESP8266 – 01 04 One (1) 2-Channel Relay Module
02 FTDI Board 05 Breadboard with some wires.
03 2 AC Appliances

Connections:

01 Connect the FTDI pins to ESP8266 as 03 Also, check if your ESP8266


shown. supports 9600 or any other Baud Rate.
02 Select your COM Port from Tools > Port 04 Now Click Upload.
after connecting FTDI USB to your PC or Laptop.

| 19
Circuit Diagram for Home Automation:
Flow the circuit diagram for making the home automation system.

GPIO 0 -> Relay IN 1


GPIO 2 -> Relay IN 2

We will use 5 volts input supply for driving the Relay Module and 3.3 Volts Input for the ESP8266.

Connecting to the web using the IP address


After uploading the code, go to Open Tools>Serial Monitor. ESP8266 will try to connect to Wi-Fi
and display its IP address on Arduino serial monitor. This IP is needed only the first time. The IP
remains the same forever so have this IP before making the main connections.
Make sure that the Wi-Fi router to be connected is already open. Hit this IP address in the

browser of the device connected to the same Wi-Fi.

Url: http://192.168.xx.xx (your IP displayed in Arduino serial monitor)


You will be able to see the HTML Web page mentioned in the code.
Try with,
http://<your IP address>/gpio1/0
http://<your IP address>/gpio1/1
http://<your IP address>/gpio2/0
http://<your IP address>/gpio2/1

| 20
Code:

#include <ESP8266WiFi.h> // This library helps to provide the


functions of the ESP8266

const char* ssid = “xxxx”; // Declare your Wi-Fi name here within
the double quotes

const char* password = “xxxx”; // Declare your Wi-Fi password here


within the double quotes

WiFiServer server(80); // Create an instance of the server and


specify the port to listen on as an argument

void setup()

Serial.begin(9600); // set buad rate

delay(10);

pinMode(0, OUTPUT); // set GPIO 0 as OUTPUT

pinMode(2, OUTPUT); // set GPIO 2 as OUTPUT

digitalWrite(0, 0); // initially set GPIO 0 as Low

digitalWrite(2, 0); // initially set GPIO 2 as Low

Serial.println();

Serial.println();

Serial.print(“Connecting to “); // Connect to WiFi network

Serial.println(ssid);

WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)

delay(500);

Serial.print(“.”);

Serial.println(“”);

Serial.println(“WiFi connected”);

server.begin(); // Start the server

Serial.println(“Server started”);

Serial.println(WiFi.localIP()); // Print the IP address

| 21
}

void loop()

WiFiClient client = server.available(); // Check if a client has connected

if (!client)

return; // Wait until the client sends some


data

Serial.println(“new client”);

while(!client.available())

delay(1);

String req = client.readStringUntil(‘\r’); // Read the first line of the request

Serial.println(req);

client.flush();

int val1;

int val2;

if (req.indexOf(“/gpio1/0”) != -1) // Match the request

val1 = 1;

else if (req.indexOf(“/gpio1/1”) != -1)

val1 = 0;

else if (req.indexOf(“/gpio2/0”) != -1)

val2 = 1;

else if (req.indexOf(“/gpio2/1”) != -1)

val2 = 0;

else

Serial.println(“invalid request”);

client.stop();

return;

| 22
}

digitalWrite(2, val1); // Set GPIO 2 according to the request

digitalWrite(0, val2); // Set GPIO 0 according to the request

client.flush();

String s = “HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\


n<html>”; // Prepare the response

s += “<body><h1>ESP8266 Smallest Home Automation</h1>\r\nGPIO1 is now “;

s += (val1)?”high”:”low”;

s += “\n GPIO2 is now “;

s += (val2)?”high”:”low”;

s += “</html>\n”;

client.print(s); // Send the response to the client

delay(1);

Serial.println(“Client disonnected”); // The client will actually be


disconnected and when the function returns and ‘client’ object is detroyed

| 23
05 Home Automation (Android App)
We are moving into an era where man power is being replaced by Technology. Technology has
shown its advancements through the long passage of time and now we rely on technology to do
every small or big daily life tasks in one click. Automated Home Assistant provides its user with
the ability to control the home appliances and ensure its security with just one tap on its Android
App. This has been discussed in detail in following sections.
In this Project we are using Android app to control the home appliances. We are using Raspberry
Pi for Fire alarm sensor and to send data related to the sensor on the android app. Also we are
using Wemos module to control the bulb (light).

Components:
01 Raspberry Pi 3b 04 Wemos Module d1 mini
02 Buzzer 05 Flame Sensor
03 Bulb 06 Relay module 5V

Circuit Diagram:

| 24
Code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = “”;


const char* password = “”;
const char* mqtt_server = “www.mosquitto.org”;

// Topic to subscribe to
String topic = “fyp/room1”;

// Pin configuration
const int led1Pin = 5;
const int led2Pin = 4;
const int led3Pin = 0;
const int fanPin = 2;
const int doorPin = 16;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(“.”);
}

randomSeed(micros());

Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}

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


Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);

| 25
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Depending on payload, turn the respective component ON/OFF


if ((char)payload[0] == ‘f’) {
if ((char)payload[5] == ‘n’) {
digitalWrite(fanPin, LOW);
}
else if ((char)payload[5] == ‘f’) {
digitalWrite(fanPin, HIGH);
}
}
else if ((char)payload[0] == ‘l’) {
if ((char)payload[3] == ‘1’) {
if ((char)payload[6] == ‘n’) {
Serial.println(“LED1 ON”);
digitalWrite(led1Pin, LOW);
}
else if ((char)payload[6] == ‘f’) {
Serial.println(“LED1 OFF”);
digitalWrite(led1Pin, HIGH);
}
}
else if ((char)payload[3] == ‘2’) {
if ((char)payload[6] == ‘n’) {
digitalWrite(led2Pin, LOW);
}
else if ((char)payload[6] == ‘f’) {
digitalWrite(led2Pin, HIGH);
}
}
else if ((char)payload[3] == ‘3’) {
if ((char)payload[6] == ‘n’) {
digitalWrite(led3Pin, LOW);
}
else if ((char)payload[6] == ‘f’) {
digitalWrite(led3Pin, HIGH);
}
}

}
else if ((char)payload[0] == ‘d’) {

if ((char)payload[6] == ‘n’) {
digitalWrite(doorPin, LOW);
}
else if ((char)payload[6] == ‘f’) {
digitalWrite(doorPin, HIGH);
}
}
}

| 26
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection...”);
// Create a random client ID
String clientId = “ESP8266Client-”;
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println(“connected”);
client.subscribe(topic.c_str());
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(“ try again in 5 seconds”);
// Wait 5 seconds before retrying
delay(5000);
}
}
}

void setup() {
// Initalize the GPIO as output
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(led3Pin, OUTPUT);
pinMode(fanPin, OUTPUT);
pinMode(doorPin, OUTPUT);

// Turn the relays off initially


digitalWrite(led1Pin, HIGH);
digitalWrite(led2Pin, HIGH);
digitalWrite(led3Pin, HIGH);
digitalWrite(fanPin, HIGH);
digitalWrite(doorPin, HIGH);
// Start Serial UART for debugging
Serial.begin(115200);

// Setup connection with internet router


setup_wifi();

// Setup connection with Mosquitto broker


client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

| 27
06 Live feed using Pi Camera
In this project we’re going to do video streaming with a Raspberry
Pi and a Raspberry Pi Camera – how to stream live video into a
web page that you can access in any device that has a browser and
is connected to the same network the Pi is. This is useful to apply
to a home surveillance camera, for example.

Enable the Rasperry Pi Camera Module


You need to enable the camera software in your Raspberry Pi in
order to use it. In the Desktop environment, go to the Raspberry
Pi Configuration window under the Preferences menu, open the
Interfaces tab and enable the Camera as shown in figure below.

| 28
Or, in the Terminal window, type the following command:

pi@raspberry:~ $ sudo raspi-config

You should see the Raspberry Pi software configuration tool. Select the Interfacing Options:

Enable the camera and reboot your Pi

Find the Raspberry Pi IP address


To access your video streaming web server, you need to know your Raspberry Pi IP address. For
that, use the following command:

pi@raspberry:~ $ ifconfig
You’ll be given a bunch of information, including your Raspberry Pi IP address. In my case, the RPi
IP address is 192.168.1.112.

| 29
Connect the camera
Connecting the Raspberry Pi Camera Module is easy. With the Pi shutdown, connect the camera
to the Pi CSI port as shown in the following figure. Make sure the camera is connected in the right
orientation with the ribbon blue letters facing up as shown in the next figure.

Writing the script:


Create a new file called rpi_camera_surveillance_system.py:
pi@raspberrypi:~ $ nano rpi_camera_surveillance_system.py

Copy the following the code in the new file:


Code:

# Web streaming example


# Source code from the official PiCamera package
# http://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming

import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

| 30
PAGE=”””\
<html>
<head>
<title>Raspberry Pi - Surveillance Camera</title>
</head>
<body>
<center><h1>Raspberry Pi - Surveillance Camera</h1></center>
<center><img src=”stream.mjpg” width=”640” height=”480”></center>
</body>
</html>
“””

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):


        if buf.startswith(b’\xff\xd8’):
            # New frame, copy the existing buffer’s content and notify all
            # clients it’s available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == ‘/’:
            self.send_response(301)
            self.send_header(‘Location’, ‘/index.html’)
            self.end_headers()
        elif self.path == ‘/index.html’:
            content = PAGE.encode(‘utf-8’)
            self.send_response(200)
            self.send_header(‘Content-Type’, ‘text/html’)
            self.send_header(‘Content-Length’, len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == ‘/stream.mjpg’:
            self.send_response(200)
            self.send_header(‘Age’, 0)
            self.send_header(‘Cache-Control’, ‘no-cache, private’)
            self.send_header(‘Pragma’, ‘no-cache’)
            self.send_header(‘Content-Type’, ‘multipart/x-mixed-replace;
boundary=FRAME’)

| 31
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b’--FRAME\r\n’)
                    self.send_header(‘Content-Type’, ‘image/jpeg’)
                    self.send_header(‘Content-Length’, len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b’\r\n’)
            except Exception as e:
                logging.warning(
                    ‘Removed streaming client %s: %s’,
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):


    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution=’640x480’, framerate=24) as camera:


    output = StreamingOutput()
    #Uncomment the next line to change your Pi’s Camera rotation (in degrees)
    #camera.rotation = 90
    camera.start_recording(output, format=’mjpeg’)
    try:
        address = (‘’, 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()

Accessing the video streaming


After writing the scrip, you can run it using Python 3. Run the next command:

pi@raspberrypi:~ $ python3 rpi_camera_surveillance_system.py

Once the script is running, you can access your video streaming web server at:
http://<Your_Pi_IP_Address>:8000. Replace with your own Raspberry Pi IP address, in my
case http://192.168.1.112:8000.
You can access the video streaming through any device that has a browser and is connected to
the same network that your Pi.

| 32
07 Missile Control using Arduino
In this project we are going to control the
direction of missile using servo motors
and joy stick. The main aim or goal for
building this project was to learn more
about controlling servos with a joystick
module. A servomotor is a rotary actuator
or linear actuator that allows for precise
control of angular or linear position,
velocity and acceleration. It consists of
a suitable motor coupled to a sensor
for position feedback. It also requires a
relatively sophisticated controller, often
a dedicated module designed specifically
for use with servomotors.

Components:
01 Two Servo motors
02 Arduino Nano
03 Sparkfun Joy Stick

| 33
Code:
#include <Servo.h>

Servo myservo1; // create servo object to control a servo

Servo myservo2;

int potpin1 = A0; // analog pin used to connect the potentiometer

int potpin2 = A1;

int val; // variable to read the value from the analog pin

void setup() {

myservo1.attach(9);

myservo2.attach(10);// attaches the servo on pin 9 to the servo object

void loop() {

val = analogRead(float(potpin1)); // reads the value of the


potentiometer (value between 0 and 1023)

val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value
between 0 and 180)

myservo1.write(val); // sets the servo position according to the


scaled value

delay(15); // waits for the servo to get there

val = analogRead(float(potpin2)); // reads the value of the


potentiometer (value between 0 and 1023)

val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value
between 0 and 180)

myservo2.write(val); // sets the servo position according to the


scaled value

delay(15);

| 34
08 Controlling motors using
Accelerometer
In this project, we are
going to control the speed
of 2 DC motors using the
MPU-6050. MPU-6050
is an accelerometer and
Gyro sensor. By moving
the sensor in upward or
downward direction, the
speed of the motors will
increase or decrease.
By moving the sensor in
upward direction, the
speed of first motor will
increase and the speed of
other motor will decrease.
Similarly, by moving the
sensor in downward
direction, the speed of first
motor will increase and the
speed of other motor will
decrease.

Explanation

01 Firstly, we have to make the connections for L293D motor driver with Arduino. The
connections of the L293D motor driver with the Arduino are as follows.

zz Pin No. 1 of L293D IC is connected to 5V (Arduino 5V pin).

zz Pin No. 2 of L293D IC is connected to Pin No. 6 of Arduino.

zz Pin No. 3 of L293D IC is for the output of motor. Connect one end of the DC
motor to Pin No. 3 of L293D and other end of the DC motor to Pin No. 6 of
L293D.

zz Pin No’s 4, 5, 12 and 13 are the ground pins; connect these to GND (Arduino
GND pin).

zz Pin No. 7 of L293D IC is connected to Pin No. 5 of Arduino.

| 35
zz Pin No. 8 is the VCC pin, connect positive of battery to Pin No. 8 of L293D and
the negative of battery to the Ground.

zz Pin No. 9 of L293D IC is connected to 5V (Arduino 5V pin).

zz Pin No. 10 of L293D IC is connected to Pin No.9 of Arduino.

zz Pin No. 11 of L293D IC is the output pin for the second motor. Connect one end
of motor to Pin No. 11 and the second end of motor to the Pin No. 14 of L293D.

zz Pin No. 15 of L293D IC is connected to Pin No. 10 of Arduino.

zz Pin No. 16 of L293D IC is connected to 5V (Arduino 5V pin).

02 Secondly, make the connections for MPU-6050 with the Arduino

zz Connect VCC pin of MPU-6050 to the 5V pin of Arduino

zz Connect GND pin of MPU-6050 to the GND of Arduino

zz Connect SCL pin of MPU-6050 to the A5 of Arduino

zz Connect SDA pin of MPU-6050 to the A4 of Arduino

MPU-6050 Accelerometer + Gyro Sensor


The MPU-6050 is a 6 DOF (Degrees of Freedom) or a six-axis IMU sensor, which means that it
gives six values as output. Three values from the accelerometer and three from the gyroscope.
An accelerometer works on the principle of the piezoelectric effect and Gyroscopes work on the
principle of Coriolis acceleration.
The MPU-6050 is a sensor based on MEMS (Micro Electro Mechanical Systems) technology. Both
the accelerometer and the gyroscope are embedded inside a single chip. This chip uses I2C (Inter-
Integrated Circuit) protocol for communication.

| 36
Circuit Diagram:

Code:
#include <Wire.h>

#include <MPU6050.h>

#define first_motor_pin1 5

#define first_motor_pin2 6

#define second_motor_pin1 9

#define second_motor_pin2 10

MPU6050 sensor;

int16_t ax, ay, az;

int16_t gx, gy, gz;

int first_motor_speed;

int second_motor_speed;

| 37
void setup ( )

Wire.begin( );

Serial.begin (9600);

Serial.println (“Initializing the sensor”);

sensor.initialize ( );

Serial.println(sensor.testConnection( ) ? “Successfully Connected” :


“Connection failed”);

delay(1000);

Serial.println(“Taking Values from the sensor”);

delay(1000);

void loop ( )

sensor.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

ax = map(ax, -17000, 17000, -125, 125);

first_motor_speed = 125+ax;

second_motor_speed = 125-ax;

Serial.print (“Motor1 Speed = “);

Serial.print (first_motor_speed, DEC);

Serial.print (“ && “);

Serial.print (“Motor2 Speed = “);


Serial.println (second_motor_speed, DEC);

analogWrite (first_motor_pin2, first_motor_speed);

analogWrite (second_motor_pin2, second_motor_speed);

delay (200);

| 38
09 Detection of Posture Change
In this project we have made a device which detect the change of posture in the body. The
application of this device could a falling body. Back pain affects a large amount of people around
the world, impacting the health of the spine and leading to many health problems (negative
impacts on the quality of life, sleep disorders, respiratory problems...)
Half of back pains are caused by improper posture and could therefore been prevented and cured
by correcting the posture. The only requirement is to actually detect a bad posture. So this could
be another application of the device.

Components: Circuit Diagram:


01 Arduino Uno
02 Gy521 accelerometer

| 39
Code:
#include<Wire.h>

const int MPU=0x68;

int16_t AcX=0,AcY=0,AcZ=0;

int16_t GyX,GyZ,GyY ;

int16_t Current_AcX=0,Current_AcY=0,Current_AcZ=0;

void setup(){

pinMode(4, OUTPUT);

Wire.begin();

Wire.beginTransmission(MPU);

Wire.write(0x6B);

Wire.write(0);

Wire.endTransmission(true);

Serial.begin(9600);

Wire.beginTransmission(MPU);

Wire.write(0x3B);

Wire.endTransmission(false);

Wire.requestFrom(MPU,12,true);

AcX=Wire.read()<<8|Wire.read();

AcY=Wire.read()<<8|Wire.read();

AcZ=Wire.read()<<8|Wire.read();

GyX=Wire.read()<<8|Wire.read();

GyY=Wire.read()<<8|Wire.read();

GyZ=Wire.read()<<8|Wire.read();

Serial.print(“X = “); Serial.print(AcX);

Serial.print(“ | Y = “); Serial.print(AcY);

Serial.print(“ | Z = “); Serial.println(AcZ);

Current_AcX=AcX;

Current_AcY=AcY;

Current_AcZ=AcZ;

void loop(){

Wire.beginTransmission(MPU);

| 40
Wire.write(0x3B);

Wire.endTransmission(false);

Wire.requestFrom(MPU,12,true);

AcX=Wire.read()<<8|Wire.read();

AcY=Wire.read()<<8|Wire.read();

AcZ=Wire.read()<<8|Wire.read();

GyX=Wire.read()<<8|Wire.read();

GyY=Wire.read()<<8|Wire.read();

GyZ=Wire.read()<<8|Wire.read();

Serial.print(“X = “); Serial.print(AcX);

Serial.print(“ | Y = “); Serial.print(AcY);

Serial.print(“ | Z = “); Serial.println(AcZ);

if(abs(Current_AcX-AcX)>=300||abs(Current_AcY-AcY)>=300||abs(Current_AcY-AcY)>=300)

Serial.println(“posture changed”);

Current_AcX=AcX;

Current_AcY=AcY;

Current_AcZ=AcZ;

digitalWrite(4, HIGH);

}
Serial.println(“ “);

delay(1000);

| 41
10 NodeMCU Based Weather Station
Humidity, Temperature
and Pressure are three
basic parameters to build
any Weather Station and
to measure environmental
conditions. In this project,
we will measure Humidity,
Temperature and Pressure
parameters and display them
on the Serial Monitor. For
the purpose of measuring
temperature we will be using
DHT11 sensor and for pressure
we will be using BMP180
sensor.

Components Required
01 NodeMCU
02 DHT11 sensor
03 BMP180 sensor
04 Breadboard
05 Jumper Wires

Circuit Diagram

| 42
Code:

#include <ESP8266WiFi.h>

#include “DHT.h”

#include <SFE_BMP180.h>

#include <Wire.h>

#define ALTITUDE 431.0

#define DHTPIN 0 // what digital pin we’re connected to

#define DHTTYPE DHT11 // DHT 11

SFE_BMP180 pressure;

DHT dht(DHTPIN, DHTTYPE);

char status;

double T,P,p0,a;

void setup() {

Serial.begin(115200);

delay(100);

dht.begin();

Serial.print(“Connecting to “);

Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(“.”);

Serial.println(“”);

Serial.println(“WiFi is connected”);

server.begin();

Serial.println(“Server started”);

Serial.println(WiFi.localIP());

if (pressure.begin())

| 43
Serial.println(“BMP180 init success”);

else

Serial.println(“BMP180 init fail\n\n”);

while(1); // Pause forever.

delay(1000);

void loop() {

status = pressure.getPressure(P,T);

if (status != 0)

p0 = pressure.sealevel(P,ALTITUDE); // we’re at 1655 meters (Boulder, CO)

Serial.print(“relative (sea-level) pressure: “);

Serial.print(p0,2);

Serial.print(“ mb, “);

float h = dht.readHumidity();// Read temperature as Celsius (the default)

float t = dht.readTemperature();// Read temperature as Fahrenheit (isFahrenheit =


true)

float f = dht.readTemperature(true);

Serial.println(“temperature: ”);
Serial.print(t,2);

Serial.print(“*F”);

delay(4000);

| 44
Contact Us

Business: austin@inventr.io
Order Inquiry: orders@inventr.io
Other: help@inventr.io
www.inventr.io

Vous aimerez peut-être aussi