[go: up one dir, main page]

0% found this document useful (0 votes)
17 views14 pages

Ex 7

The document describes how to create communication between an Arduino and Raspberry Pi using a wireless medium like ESP8266. It provides the required components, background theory on ESP8266 WiFi module, code examples to connect ESP8266 to a wireless network and setup a server, and basics on UART, I2C and SPI communication protocols.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views14 pages

Ex 7

The document describes how to create communication between an Arduino and Raspberry Pi using a wireless medium like ESP8266. It provides the required components, background theory on ESP8266 WiFi module, code examples to connect ESP8266 to a wireless network and setup a server, and basics on UART, I2C and SPI communication protocols.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Ex. No.

7 COMMUNICATE BETWEEN ARDUINO AND RASPBERRY PI USING ANY


WIRELESS MEDIUM

OBJECTIVE:
To create a communication between Arduino and Raspberry Pi using Wireless Medium.

REQUIRED COMPONENTS:
● A DVI to HDMI cable
● A MicroSD card with Raspbian image loaded on it
● A mouse and keyboard
● A microUSB power supply
● A Raspberry Pi kit
● Arduino UNO

BACKGROUND THEORY:
ESP8266 is all about Wi-Fi. The Wi-Fi library for ESP8266 has been developed based on
ESP8266 SDK, using the naming conventions and overall functionality philosophy of the
Arduino WiFi library. In order to get the ESP8266 to work properly with the Arduino, it is
required to do some initial programming. Specifically, it will be changing the ESP8266 to work
as an access point and a client and changing the baud rate. Since most code samples out
there are communicating with the ESP module with a baud rate of 9600, that’s what will be
used. Also verify that the ESP8266 module can be connected to the router.
With the Arduino Uno connected to the computer, open the serial monitor via the Arduino
IDE (ctrl + shift + m). On the bottom of the serial monitor there are dropdowns for line endings
and baud rate. Set line endings to “Both NL & CR” and change the baud rate to “115200”.
Then send the following commands:
1. Verify that the ESP8266 is connected properly.
Command to send: AT Expected response: OK
2. Change the mode.
Command to send: AT+CWMODE=3 Expected response: OK
3. Connect to the router (Make sure to replace YOUR_SSID and
YOUR_WIFI_PASSWORD).
Command to send: AT+CWJAP=”YOUR_SSID”,”YOUR_WIFI_PASSWORD”
Expected response:
WIFI CONNECTED WIFI GOT IP
OK
4. Set baud rate to 9600.
Command to send: AT+UART=9600,8,1,0,0 Expected response: OK
5. Verify that the ESP8266 is communicating with baud rate of 9600.
Command to send: AT Expected response: OK
Basic Operation
#include "WiFiEsp.h" #include <ArduinoJson.h>
#ifndef HAVE_HWSERIAL1 #include "SoftwareSerial.h"
// set up software serial to allow serial communication to the TX and RX pins SoftwareSerial
Serial1(10, 11);
#endif
// Set baud rate of so it is possible to monitor output from esp. #define ESP8266_BAUD 9600
// CHANGE THIS TO MATCH YOUR SETTINGS
char ssid[] = "MY_SSID";
char pass[] = "MY_WIFI_PASSWORD"; i
nt status = WL_IDLE_STATUS;
// Define an esp server that will listen on port 80 WiFiEspServer server(80);
void setup()
{
// Open up communications for arduino serial and esp serial at same rate Serial.begin(9600);
Serial1.begin(9600);
// Initialize the esp module WiFi.init(&Serial1);
// Start connecting to wifi network and wait for connection to complete while (status !=
WL_CONNECTED)
{
Serial.print("Conecting to wifi network: "); Serial.println(ssid);
status = WiFi.begin(ssid, pass);
}
// Once connected log the IP address of the ESP module Serial.print("IP Address of ESP8266
Module is: "); Serial.println(WiFi.localIP());
Serial.println("You're connected to the network");
// Start the server server.begin();
}
// Continually check for new clients void loop()
{
WiFiEspClient client = server.available();
// If a client has connected... if (client)
{
String json = "";
Serial.println("A client has connected");
while (client.connected())
{
// Read in json from connected client if (client.available())
{
// ignore headers and read to first json bracket client.readStringUntil('{');
// get json body (everything inside of the main brackets) String jsonStrWithoutBrackets =
client.readStringUntil('}');
// Append brackets to make the string parseable as json String jsonStr = "{" +
jsonStrWithoutBrackets + "}";
// if managed to properly form jsonStr... if (jsonStr.indexOf('{', 0) >= 0)
{
// parse string into json, bufferSize calculated by https://arduinojson.org/v5/assistant/
const size_t bufferSize = JSON_OBJECT_SIZE(1) + 20; DynamicJsonBuffer
jsonBuffer(bufferSize);
JsonObject &root = jsonBuffer.parseObject(jsonStr);
// get and print the value of the action key in the json object const char *value = root["action"];
Serial.println(value);
if (strcmp(value, "on") == 0)
{
// Do something when receiving the on command Serial.println("Received on command from
client");
}
else if (strcmp(value, "off") == 0)
{
// Do something when receiving the off command Serial.println("Received off command from
client");
}
response
}
// send response and close connection client.print(
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\n" // the connection will be closed after completion of the "\r\n");
client.stop();
else
{
// It is unable to parse json, send http error status and close connection client.print(
"HTTP/1.1 500 ERROR\r\n"
"Connection: close\r\n" "\r\n");
Serial.println("Error, bad or missing json"); client.stop();
}
}
}
delay(10); client.stop();
Serial.println("Client disconnected");
}
}.
Circuit Basics
Devices that connect to Wi-Fi networks are called stations (STA). Connection to Wi-Fi is
provided by an access point (AP), that acts as a hub for one or more stations. The access
point on the other end is connected to a wired network. An access point is usually integrated
with a router to provide access from a Wi-Fi network to the internet. Each access point is
recognized by a SSID (Service Set IDentifier), that essentially is the name of network
selected when connecting a device (station) to the Wi-Fi.
ESP8266 modules can operate as a station, so it is possible to connect it to the Wi-Fi
network. It can also operate as a soft access point (soft-AP), to establish its own Wi-Fi
network. When the ESP8266 module is operating as a soft access point, it is possible to
connect other stations to the ESP module. ESP8266 is also able to operate as both a station
and a soft access point mode. This provides the possibility of building e.g. mesh networks.
ESP8266 Module.

