NetMax IoT Report - Aditya
NetMax IoT Report - Aditya
IoT, RaspberryPi
SUBMITTED TO SUBMITTED BY
Mr. Rohit Khosla Aditya Chattopadhyay
Index
Introduction to RaspberryPi
Generations of RaspberryPi
o RaspberryPi 1 Model B
o RaspberryPi 1 Model A
o RaspberryPi 1 Model B+
o RaspberryPi 1 Model A+
o RaspberryPi 2 Model B
o RaspberryPi Zero
o RaspberryPi Zero W/WH
o RaspberryPi 3 B
o RaspberryPi 3 A+
o RaspberryPi 3 B+
Installation Of OS On The RaspberryPi
Raspberry Pi Configurations
Some Basic Linux Commands
Webcam on Raspberry Pi
Configuring motion server
WinSCP
Putty/Terminal (Linux/Windows)
Useful Linux Commands
Creating Hotspot on RaspberryPi
Introduction To Python
Syntax for Python (Version 2.7)
Downloading and Installing Python
Installing GPIO Library
Text Editors
o Sublime Text 3
o Atom
o Visual Studio Code (VSCode)
Connections On Raspberry Pi
o Introduction To GPIO
o Introduction To SPI
o Introduction to PWM
o Introduction to I2C
Programming With Python on Raspberry Pi
Sensors
o DHT11
o DHT22
o DS18B20
o LM35
o LDR
Cloud Services
o Google API
o UBI Dots
o Adafruit IO
o Particle IO
o ThingSpeak
o IFTTT
NodeMCU (ESP8266)
o NodeMCU With Aurdino IDE
o NodeMCU GPIO
o NodeMCU PWM
o NodeMCU SPI
o NodeMCU I2C
o NodeMCU HTTP Client
o Node MCU HTTP Server
o Node MCU MQTT
Introduction to RaspberryPi
The Raspberry Pi is a series of small single-board computers developed in
the United Kingdom by the Raspberry Pi Foundation to promote teaching of
basic computer science in schools and in developing countries. The original model
became far more popular than anticipated, selling outside its target market for
uses such as robotics. It does not include peripherals (such
as keyboards and mice) and cases. However, some accessories have been
included in several official and unofficial bundles.
Generations Of Raspberry Pi
RaspberryPi 1
1. Model B
2. Model A
4. Model A+
This model is square in shape.
700 MHz ARM11 ARM1176JZF-S processor core
256 MB of RAM
1 USB port
3.5mm jack for Audio outputs
Micro-SD card slot to save space
No Ethernet port
40 General Purpose Input/Output (GPIO) pins
RaspberryPi 2
1. Model B
1. Model Zero
RaspberryPi 3
1. Model B
Beginners should start with NOOBS – New out of the box software. We can
purchase a pre-installed NOOBS SD card from many retailers, such as Pimoroni,
Adafruit and The Pi Hut or download NOOBS
NOOBS Lite contains the same operating system installer without Raspbian pre-
loaded. It provides the same operating system selection menu allowing Raspbian
and other images to be downloaded and installed.
Getting NOOBS
Visit www.raspberrypi.org/downloads/
Insert your SD card into the computer or laptop’s SD card reader and make
a note of the drive letter allocated to it, e.g. G:
In SD Formatter, select the drive letter for your SD card, and format it.
Next, you will need to extract the files from the NOOBS zip archive you
downloaded from the Raspberry Pi website.
Go to your Downloads folder and find the zip file you downloaded.
Extract the files and keep the resulting Explorer/Finder window open.
follows-
You should check the box for Raspbian, and then click Install.
A similar interface is available for the installation of the NOOBS Version
3.0.1
After the install, the RaspberryPi boots up to display the main screen
RaspberryPi Configurations
On loading the main screen appears giving the IP-Address on the Wi-Fi icon
and other basic Debian features like the terminal and other Linux settings
Our first task is to configure the RaspberryPi according to our needs. To
enter into the settings menu, we click on the Pi icon and navigate to the
preferences tab.
On entering the “Raspberry Pi Configuration” option, we are taken into the
tab shown next.
We can set the name of the device using this menu. By default the name of
the device is set to “raspberrypi”.
Using the terminal, the device can be referenced by using the username
“pi”. Password by default is “raspberrypi”.
After finishing the settings on the first page, like the device name,
password, auto login settings, we move on to the Interfaces menu.
In the interfaces menu, we have the option to choose the devices the we
intend to interface with the Pi, these include :
o Camera
o SSH (Secure Shell)
o SPI (Serial Peripheral Interface)
o I2C (
o Serial Bus
Through this configuration we enable the settings for the SSH that is
required in order to interface the pi through other systems by the use of a
Linux terminal.
After finishing with the interface settings, we move on to the localization
settings in which we set the keyboard, time zone and the area.
o NOTE : The keyboard settings must be set to the English US as other
keyboard formats are different and in India, the standard English
US keyboard format is used.
Raspberry Pi configurations can also be done through the use of the
terminal by using CLI.
On the terminal we type:
sudo raspi-config
This command gives us a screen like the windows boot settings and can be
used to configure the Raspberry Pi as needed.
Some Basic Linux Commands
RaspberryPi Webcam Using Motion
The RaspberryPi that we use, either a 3B or a 3B+, both consist of 4 USB ports and
supports the usage of a webcam connected to the USB ports available on the pi.
For this we use a software called “Motion”. This is to be installed through the
terminal onto the Pi.
Configuring Motion
To check if the camera is properly connected to the raspberry pi, we look for a file
named Video0 in the /home/pi/dev folder. If the file is present then that means
that motion is up and running.
We now navigate to the folder /home/pi/etc/motion and edit the motion.config
file to get started.
Run motion on your device and the result should be displayed onto the web
browser or the local host as specified by the user.
Note: The motion config does not take the frame size more than 640x480 and any
size beyond that may result in no display or an error in the browser.
Note: By default the browsers on the windows desktop does not support
unauthorized ports to display information. This can be solved by going into the
about:config
After accepting the risks we get to the page shown above.
We need to create a new string with the IP Address and port that we have used in
the motion config file and hence enable an https request on that IP and port.
Just visiting the IP will gave us the results from the camera.
IPAddress:PORT This goes in the address bar (URL)
WinSCP
WinSCP is an open source free SFTP client, FTP client, WebDAV client, S3 client
and SCP client for Windows. Its main function is file transfer between a local and
a remote computer. Beyond this, WinSCP offers scripting and basic file manager
functionality.
Features
Graphical user interface (screenshots)
Translated into many languages
Integration with Windows (drag&drop, URL, shortcut icons, jump list)
All common operations with files
Support for SFTP and SCP
protocols over SSH and FTP and WebDAV and S3 protocols
Batch file scripting and command-line interface and .NET assembly for
advanced programming tasks
Directory synchronization in several semi or fully automatic ways
Integrated text editor
Shares site settings with PuTTY
Support for password, keyboard-interactive, public key and Kerberos
(GSS) authentication
Integrates with Pageant (PuTTY authentication agent) for full support
of public key authentication with SSH
Explorer and Commander interfaces
Optionally protects stored site information with master password
Optionally supports portable operation using a configuration file in place of
registry entries, suitable for operation from removable media
pwd
2) Change directory
cd
cd .
Using this command you will remain in the same directory you were.
4) Move me up one directory
cd ..
Above command will navigate two steps back from current directory
cd –
6) Go to Home folder
cd ~
7) Go to root
cd /
8) List files
ls
usage: ls [option] [file]
Example: ls /home.
ls -h
If you wish to see a directory’s contents with file sizes just type ls -h
ls -r
ls -is
ls -alh
cp
Example:
cp filename.php /home/filename.php
cp -r
This one is used to copy the entire folder with all it’s contents.
cp filename.php /home/filename2.php
mv
mv page.php /home/newpage.php
example: mv index.html/ ..
How to Create files/folders using Putty Commands
mkdir
Use the touch command to create different files and file extensions
Example: rm index.php
Example: rm * foldername
Thanks for reading our article and we will keep updating the same articles with
more useful commands in coming days. Keep checking this space for more
Putty commands.
apt-get update: Synchronizes the list of packages on your system to the list in
the repositories. Use it before installing new packages to make sure you are
installing the latest version.
of the software packages you have installed.
clear: Clears previously run commands and text from the terminal screen.
date: Prints the current date.
find / -name example.txt: Searches the whole system for the file example.txt
and outputs a list of all directories that contain the file.
nano example.txt: Opens the file example.txt in the Linux text editor Nano.
poweroff: To shutdown immediately.
raspi-config: Opens the configuration settings menu.
reboot: To reboot immediately.
shutdown -h now: To shutdown immediately.
shutdown -h 01:22: To shutdown at 1:22 AM.
startx: Opens the GUI (Graphical User Interface).
init 0: Shut down
Init 6: Restart
ls -l: Lists files in the current directory, along with file size, date modified,
and permissions.
mkdir example_directory: Creates a new directory named
example_directory inside the current directory.
ifconfig: To check the status of the wireless connection you are using (to
see if wlan0 has acquired an IP address).
ping: Tests connectivity between two devices connected on a network. For
example, ping 10.0.0.32 will send a packet to the device at IP 10.0.0.32 and wait
for a response. It also works with website addresses.
The Raspberry Pi can do a lot, especially now that the new Raspberry Pi comes
with wireless capabilities already on board. It can take the place of a ton of
different (and more expensive) devices – including a router! If you turn your
Raspberry Pi into a wireless access point, you can make it act as a router. It’s not
the most powerful thing in the world, but it does work, and the project is a lot of
fun.
We’re going to get into the command line a bit here, but this project isn’t really all
that difficult. All we’re really doing is using Raspbian and installing a couple
packages that give the Pi the ability to do router-like things like assign IP
addresses to devices that connect to it.
Check out our complete guide to installing Raspbian for the details on this
one. Then plug everything in and hop into the terminal and check for updates and
ugrades:
These are the two programs we’re going to use to make your Raspberry Pi into a
wireless access point. To get them, just type these lines into the terminal:
Both times, you’ll have to hit y to continue. hostapd is the package that lets us
create a wireless hotspot using a Raspberry Pi, and dnsmasq is an easy-to-use
DHCP and DNS server.
We’re going to edit the programs’ configuration files in a moment, so let’s turn the
programs off
before we start tinkering:
For our purposes here, I’m assuming that we’re using the standard home network
IP addresses, like 192.168.###.###. Given that assumption, let’s assign the IP
address 192.168.0.10 to the wlan0
interface by editing the dhcpcd configuration file. Start editing with this
command:
Now that you’re in the file, add the following lines at the end:
interface wlan0
static
ip_address=192.168.0.10/24
denyinterfaces eth0
(The last two lines are needed in order to make our bridge work –- but more on
that in
Step 8.)
After that, press Ctrl+X, then Y, then Enter to save the file and exit the editor.
Step 4: Configure the DHCP server (dnsmasq)
We’re going to use dnsmasq as our DHCP server. The idea of a DHCP server is to
dynamically distribute network configuration parameters, such as IP addresses,
for
interfaces and services.
You’ll be editing a new file now, and with the old one renamed, this is the config
file that dnsmasq will use. Type these lines into your new configuration file:
interface=wlan0
dhcp-range=192.168.0.11,192.168.0.30,255.255.255.0,24h
The lines we added mean that we’re going to provide IP addresses between
192.168.0.11 and 192.168.0.30 for the wlan0 interface.
Another config file! This time, we’re messing with the hostapd config file. Open ‘er
up:
interface=wlan0
bridge=br0
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_key_mgmt=WPA-
PSK wpa_pairwise=TKIP
rsn_pairwise=CCMP
ssid=NETWORK
wpa_passphrase=PASSWORD
Note that where I have “NETWORK” and “PASSWORD,” you should come up with
your own names. This is how you’ll join the Pi’s network from other devices.
We still have to show the system the location of the configuration file:
In this file, track down the line that says #DAEMON_CONF=”” – delete that # and
put the path to our config file in the quotes, so that it looks like this:
DAEMON_CONF="/etc/hostapd/hostapd.conf"
The # keeps the line from being read as code, so you’re basically bringing this line
to life here while giving it the right path to our config file.
The idea here is that when you connect to your Pi, it will forward the traffic over
your Ethernet cable. So we’re going to have wlan0 forward via Ethernet cable to
your modem. This involves editing yet another config file:
#net.ipv4.ip_forward=1
net.ipv4.ip_forward=1
Next, we’re going to add IP masquerading for outbound traffic on eth0 using
iptables:
To load the rule on boot, we need to edit the file /etc/rc.local and add the
following
line just above the line exit 0:
iptables-restore < /etc/iptables.ipv4.nat
Now the Raspberry Pi is acting as an access point to which other devices can
connect. However, those devices can’t use the Pi to access the internet just yet. To
make the possible, we need to build a bridge that will pass all traffic between the
wlan0 and eth0 interfaces.
auto br0
iface br0 inet manual
bridge_ports eth0
Step 9: Reboot
Now your Pi should be working as a wireless access point. Try it out by hopping
on another device and looking for the network name you used back in step 5.
PYTHON
Python is an easy to learn, powerful programming language. It has efficient high-
level data structures and a simple but effective approach to object-oriented
programming. Python’s elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and rapid application
development in many areas on most platforms.
The Python interpreter and the extensive standard library are freely available in
source or binary form for all major platforms from the Python Web
site, https://www.python.org/, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.
The Python interpreter is easily extended with new functions and data types
implemented in C or C++ (or other languages callable from C). Python is also
suitable as an extension language for customizable applications.
This tutorial introduces the reader informally to the basic concepts and features
of the Python language and system. It helps to have a Python interpreter handy
for hands-on experience, but all examples are self-contained, so the tutorial can
be read off-line as well.
For a description of standard objects and modules, see The Python Standard
Library. The Python Language Reference gives a more formal definition of the
language. To write extensions in C or C++, read Extending and Embedding the
Python Interpreter and Python/C API Reference Manual. There are also several
books covering Python in depth.
This tutorial does not attempt to be comprehensive and cover every single
feature, or even every commonly used feature. Instead, it introduces many of
Python’s most noteworthy features, and will give you a good idea of the
language’s flavor and style. After reading it, you will be able to read and write
Python modules and programs, and you will be ready to learn more about the
various Python library modules described in The Python Standard Library.
Python Versions:
The newer versions of python come with a variety of syntax changes along with
the inclusion and exclusion several libraries and functions. Python 2.7 supports
most of the inbuilt functions and libraries that have been made till date.
Python 3 on the other hand has trouble with compatibility of some libraries and
functions and those have to be rewritten in the Python 3 Script.
Python 2 Syntax
as comments
"""
####################################################
####################################################
# You have numbers
3 # => 3
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7
# automatically.
5 / 2 # => 2
# Result of integer division truncated down both for positive and negative.
5 // 3 # => 1
-5 // 3 # => -2
# Modulo operation
7 % 3 # => 1
2 ** 4 # => 16
(1 + 3) * 2 # => 8
# Boolean Operators
0 and 2 # => 0
-5 or 0 # => -5
# Equality is ==
1 == 1 # => True
2 == 1 # => False
# Inequality is !=
1 != 1 # => False
2 != 1 # => True
# More comparisons
"This is a string."
# ... or multiplied
# Even though the % string operator will be deprecated on Python 3.1 and
removed
x = 'apple'
y = 'lemon'
# None is an object
# - None
conditions # see:
https://docs.python.org/2/reference/datamodel.html#object. nonzero
# All other values are truthy (using the bool() function on them returns True).
####################################################
####################################################
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
input_string_var = raw_input(
input_var = input("Enter some data: ") # Evaluates the data as python code
some_var # => 5
li = []
other_li = [4, 5, 6]
li[0] # => 1
# Assign new values to indexes that have already been initialized with =
li[0] = 42
li[0] # => 42
li[-1] # => 3
# Looking out of bounds is an IndexError
li[::2] # =>[1, 4]
# li[start:end:step]
li.index(2) # => 1
1 in li # => True
len(li) # => 6
tup = (1, 2, 3)
tup[0] # => 1
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
g = 4, 5, 6 # => (4, 5, 6)
empty_dict = {}
filled_dict["one"] # => 1
filled_dict["four"] # KeyError
filled_dict.get("one") # => 1
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
# You can declare sets (which are like unordered lists that cannot contain
empty_set = set()
other_set = {3, 4, 5, 6}
####################################################
# 3. Control Flow
####################################################
# Let's just make a variable
some_var = 5
"""
prints:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
"""
"""
for i in range(4):
print i
"""
prints:
"""
print i
"""
prints:
1
2
"""
x=0
while x < 4:
print x
x += 1 # Shorthand for x = x + 1
try:
except IndexError as e:
else: # Optional clause to the try/except block. Must follow all except blocks
print "All good!" # Runs only if the code in try raises no exceptions
with open("myfile.txt") as f:
for line in f:
print line
####################################################
# 4. Functions
####################################################
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
def keyword_args(**kwargs):
return kwargs
print args
print kwargs
"""
(1, 2)
{"a": 3, "b": 4}
"""
args = (1, 2, 3, 4)
# you can pass args and kwargs along to other functions that take args/kwargs
all_the_args(*args, **kwargs)
print varargs(*args)
print keyword_args(**kwargs)
# Function Scope
x=5
def set_x(num):
x = num # => 43
print x # => 43
def set_global_x(num):
global x
print x # => 5
print x # => 6
set_x(43)
set_global_x(6)
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
####################################################
# 5. Classes
####################################################
class Human(object):
# Note that the double leading and trailing underscores denote objects
# or attributes that are used by python but that live in user-controlled
self.name = name
# Initialize property
self.age = 0
# They are called with the calling class as the first argument
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def grunt():
return "*grunt*"
@property
def age(self):
return self._age
@age.setter
self._age = age
@age.deleter
def age(self):
del self._age
# Instantiate a class
i = Human(name="Ian")
j = Human("Joel")
i.age = 42
i.age # => 42
del i.age
####################################################
# 6. Modules
####################################################
import math
import math as m
# can write your own, and import them. The name of the
# defines a module.
import math
dir(math)
####################################################
# 7. Advanced
####################################################
# Generators
# everything up front
# The following method (*NOT* a generator) will double all values and store it
def double_numbers(iterable):
double_arr = []
for i in iterable:
double_arr.append(i + i)
return double_arr
# Running the following would mean we'll double all values first and return all
print value
if value > 5:
break
# We could instead use a generator to "generate" the doubled value as the item
# is being requested
def double_numbers_generator(iterable):
for i in iterable:
yield i + i
# Running the same code as before, but with a generator, now allows us to iterate
# over the values and doubling them one by one as they are being consumed by
# our logic. Hence as soon as we see a value > 5, we break out of the
# loop and don't need to double most of the values sent in (MUCH FASTER!)
print value
if value > 5:
break
# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in
`test_generator`?
# `range` would return back and array with 1000000 values for us to use
# Just as you can create a list comprehension, you can create generator
# comprehensions as well.
for x in values:
gen_to_list = list(values)
# Decorators
# Simple usage example – add_apples decorator will add 'Apple' element into
def add_apples(func):
def get_fruits():
fruits = func()
fruits.append('Apple')
return fruits
return get_fruits
@add_apples
def get_fruits():
# Beg will call say. If say_please is True then it will change the returned
# message
def beg(target_function):
@wraps(target_function)
if say_please:
return msg
return wrapper
@beg
def say(say_please=False):
3. Move this file to a more permanent location, so that you can install Python
(and reinstall it easily later, if necessary).
4. Feel free to explore this webpage further; if you want to just continue the
installation, you can terminate the tab browsing this webpage.
5. Start the Installing instructions directly below.
Installing
1. Double-click the icon labeling the file python-3.6.2.exe.
An Open File - Security Warning pop-up window will appear.
2. Click Run.
A Python 3.6.2 (32-bit) Setup pop-up window will appear.
Ensure that the Install launcher for all users (recommended) and the Add Python
3.6 to PATH checkboxes at the bottom are checked.
If the Python Installer finds an earlier version of Python installed on your
computer, the Install Now message will instead appear as Upgrade Now (and the
checkboxes will not appear).
3. Highlight the Install Now (or Upgrade Now) message, and then click it.
A User Account Control pop-up window will appear, posing the question Do you
want the allow the following program to make changes to this computer?
1. Manual Installation:
The package is available from https://pypi.python.org/pypi/RPi.GPIO . There
will be a download button on the page as shown
NOTE: This above manual installation is only useful for the Ubuntu system and
is not applicable for the windows systems
Right click on this and copy the link address.
Further, in the terminal on the Raspberry Pi, paste the link address in the
following command to download the library-
wget link address
This downloads the RPi.GPIO-0.6.3.tar.gz file. Extract the tar file to a new
folder-
tar -zxvf RPi.GPIO-0.6.3.tar.gz
Browse to the new directory i.e. into the above folder by-
cd RPi.GPIO-0.6.3
and install the setup file-
sudo python setup.py install
o 2.Install from repository:
o If the package exists in the Raspbian repository is can be installed
using apt-get. First you need to update the available package
versions
:
sudo apt-get update
Then attempt to install the RPi.GPIO package :
apt-get install python-rpi.gpio
If it isn’t already installed it will be installed. If it is already installed it
will be upgraded if a newer version is available.
Usually now, the default Raspbian image include the RPi.GPIO library
but we would like to install a newer version to get access to newer API
for callbacks. This can be done by using-
sudo pip install --upgrade RPi.GPIO
Text Editors
For the windows systems we have a lot of text editors available that can be used
to write code and even compile the code.
Text editors have a load of capabilities and functions
Syntax Highlighting
Emmet
Auto Completion
Code Compilation
Error Detection
Auto include directories
Indentation
Some of the most popular Text editors are:
Sublime Text
Atom
VS Code (Visual Studio Code Editor)
Sublime Text 3
Some features our users love :
GOTO ANYTHING
Use Goto Anything to open files with only a few keystrokes, and instantly jump to symbols, lines
or words.
These shortcuts can be combined, so tp@rf may take you to a function read_file within a
file text_parser.py. Similarly, tp:100 would take you to line 100 of the same file.
GOTO DEFINITION
Using information from syntax definitions, Sublime Text automatically generates a project-wide
index of every class, method and function. This index powers Goto Definition, which is exposed
in three different ways:
Symbol indexing can be customized on a per-syntax basis via configuration files, allowing users
to tailor the feature to their needs.
MULTIPLE SELECTIONS
Make ten changes at the same time, not one change ten times. Multiple selections allow you to
interactively change many lines at once, rename variables with ease, and manipulate files faster
than ever.
Try pressing Ctrl + Shift + L to split the selection into lines and Ctrl + D to select the next
occurrence of the selected word. To make multiple selections with the mouse, take a look at
the Column Selectiondocumentation.
COMMAND PALETTE
The Command Palette holds infrequently used functionality, like sorting, changing the syntax
and changing the indentation settings. With just a few keystrokes, you can search for what you
want, without ever having to navigate through the menus or remember obscure key bindings.
CUSTOMIZE ANYTHING
Key bindings, menus, snippets, macros, completions and more - just about everything in
Sublime Text is customizable with simple JSON files. This system gives you flexibility as settings
can be specified on a per-file type and per-project basis.
SPLIT EDITING
Get the most out of your wide screen monitor with split editing support. Edit files side by side,
or edit two locations in the one file. You can edit with as many rows and columns as you wish.
Take advantage of multiple monitors by editing with multiple windows, and using multiple
splits in each window.
Take a look at the View Layout menu for split editing options. To open multiple views into
the one file, use the File New View into File menu item.
PERFORMANCE
Sublime Text is built from custom components, providing for unmatched responsiveness. From
a powerful, custom cross-platform UI toolkit, to an unmatched syntax highlighting engine,
Sublime Text sets the bar for performance.
CROSS PLATFORM
Sublime Text is available for Mac, Windows and Linux. One license is all you need to use
Sublime Text on every computer you own, no matter what operating system it uses.
Sublime Text uses a custom UI toolkit, optimized for speed and beauty, while taking advantage
of native functionality on each platform.
ATOM
Create new branches, stage and commit, push and pull, resolve merge conflicts,
view pull requests and more—all from within your editor. The GitHub package is
already bundled with Atom, so you're ready to go!
Smart autocompletion
Atom helps you write code faster with a smart and flexible autocomplete.
File system browser
Easily browse and open a single file, a whole project, or multiple projects in one
window.
Multiple panes
Split your Atom interface into multiple panes to compare and edit code across
files.
Find and replace
Find, preview, and replace text as you type in a file or across all your projects.
VS Code
Getting Started
Visual Studio Code is a lightweight but powerful source code editor which runs on
your desktop and is available for Windows, macOS and Linux. It comes with built-
in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of
extensions for other languages (such as C++, C#, Java, Python, PHP, Go) and
runtimes (such as .NET and Unity). Begin your journey with VS Code with
these introductory videos.
First Steps
To get the most out of Visual Studio Code, start by reviewing a few introductory
topics:
Intro Videos - Begin your journey with VS Code through these introductory
videos.
Setup - Install VS Code for your platform and configure the tool set for your
development needs.
User Interface - Introduction to the basic UI, commands, and features of the VS
Code editor.
Settings - Customize VS Code for how you like to work.
Languages - Learn about VS Code's support for your favorite programming
languages.
Node.js - This tutorial gets you quickly running and debugging a Node.js web app.
Tips and Tricks - Jump right in with Tips and Tricks to become a VS Code power
user.
Azure - VS Code is great for deploying your web applications to the cloud.
Extension API - Learn how to write a VS Code extension.
Why VS Code? - Read about the design philosophy and architecture of VS Code.
Keyboard Shortcuts
Increase your productivity with VS Code's keyboard shortcuts.
Keyboard Shortcut Reference Sheet - Learn the commonly used keyboard
shortcuts.
Keymap Extensions - Change VS Code's keyboard shortcuts to match another
editor.
Customize Keyboard Shortcuts - Modify the default keyboard shortcuts.
Connections On Raspberry Pi
The Raspberry Pi consists of a 40 pin SPI controller. This can be used to control
several devices and sensors that we may need to use during a project or any
general task performed with the Pi.
This Pins are of different types:
GPIO (General Purpose Input Output)
SPI (Serial Peripheral Interface)
I2C (Inter-Integrated Circuits)
UART (Universal Asynchronous Receiver/Transmitter)
One Wire
GROUND
VCC (3V3 or 5V) [3V3 means 3.3V]
For additional purposes we connect our pi to the Netmaxiot Shield using:
Raspberry Pi Pinout Diagram
Introduction to GPIO
A powerful feature of the Raspberry Pi is the row of GPIO (general-purpose
input/output) pins along the top edge of the board. A 40-pin GPIO header is found
on all current Raspberry Pi boards (unpopulated on Pi Zero and Pi Zero W). Prior
to the Pi 1 Model B+ (2014), boards comprised a shorter 26-pin header.
Any of the GPIO pins can be designated (in software) as an input or output pin
and used for a wide range of purposes.
Note: the numbering of the GPIO pins is not in numerical order; GPIO pins 0 and
1 are present on the board (physical pins 27 and 28) but are reserved for
advanced use (see below).
Voltages
Two 5V pins and two 3V3 pins are present on the board, as well as a number of
ground pins (0V), which are not configurable. The remaining pins are all general
purpose 3V3 pins, meaning outputs are set to 3V3 and inputs are 3V3-tolerant.
Outputs
A GPIO pin designated as an output pin can be set to high (3V3) or low (0V).
Inputs
A GPIO pin designated as an input pin can be read as high (3V3) or low (0V). This
is made easier with the use of internal pull-up or pull-down resistors. Pins
GPIO2
and GPIO3 have fixed pull-up resistors, but for other pins this can be configured
in software.
MOSI MISO
P1-19
SCLKP1-21
GND P1-23P1-24
P1-25P1-26
CE0
CE1
Software
WiringPi
WiringPi includes a library which can make it easier to use the Raspberry Pi's on-
board SPI interface. Accesses the hardware registers directly.
http://wiringpi.com/
bcm2835 library
This is a C library for Raspberry Pi (RPi). It provides access to GPIO and other IO
functions on the Broadcom BCM 2835 chip. Accesses the hardware registers
directly.
http://www.airspayce.com/mikem/bcm2835/
Use spidev from C
There's a loopback test program in the Linux documentation that can be used as a
starting point. See the Troubleshooting section. Uses the Linux spidev driver to
access the bus.
Shell
Hardware
The BCM2835 on the Raspberry Pi has 3 SPI Controllers. Only the SPI0 controller
is available on the header. Chapter 10 in the BCM2835 ARM Peripherals datasheet
describes this controller.
Master modes
Signal name abbreviations
Standard mode
In Standard SPI master mode the peripheral implements the standard 3 wire
serial protocol (SCLK, MOSI and MISO).
Bidirectional mode
In bidirectional SPI master mode the same SPI standard is implemented, except
that a single wire is used for data (MOMI) instead of the two used in standard
mode (MISO and MOSI). In this mode, the MOSI pin serves as MOMI pin.
LoSSI mode (Low Speed Serial Interface)
The LoSSI standard allows issuing of commands to peripherals (LCD) and to
transfer data to and from them. LoSSI commands and parameters are 8 bits long,
but an extra bit is used to indicate whether the byte is a command or
parameter/data. This extra bit is set high for a data and low for a command. The
resulting 9-bit value is serialized to the output. LoSSI is commonly used with MIPI
DBI type C compatible LCD controllers.
Note:
Some commands trigger an automatic read by the SPI controller, so this mode
can't be used as a multipurpose 9-bit SPI.
Transfer modes
Polled
Interrupt
DMA
Speed
The CDIV (Clock Divider) field of the CLK register sets the SPI clock speed:
cdiv speed
2 125.0 MHz
4 62.5 MHz
8 31.2 MHz
16 15.6 MHz
32 7.8 MHz
64 3.9 MHz
128 1953 kHz
256 976 kHz
512 488 kHz
1024 244 kHz
2048 122 kHz
4096 61 kHz
8192 30.5 kHz
16384 15.2 kHz
32768 7629 Hz
When asking for say 24 MHz, the actual speed will be 15.6 MHz.
Forum post: SPI has more speeds
Supported Mode bits
wget https://raw.githubusercontent.com/raspberrypi/linux/rpi-
3.10.y/Documentation/spi/spidev_test.c
./spidev_test -D /dev/spidev0.0
spi mode: 0
FF FF FF FF FF
FF 40 00 00 00
00 95 FF FF FF
FF FF FF FF FF
FF FF FF FF FF
FF FF FF FF FF
DE AD BE EF BA
AD
Raspberry Pi PWM
Raspberry Pi has two PWM channels i.e. PWM0 and PWM1.
PWM pins for the two PWM channels on 40-pin P1 header are as follows:
GPIO12 PWM0
GPIO18 PWM0
GPIO13 PWM1
GPIO19 PWM1
The PWM pins on Raspberry Pi 40-pin P1Header is shown in below figure,
GPIO.setup(ledpin,GPIO.OUT)
pi_pwm = GPIO.PWM(ledpin,1000)
#create PWM instance with frequency
pi_pwm.start(0) #start PWM of required Duty Cycle
while True:
for duty in range(0,101,1):
pi_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 0-100
sleep(0.01) sleep(0.5)
○ GPIO.setwarnings(False)
Sometimes, when the GPIO pins, which we are trying to use, might be doing some
other functions. In that case, we will receive warnings while executing the
program. Below command tells the PI to ignore the warnings and proceed with
the program.
○ GPIO.setmode (GPIO.BCM)
We can refer the GPIO pins of PI, either by pin number on board or by their
function number. In pin diagram, you can see ‘PIN 35’ on the board is ‘GPIO 19’.
So we tell here either we are going to represent the pin here by ‘35’ or ‘19’.
○ GPIO.setup(19,GPIO.IN)
We can set the GPIO pins as input or output pins using setup command. As
shown below we are setting GPIO 19 (or PIN 35) as output pin. We will get PWM
output from this pin.
○ While 1
It is used for infinity loop. With this command the statements inside this loop will
be executed continuously.
1. import RPi.GPIO as GPIO # import RPi.GPIO module
2. GPIO.setmode(GPIO.BCM) # choose BCM or BOARD
3. GPIO.setup(port_or_pin, GPIO.IN) # set a port/pin as an input
4. GPIO.setup(port_or_pin, GPIO.OUT) # set a port/pin as an output
5. GPIO.output(port_or_pin, 1) # set an output port/pin value to 1/HIGH/True
6. GPIO.output(port_or_pin, 0) # set an output port/pin value to 0/LOW/False
7. i = GPIO.input(port_or_pin) # read status of pin/port and assign to variable i
Programs:
The above is a simple hello world program and prints “Hello World” onto the console.
The above program gives a code for blinking the led bulbs present on the
Netmaxiot Shield using the Pi.
The pins GPIO 17, 27, 22 corresponding to the pin numbers 11, 13, 15 of the
Raspberry Pi are set as outputs for the LED’s and a python code is used to
implement the given blinking effect.
Rest of the programs are available at:
https://github.com/AdityaSA99/IoT-Programs
Sensors
Some of the major sensors used in the IoT projects include:
DHT 11
DHT 22
DS18B20
LM 35
LDR
DHT 11
This DHT11 Temperature and Humidity Sensor features a calibrated digital signal
output with the temperature and humidity sensor capability. It is integrated with
a high-performance 8-bit microcontroller. Its technology ensures the high
reliability and excellent long-term stability. This sensor includes a resistive
element and a sensor for wet NTC temperature measuring devices. It has
excellent quality, fast response, anti-interference ability and high performance.
Each DHT11 sensors features extremely accurate calibration of humidity
calibration chamber. The calibration coefficients stored in the OTP program
memory, internal sensors detect signals in the process, we should call these
calibration coefficients. The single-wire serial interface system is integrated to
become quick and easy. Small size, low power, signal transmission distance up to
20 meters, enabling a variety of applications and even the most demanding ones.
The product is 4-pin single row pin package. Convenient connection, special
packages can be provided according to users need.
Specification
Supply Voltage: +5 V
Temperature range :0-50 °C error of ± 2 °C
Humidity :20-90% RH ± 5% RH error
Interface: Digital
Many low cost sensors have unusual output formats, and in this case, a
"Manchester-esque" output that is not SPI, I2C or 1-Wire compatible must
be polled continuously. Please refer to data sheet below
DHT 11 Sensors have a lower precision range and usually only give Whole
number values.
The three pins on the DHT 11 from the left are:
Ground
Output
VCC
DHT 22
The DHT22 is a basic, low-cost digital temperature and humidity sensor. It uses a
capacitive humidity sensor and a thermistor to measure the surrounding air, and
spits out a digital signal on the data pin (no analog input pins needed).
Simply connect the first pin on the left to 3-5V power, the second pin to your data
input pin and the right most pin to ground. Although it uses a single-wire to send
data it is not Dallas One Wire compatible! If you want multiple sensors, each one
must have its own data pin.
Compared to the DHT11, this sensor is more precise, more accurate and works in
a bigger range of temperature/humidity, but it’s larger and more expensive.
Comes with a 4.7K - 10K resistor, which you will want to use as a pull-up from the
data pin to VCC.
Product Details:
The pull-up resistor is used to keep the line in high state when the bus is not in
use. The temperature value measured by the sensor will be stored in a 2-byte
register inside the sensor. This data can be read by the using the 1- wire method
by sending in a sequence of data. There are two types of commands that are to be
sent to read the values, one is a ROM command and the other is function
command. The address value of each ROM memory along with the sequence is
given in the datasheet below. You have to read through it to understand how to
communicate with the sensor.
If you are planning to interface it with Arduino or Raspberry Pi or even a
Node MCU, then you need not worry about all these. You can develop the readily
available library and use the in-built functions to access the data.
Applications
LM35
The LM35 datasheet specifies that this ICs are precision integrated-circuit
temperature sensors, whose output voltage is linearly proportional to the Celsius
(Centigrade) temperature.
The LM35 thus has an advantage over linear temperature sensors calibrated in ˚
Kelvin, as the user is not required to subtract a large constant voltage from its
output to obtain convenient Centi-grade scaling. The LM35 does not require any
external calibration or trimming to provide typical accuracies of ±1⁄4˚C at room
temperature and ±3⁄4˚C over a full −55 to +150˚C temperature range.
LM35 datasheet
LM35 Features
Calibrated directly in o Celsius (Centigrade)
Linear + 10.0 mV/oC scale factor
0.5oC accuracy guaranteeable (at +25oC)
Rated for full −55o to +150oC range
Suitable for remote applications
Low cost due to wafer-level trimming
Operates from 4 to 30 volts
Less than 60 µA current drain
Low self-heating, 0.08oC in still air
Nonlinearity only ±1⁄4oC typical
Low impedance output, 0.1 Ω for 1 mA load
LDR
A Light Dependent Resistor (LDR) is also called a photoresistor or a cadmium
sulfide (CdS) cell. It is also called a photoconductor. It is basically a photocell that
works on the principle of photoconductivity. The passive component is basically a
resistor whose resistance value decreases when the intensity of light decreases.
This optoelectronic device is mostly used in light varying sensor circuit, and light
and dark activated switching circuits. Some of its applications include camera
light meters, street lights, clock radios, light beam alarms, reflective smoke
alarms, and outdoor clocks.
Some projects with the application of LDR is listed below.
Automatic Street Light Circuit
Simple Fire Alarm Circuit
Light Activated Switch Circuit
Automatic LED Emergency Light
Night Security Light
LDR Structure and Working
The basic structure of an LDR is shown below.
The snake like track shown below is the Cadmium Sulphide (CdS) film which also
passes through the sides. On the top and bottom are metal films which are
connected to the terminal leads. It is designed in such a way as to provide
maximum possible contact area with the two metal films. The structure is housed
in a clear plastic or resin case, to provide free access to external light. As
explained above, the main component for the construction of LDR is cadmium
sulphide (CdS), which is used as the photoconductor and contains no or very few
electrons when not illuminated. In the absence of light it is designed to have a
high resistance inthe range of megaohms. As soon as light falls on the sensor, the
electrons are liberated and the conductivity of the material increases. When the
light intensity exceeds a certain frequency, the photons absorbed by the
semiconductor give band electrons the energy required to jump into the
conduction band. This causes the free electrons or holes to conduct electricity and
thus dropping the resistance dramatically (< 1 Kiloohm).
The equation to show the relation between resistance and illumination can be
written as
R = A.E^a
where E – Illumination (lux)
R – Resistance (Ohms)
A,a – constants
The value of ‘a’ depends on the CdS used and on the manufacturing process.
Values usually range betwee 0.7 and 0.9.
Advantages
LDR’s are cheap and are readily available in many sizes and shapes. Practical
LDRs are available in a variety of sizes and package styles, the most popular size
having a face diameter of roughly 10 mm. They need very small power and
voltage for its operation.
Disadvantages
Highly inaccurate with a response time of about tens or hundreds of milliseconds.
Cloud Services
There are a variety of cloud services available to track and display our data. Some
of them are:
Google API (Used with Spreadsheet as a cloud)
UBI Dots
Adafruit
ThingSpeak
Tamboo
Google API
Navigate to the page https://console.developers.google.com
Here we are given with an option to create a Google API.
This API helps us in the creating credentials to send data over the net from
the Raspberry Pi or the Node MCU.
This dialogue box appears, notifying us that the project has been
successfully created.
We next use the Credentials option to create credentials for our device. We
use the Service Account Key for this purpose and authenticate it.
For the credentials, choose the third option of Service Account Key and
continue.
On choosing the Service Account Key, we get the chance to create a new
service account that serves as an access point for our device.
We create a JSON file that contains all information regarding the credentials
and the ID of the new service account. This is used as authentication in
further steps.
We give a account name and set it as a the project owner (All permissions)
This bit of code represents that Authentication of the code with the google
API. We get the credentials from the JSON file that we have created and use
it to share the Google spreadsheet with the given E-Mail address that we
have designated.
The function above, sends the API Authentication Key and the Name of the
Spreadsheet as parameters and further authenticates the spreadsheet for
access by the device. Once this step is done, data can be sent.
UBI Dots
UBI Dot is a data cloud that can be used to store and retrieve data from our
IoT devices.
App.ubidots.com is the site that we use and this is for educational purposes.
The official site is for industrial applications.
On login we get to the dashboard that contains all the widgets that we
create using the variables that we receive from the device. On the top right
we get credits. By default we receive 5000 credits for our account and these
can be used to use the UBI Dots services.
Coming back to the dashboard, we get the options to make widgets that can
be used to represent and monitor the data that we send. It may be in the
form of a Chart or Indicator etc.
We select the type of indicator most suitable for representing our data. In
this case we go for a Gauge.
After selection we select the device from which the data is to be taken. Here
we take the data from the Node MCU ESP8266.
Finally as for the Gauge we require a Minimum and Maximum value, we put
those and finish. We see the widget displayed on the main dashboard and
the values can be easily read through it in real time with a max delay of a
few seconds depending on the Internet Speeds.
Above given is the code for the authentication of the UBI Dots website. We
use the request library to send a request to the UBI Dots Server to grant
permission to our device to Access it. We use our API Key for this purpose.
For sending the data we create a function by any name and write a payload
function in order to create the variables and assign the values to them. This
payload is then returned as a value from the function and we can use these
to create the widgets in the dashboard of the UBI Dots.
Adafruit IO
Adafruit IO is one of the most popular clouds for IoT Services. The website can be
accessed from the URL:
https://www.io.adafruit.com
Triggers are used to automate the events that take place in the cloud. For
example if we have a water tank and we are monitoring the level of water.
We can create the trigger to turn off the water pump once the tank is full
and turn on the water supply when the water level falls below 10% of the
tank capacity.
The AIO keys are used to authenticate the user and the program. We give
the AIO login in the program in order to authenticate when the program
tries to communicate with the cloud over the internet.
This shows the final result in the dashboard of the cloud along with two
widgets that are used to control the functions of light and fan for this case
and the code screen shows the backend process.
Particle IO
Particle is another cloud that can be installed into the raspberry pi and can
control all of the required things from the GUI on the website.
After login we go to console. Initially we find the screen empty and used the
following codes to install particle onto the Raspberry Pi and create a device
through it.
We run the command on line one if we want to use the terminal to pass
commands to the particle cloud.
The second command installs the particle for Pi and enables us to use the
services of the particle cloud GUI from the Particle website.
We create a device and obtain a screen as shown above. This gives us the
device ID, The type and the name of the device as given by the user. For a
Raspberry Pi the default name given is pi.
There is a small grey icon displayed beside the device id represents the
status of the device.
o Grey Inactive
o Blinking Blue Active
Particle provides the user with a web interface for programming with a few
built in programs. This allows the user to write and flash the code without
the use of any third party software like WinSCP or Terminal or Text Editors.
Through particle we can also write code that can be run through the use of
a web page. Using the curl command given in the first screen shot we
generate the access token and keys this is given to the html code to interact
with the particle account specified and finally uses the code in html and the
Particle GUI to interact with devices. In this case LEDs present on the
Raspberry Pi.
ThingSpeak
For new IoT Software there is another cloud introduced. This is known as
ThingSpeak. This platform performs the same functions as the other cloud
services with the added advantage of a simpler interface and customization
options.
The above shows the creation of a channel and the variables of the channel.
This channel contains 3 variables Temperature, Humidity and Analog Noise
and the data of all three can be represented and monitored on the cloud.
IFTTT
IFTTT is a cloud service that can be used to collect data from other cloud
services.
Now on Preference window, Enter below link in Additional Boards Manager URLs
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Now close Preference window and go to Tools -> Board -> Boards Manager
In Boards Manager window, Type esp in the search box, esp8266 will be listed
there below. Now select latest version of board and click on install.
After installation of the board is complete, open Tools->Board->and select
NodeMCU 1.0(ESP-12E Module).
Now Your Arduino IDE is ready for NodeMCU
Example
Let’s see how to write simple serial print sketch using Arduino IDE for NodeMCU.
First connect NodeMCU Development Kit with PC as shown in below figure.
void loop()
{
Serial.println("ElectronicWings"); /* print Electronic Wings at new line per
second */
delay(1000);
}
Ensure that you have selected the correct board as shown in below figure.
Also make sure that you have selected the appropriate COM port.
Now compile & upload the written sketch directly to the NodeMCU Dev Kit by
clicking on upload button.
Now Click on Serial Monitor (upper right corner) option to check output on serial
monitor window of Arduino IDE.
Serial monitor output window will pop up with output as shown in below figure.
NodeMCU GPIO with Arduino IDE
General-purpose input/output (GPIO) is a pin on an IC (Integrated Circuit). It can
be either input pin or output pin, whose behavior can be controlled at the run
time.
NodeMCU Development kit provides access to these GPIOs of ESP8266. The only
thing to take care is that NodeMCU Dev kit pins are numbered differently than
internal GPIO notations of ESP8266 as shown in below figure and table. For
example, the D0 pin on the NodeMCU Dev kit is mapped to the internal GPIO pin
16 of ESP8266.
The GPIO’s shown in blue box (1, 3, 9, 10) are mostly not used for GPIO
purpose on Dev Kit
ESP8266 is a system on a chip (SoC) design with components like the processor
chip. The processor has around 16 GPIO lines, some of which are used internally
to interface with other components of the SoC, like flash memory.
Since several lines are used internally within the ESP8266 SoC, we have about 11
GPIO pins remaining for GPIO purpose.
Now again 2 pins out of 11 are generally reserved for RX and TX in order to
communicate with a host PC from which compiled object code is
downloaded.
Hence finally, this leaves just 9 general purpose I/O pins i.e. D0 to D8.
As shown in above figure of NodeMCU Dev Kit. We can see RX, TX, SD2, SD3 pins
are not mostly used as GPIOs since they are used for other internal process. But
we can try with SD3 (D12) pin which mostly like to respond for
GPIO/PWM/interrupt like functions.
Note that D0/GPIO16 pin can be only used as GPIO read/write, no special
functions are supported on it.
Example
Let’s write an Arduino sketch for LED blinking on pin D4 of NodeMCU Dev Kit.
Arduino Sketch for LED Blink
uint8_t LED_Pin = D4; // declare LED pin on NodeMCU Dev Kit
void setup() {
pinMode(LED_Pin, OUTPUT); // Initialize the LED pin as an output
}
void loop() {
digitalWrite(LED_Pin, LOW); // Turn the LED on
E.g. A pulse with a period of 10ms will remain ON (high) for 2ms.Therefore, duty
cycle will be
D = 2ms / 10ms = 20%
Through PWM technique, we can control the power delivered to the load by using
ON-OFF signal. The PWM signals can be used to control the speed of DC motors
and to change the intensity of the LED. Moreover, it can also be used to generate
sine signals. Pulse Width Modulated signals with different duty cycle are shown
below.
PWM Duty cycle
NodeMCU based ESP8266 has the functionality of PWM interfaces via software
programming. It is achieved with the timer interruption method. PWM frequency
range for ESP8266 is adjustable up to 1KHz.
PWM pins on NodeMCU Kit
void setup(){
Serial.begin(9600);
analogWrite(LEDpin, 512); /* set initial 50% duty cycle */
}
void loop(){
uint16_t dutycycle = analogRead(A0); /* read continuous POT and set PWM
duty cycle according */
if(dutycycle > 1023) dutycycle = 1023;/* limit dutycycle to 1023 if POT read
cross it */
Serial.print("Duty Cycle: "); Serial.println(dutycycle);
analogWrite(LEDpin, dutycycle);
delay(100);
}
Example
Let’s write Arduino sketch of SPI communication for NodeMCU. Here NodeMCU is
acting as master device and we are using Arduino uno as slave device.
In this example, we are sending “Hello Slave” string with ‘\n’ as ending of string
from NodeMCU Master device. Slave device receives this string and prints it on
serial monitor.
void setup() {
Serial.begin(9600); /* begin serial with 9600 baud */
SPI.begin(); /* begin SPI */
}
void loop() {
for(inti=0; i<sizeof buff; i++) /* transfer buff data per second */
SPI.transfer(buff[i]);
delay(1000);
}
Master mode
Slave mode
SDA (serial data) wire is used for data exchange in between master and slave
device. SCL (serial clock) is used for the synchronous clock in between master and
slave device.
Master device initiates communication with a slave device. Master device
requires slave device address to initiate conversation with a slave device. Slave
device responds to master device when it is addressed by a master device.
NodeMCU has I2C functionality support on its GPIO pins. Due to internal
functionality on ESP-12E, we cannot use all its GPIOs for I2C functionality. So, do
tests before using any GPIO for I2C applications.
Example
Let’s write Arduino sketch for NodeMCU as I2C master device and Arduino sketch
for Arduino Uno as I2C slave device. Master device sends hello string to slave
device and slave device will send hello string in response to the master device.
Here, we are using
Master Device: NodeMCU
Slave Device: Arduino Uno
Slave Device Address: 8
Interfacing diagram is shown in below figure
void setup() {
Serial.begin(9600); /* begin serial for debug */
Wire.begin(D1, D2); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}
void loop() {
Wire.beginTransmission(8); /* begin with device address 8 */
Wire.write("Hello Arduino"); /* sends hello string */
Wire.endTransmission(); /* stop transmitting */
void setup() {
Wire.begin(8);
/* join i2c bus with address 8 */
Wire.onReceive(receiveEvent); /* register receive event */
Wire.onRequest(requestEvent); /* register request event */
void loop() {
delay(100);
}
// function that executes whenever data is received from master void receiveEvent(int ho
while (0 <Wire.available()) {
char c = Wire.read();/* receive byte as a character */
// function that executes whenever data is requested from master void requestEvent() {
Wire.write("Hello NodeMCU"); /*send string on request */
}
Output Window
Output window of serial monitor at Slave device (Arduino Uno)
Channel ID is = 309236
Write Key is = 1EYZIS5OCRJSKZHG
Note: Do not forget to tick the Make Public field in channel setting option on your
thingspeak channel.
#include <ESP8266WiFi.h>
WiFiClient client;
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("Connecting to ");
Serial.println(ssid);
void loop()
{
if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
{
String getStr = _getLink;
client.print("GET "+getStr+"\n");
client.print("HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n\n\n");
while(client.available()){
char c = client.read();
Serial.print(c);
}
Serial.println("");
}
client.stop();
Serial.println("Waiting…");
delay(10000);
}
#include <ESP8266WiFi.h>
WiFiClient client;
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("Connecting to ");
Serial.println(ssid);
void loop()
{
if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
{
String postStr = apiKey;
postStr +="&field1=";
postStr += String(Sample++);
postStr += "\r\n\r\n";
delay(20000);
}
Example
Let’s write Arduino Sketch to enable NodeMCU as HTTP server with Wi-Fi
STA/AP mode and control an LED connected at server side from client side.
Here we have connected LED to the pin no. 2 i.e. D2 pin on NodeMCU board as
shown in below figure.
HTML page for client
As we are making HTTP server for LED on/off functionality, we are going to make
simple HTML page which will be visible at client side and able to take user input
for LED on/off. It is user friendly representation of button input which takes input
from user on click.
We need to write two HTML pages for LED ON and LED OFF state i.e. when client
clicks the LED ON button, then in next action we need to provide option for LED
OFF. Below are the two HTML code snippets for LED ON and LED OFF state
presentation.
<!DOCTYPE html>
<html>
<head><title>LED Control</title></head>
<body>
<h1>LED</h1>
<p>Click to switch LED on and off.</p>
<form method="get">
<input type="button" value="LED ON" onclick="window.location.href='/ledon'">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head><title>LED Control</title></head>
<body>
<h1>LED</h1>
<p>Click to switch LED on and off.</p>
<form method="get">
<input type="button" value="LED OFF" onclick="window.location.href='/ledoff'">
</form>
</body>
</html>
From above two HTML snippets we can see that only forms are different for LED
ON and LED OFF state.
Let’s have a look at HTML lines
<!DOCTYPE html>: This declaration defines that document as an HTML and
helps browsers to display web pages correctly. It must only appear once, at the
top of the page.
<html>: This element is the root element of an HTML page
<head>: This element contains meta information about the document
<title>: This element specifies a title for the document
<body>: This element contains the visible page content i.e. body of document
<h1>: This element defines the largest font size for heading. Similarly, we can use
<h2>/<h3>and so on for smaller font sizes of the header.
<p>: This element defines a paragraph.
<form>: This element defines a form that is used to collect user input
window.location.href : This is a property that will tell us the current URL
location. Changing the value of the property will redirect the page.
e.g.window.location.href='/ledon' will redirect the current page to the
URL current_url/ledon page. If current location is http://192.168.0.1 then it will
redirect to http://192.168.0.1/ledon page. Page redirect action is taken on click
event (e.g. click on button).
Here we are using above mentioned concept (page redirect) to redirect the client
from LED ON page to LED OFF page and vice versa.
To learn more about HTML refer https://www.w3schools.com/html/default.asp
Now we can send above HTML snippets when client connects to the server and
also when client clicks on button.
Program
In Wi-Fi Access Point (AP) mode, NodeMCU creates server hence we can set its IP
address, IP subnet mask and IP gateway.
Let’s take below SSID, Password to join network and addresses for AP mode
SSID = “NodeMCU”
Password = “12345678”
IP = "192.168.2.1"
Sub netmask = "255.255.255.0"
Gateway = "192.168.2.1"
#include <ESP8266WiFi.h>
#include
<ESP8266WebServer.h>
void setup() {
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
delay(100);
server.on("/", handle_OnConnect);
server.on("/ledon", handle_ledon);
server.on("/ledoff", handle_ledoff);
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(LEDstatus)
digitalWrite(LEDpin, HIGH);
else
digitalWrite(LEDpin, LOW);
}
void handle_OnConnect() {
LEDstatus = LOW;
server.send(200, "text/html", SendHTML(false));
}
void handle_ledon() {
LEDstatus = HIGH;
server.send(200, "text/html", SendHTML(true));
}
void handle_ledoff() {
LEDstatus = LOW;
server.send(200, "text/html", SendHTML(false));
}
void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}
Note: After successful uploading of above sketch client needs to connect to the
network created by NodeMCU first.
After connecting to NodeMCU network from wifi enter the server address in
browser i.e. http://server_ip_address e.g. in our case it is http://192.168.2.1.
After press Enter key we can see the HTML page response from server as shown
in below image. Now just click the button to change the state of LED.
Now, let’s do the HTTP server to NodeMCU using Wi-Fi station mode.
In Wi-Fi Station (STA) mode, NodeMCU gets IP addresses from Wi-Fi router
(access point). If we are also in same network then we can directly connect to
NodeMCU HTTP Server using IP address only.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
void setup() {
Serial.begin(9600);
delay(100);
pinMode(LEDpin, OUTPUT);
Serial.println("Connecting to ");
Serial.println(ssid);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(LEDstatus)
digitalWrite(LEDpin, HIGH);
else
digitalWrite(LEDpin, LOW);
}
void handle_OnConnect() {
LEDstatus = LOW;
server.send(200, "text/html", SendHTML(false));
}
void handle_ledon() {
LEDstatus = HIGH;
server.send(200, "text/html", SendHTML(true));
}
void handle_ledoff() {
LEDstatus = LOW;
server.send(200, "text/html", SendHTML(false));
}
void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}
Note: in wi-fi station mode we need to enter the ssid and password of existing
network. After connecting to WiFi network enter the server address in browser
i.e. http://assigned_ip_address. After pressing Enter key we can see the HTML page
response from server in the browser as shown above for AP mode
NodeMCU MQTT Client with Arduino IDE
MQTT is lightweight publish-subscribe based messaging protocol.
Example
Let’s write Arduino program to configure NodeMCU as MQTT Client to
Here we are using Adafruit server for MQTT Client demo purpose.
In IOT platform, Adafruit IO Dashboard allow us to visualize and provides control
over connected device to internet. Anyone can visualize and analyse live data
from their sensor devices. To learn more and start with Adafruit IO Dashboard
refer link https://learn.adafruit.com/adafruit-io-basics-dashboards/creating-a-
dashboard
Just sign up and create dashboard. After successful creating of dashboard we will
get AIO key which is later used to access feed data.
Once we created dashboard on Adafruit we can add various blocks that can be
used to control devices as well as monitor status of devices. To see more about
blocks, refer link https://learn.adafruit.com/adafruit-io-basics-
dashboards/adding-blocks
POT and LED connection to NodeMCU
Open the Arduino IDE and navigate to Sketch -> Include Library -> Manage
Libraries…
Library Manager window will pop up. Now enter Adafruit IO Arduino into the
search box, and click Install on the Adafruit IO Arduino library option to install
version 2.6.0 or higher.
Now enter Adafruit MQTT into the search box, and click Install on the Adafruit
MQTT libraryoption to install version 0.17.0 or higher.
Now enter Arduino Http Client into the search box, and click Install on
the ArduinoHttpClientlibrary option to install version 0.3.0 or higher.
Now open example of Adafruit mqtt io dashboard. To open it navigate to File ->
Examples -> Adafruit MQTT Library -> mqtt_esp8266
Now edit the wifi and Adafruit io credentials with correct information of example
as shown in below image.
We have modified mqtt_esp8266 example as per our above example as below
// Setup the MQTT client class by passing in the WiFi client and MQTT server and
login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERN
AME, AIO_KEY);
void setup() {
Serial.begin(9600);
delay(10);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_
connect
// function definition further below.
MQTT_connect();
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(200))) {
if (subscription == &ledBrightness) {
Serial.print(F("Got LED Brightness : "));
ledBrightValue = atoi((char *)ledBrightness.lastread);
Serial.println(ledBrightValue);
analogWrite(ledPin, ledBrightValue);
}
}
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}