I2C and SPI


UART, I2C and SPI are one of the most common and basic hardware communication
peripherals that makers and electricians use in microcontroller development. Similarly, for
the Arduino, they contain UART, I2C and SPI peripheral too. The Arduino Uno Rev 3 is a
microcontroller board based on the ATmega328, an 8-bit microcontroller with 32KB of
Flash memory and 2KB of RAM.
Arduino with I2C and SPI.

It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog
inputs, a 16 MHz crystal oscillator, a USB connection, a power jack, an ICSP header, and
a reset button
UART
UART stands for Universal Asynchronous Reception and Transmission and is a simple
communication protocol that allows the Arduino to communicate with serial devices. The
UART system communicates with digital pin 0 (RX), digital pin 1 (TX), and with another
computer via the USB port. This peripheral, found on all Arduino boards, allows the
Arduino to directly communicate with a computer thanks to the fact that the Arduino has
an onboard USB-to-Serial converter. Therefore, programs written on a Windows, Mac, or
Linux OS can be used with an Arduino connected to a USB port as if it was a serial port
(serial port communication is trivial compared to USB communication). UART, which
stands for Universal Asynchronous Reception and Transmission, is a simple serial
communication protocol that allows the host (Arduino) to communicate with serial devices.
UART supports bidirectional, asynchronous and serial data transmission. It uses 2 data
lines to communicate with each other which are: TX (Pin 1) and RX (Pin 0).
 TX – Used for transmitting
 RX – Used for receiving
They are connected between two devices (e.g., USB on Arduino and computer). UART is
found on all types of Arduino boards which allows the Arduino to communicate with a
computer due to its onboard USB to Serial converter. If the program is written on a
Windows, Mac or Linux OS and wants to use it with the Arduino, just connect them together
via the USB port as if it was a serial port.
Advantages and Disadvantages of using UART with Arduino Advantages of using UART
with Arduino
 Simple to operate and use with the Arduino. It is well documented online as it is a
widely used method by Arduino users with many resources and tutorials online.
 No clock needed.
Disadvantages of using UART with Arduino
 Lower speed compared to I2C and SPI.
 Baud rates of each UART must be within 10% of each other to prevent data loss.
 Cannot use multiple master systems like the Arduino and slaves.
I2C
I2C, which stands for inter-integrated-circuit, is a serial communications protocol specially
designed for microcontrollers. While this peripheral is almost never used for PC-device
communication, it is incredibly popular with modules and sensors, making it useful for
projects that require many parts working together. In fact, I2C allows to potentially connect
up to 128 devices to the main board!. When connecting two circuits to one another, think
of the main device as the “master” and the connected devices—such as sensors, pin
expansions, and drivers—as “slaves”. I2C makes it possible to connect multiple masters
and slaves to the board while maintaining a clear communication pathway.
Maintaining a clear communication pathway is possible because I2C uses an address
system and a shared bus, meaning many devices can be connected to the exact same
wires. However, the Arduino must first select a specific device by transmitting a unique
address before sending data. This provides each slave device with what it needs while
also supporting multiple masters. I2C uses fewer wires and all data is transmitted on a
single wire, keeping the pin count low. The tradeoff for this simplified wiring is slower
speeds than SPI.
SPI
SPI stands for Serial Peripheral Interface. Like I2C, SPI is a different form of serial-
communications protocol specially designed for microcontrollers to talk to each other.
However, it has some key differences from its I2C counterpart. The most notable
difference right off the bat is that, while using multiples masters and slaves with I2C, SPI
allows a single master device with a maximum of four slave devices.

SPI is typically much faster than I2C due to the simple protocol and, while data/clock lines
are shared between devices, each device requires a unique address wire. SPI is
commonly found in places where speed is important such as with SD cards and display
modules, or when information updates and changes quickly, like with temperature sensors.
Interfacing arduino and Blynk
IoT based Temperature and Humidity Monitoring using BLYNK Application. The ESP8266
Integrates 802.11b/g/n HT40 a Wi-Fi transceiver, so it cannot only connect with a Wi-Fi
network and interact with the Internet. It can also set up a network of its own, allowing
other devices to connect directly to it. There’s an on-board voltage regulator that ensures
the cleanest possible power to the NodeMCU itself, as well as a push-button reset and a
USB connection for easy interface with the computer.
DHT11 is a low-cost digital sensor for sensing temperature and humidity. This sensor can
easily have interfaced with any microcontroller such as Arduino, Raspberry Pi, etc… to
measure humidity and temperature instantaneously. DHT11 humidity and temperature
sensor are available as a sensor and as a module. The difference between this sensor
and module is the pull-up resistor and a power-on LED. DHT11 is a relative humidity
sensor.
The working of the DHT sensor is pretty simple. DHT11 sensor consists of a capacitive
humidity sensing element and a thermistor for sensing temperature. The humidity sensing
capacitor has two electrodes with a moisture-holding substrate as a dielectric between
them. Change in the capacitance value occurs with the change in humidity levels. The IC
measure, process this changed resistance values and change them into digital form.

For measuring temperature this sensor uses a Negative Temperature coefficient


thermistor, which causes a decrease in its resistance value with an increase in
temperature. To get a larger resistance value even for the smallest change in temperature,
this sensor is usually made up of semiconductor ceramics or polymers.
DHT11 Sensor.

The temperature range of DHT11 is from 0 to 50 degrees Celsius with a 2-degree accuracy.
The humidity range of this sensor is from 20 to 80% with 5% accuracy. The sampling rate
of this sensor is 1Hz. i.e. it gives one reading for every second. DHT11 is small in size with
an operating voltage from 3 to 5 volts. The maximum current used while measuring is
2.5mA.
Blynk was designed for the Internet of Things. It can control hardware remotely, it can
display sensor data, it can store data, visualize it, and do many other cool things. Every
time press a Button in the Blynk app, the message travels to the Blynk Cloud, where it
magically finds its way to the hardware. It works the same in the opposite direction and
everything happens in a blynk of an eye.
There are three major components in the platform:
 Blynk App - allows to create amazing interfaces for the projects using various
widgets provided.
 Blynk Server - responsible for all the communications between the smartphone and
hardware. It is possible use the Blynk Cloud or run the private Blynk server locally.
It’s open-source, could easily handle thousands of devices and can even be
launched on a Raspberry Pi.
 Blynk Libraries - for all the popular hardware platforms - enable communication with
the server and process all the incoming and outcoming commands.
For installation of the blynk app, it is needed to follow these steps Go to play store app
store and type blynk, it is possible to find the green color icon for the blynk app, then install
it on the device.
Blink App.

Auth token will be generated this auth token it is possible to get in the settings option of
this project and on the Gmail Account. Once the project is created, insert different types
of widget into it, for example it is possible to add two buttons from widget box shown
below. After selecting two Gauge click on the Settings Gauge and fill the details as in
following image.
Dash Board.

CODING:
#define BLYNK_PRINT Serial // Comment this out to disable prints and save space #include
<SPI.h>
#include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <SimpleTimer.h>
#include <DHT.h>
char auth[] = "TB6KiXEXl-------- qFo3Bp"; //To add the auth token
char ssid[] = "sneha123"; // your Wifi name char pass[] = "asdfghjkl"; // your wifi
password
#define DHTPIN D1 // Digital pin D1 float moisture;
#define DHTTYPE DHT11 // DHT 11 int temp, Humid;
DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer; WidgetTerminal terminal(V1); BLYNK_WRITE(V1)
{
terminal.write(param.getBuffer(), param.getLength()); terminal.println();
// Ensure everything is sent terminal.flush();
}
void sendSensor()
{
float h = dht.readHumidity();
float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit if (isnan(h) ||
isnan(t)) {
Serial.println("Failed to read from DHT sensor!"); return;
}
// To send any value at any time.
// Please don't send more that 10 values per second. Blynk.virtualWrite(V5, h); //V5 is for
Humidity Blynk.virtualWrite(V6, t); //V6 is for Temperature
}
void setup()
{
Serial.begin(9600); // See the connection status in Serial Monitor Blynk.begin(auth, ssid,
pass);
dht.begin();
timer.setInterval(1000L, sendSensor); terminal.flush();
}
void loop()
{
temp = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit Humid =
dht.readHumidity();
Serial.print("temp: "); Serial.print(temp); Serial.print(" c"); terminal.print("temp: ");
terminal.print(temp);
terminal.print(" c"); Serial.print(" Humidity: "); Serial.print(Humid);
Serial.println(" %"); terminal.print(" Humidity: "); terminal.print(Humid); terminal.println(" %");
delay(300);
terminal.flush();
Blynk.run(); // Initiates Blynk timer.run(); // Initiates SimpleTimer
}

Circuit Basics
Servo meter with Arduino
Servo motors use feedback to determine the position of the shaft, it is possible to control that
position very precisely. As a result, servo motors are used to control the position of objects,
rotate objects, move legs, arms or hands of robots, move sensors etc. with high precision.
Servo motors are small in size, and because they have built-in circuitry to control the
movement, they can be connected directly to an Arduino. Most servo motors have the
following three connections: Black/Brown ground wire. Red power wire (around 5V). Yellow
or White PWM wire.
In this experiment, it is possible to connect the power and ground pins directly to the Arduino
5V and GND pins. The PWM input will be connected to one of the Arduino's digital output
pins.
Hardware Required
 1 x TowerPro SG90 servo motor
 1 x Arduino Mega2560
 3 x jumper wires
The best thing about a servo motor is that it can be connected directly to an Arduino. Connect
to the motor to the Arduino as shown in the table below:
 Servo red wire – 5V pin Arduino
 Servo brown wire – Ground pin Arduino Servo yellow wire – PWM(9) pin Arduino
Arduino with Servo motor.
When the program starts running, the servo motor will rotate slowly from 0 degrees to
180 degrees, one degree at a time. When the motor has rotated 180 degrees, it will begin
to rotate in the other direction until it returns to the home position.
#include //Servo library
Servo servo_test; //initialize a servo object for the connected servo int
angle = 0;
void setup()
{
servo_test.attach(9); // attach the signal pin of servo to pin9 of arduino
}
void loop()
{
for(angle = 0; angle < 180; angle += 1) // command to move from 0 degrees to
180
degrees
{
servo_test.write(angle); //command to rotate the servo to the specified
angle delay(15);
}
delay(1000);
for(angle = 180; angle>=1; angle-=5) // command to move from 180 degrees to 0
degrees
{
servo_test.write(angle); //command to rotate the servo to the specified angle
delay(5);
}
delay(1000);
}

CONCLUSION:
Thus communication between Arduino and Raspberry Pi using Wireless Medium is done
successfully.

You might also like