0% found this document useful (0 votes)
117 views

NetMax IoT Report - Aditya

The document discusses the different generations of Raspberry Pi models and provides details about their specifications. It also describes how to install an operating system like Raspbian onto the Raspberry Pi using NOOBS and provides instructions for formatting an SD card and copying the NOOBS files.

Uploaded by

Avneet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

NetMax IoT Report - Aditya

The document discusses the different generations of Raspberry Pi models and provides details about their specifications. It also describes how to install an operating system like Raspbian onto the Raspberry Pi using NOOBS and provides instructions for formatting an SD card and copying the NOOBS files.

Uploaded by

Avneet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 187

Internship Report

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.

The Raspberry Pi is a low cost, credit-card sized computer that


plugs into a computer monitor or TV, and uses a standard
keyboard and mouse. It is a capable little device that enables
people of all ages to explore computing, and to learn how to
program in languages like Scratch and Python.

Generations Of Raspberry Pi
RaspberryPi 1
1. Model B

This first generation was released in February 2012.


The CPU is an older ARMv6 architecture, which includes a 700
MHzARM1176JZF-S processor.
32 bit CPU
512 MB of RAM
2 USB ports
10/100 wired Ethernet RJ45
Features a yellow RCA Composite Video Connector and a 3.5mm jack for
audio out.
1 HDMI port
Full-sized SD card slot.
26 General Purpose Input/output (GPIO) pins

2. Model A

This model was released in Feb 2013. It is simpler and inexpensive


model than the above
32 bit, 700 MHz ARM11 ARM1176JZF-S processor core
256 MB of RAM rather than the originally planned 128 MB
No Ethernet port
1 USB port
Composite video, Composite RCA, HDMI
3. Model B+

In 2014, the foundation released a board with an improved design. It is


the final revision of the original Raspberry Pi. 700 MHz ARM11
ARM1176JZF-S processor
32 bit CPU
4 USB ports
Feature a single 10/100 Ethernet jack
HDMI and Composite video. The Micro-USB port is relocated to the side
of the board alongside the HDMI port.
4-pole 3.5mm jack
Micro SD card slot to save space
CSI (camera) and DSI (display) connectors
40 General Purpose Input/Output (GPIO) pins

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

It was released in February 2015.


32-bit 900 MHz quad-core ARM Cortex-A7 processor.
1 GB RAM.
4 USB ports
1 Ethernet port
Combined 3.5mm audio jack and composite video
Full HDMI port
Camera interface (CSI) and Display interface (DSI)
Micro SD card slot.
40 GPIO pins
RaspberryPi Zero

1. Model Zero

This smaller size Pi was released in November 2015 for US$5.


1 GHz Low Power ARM1176JZ-F processor
512 MB of RAM
No Ethernet port
1 Micro USB OTG
Mini HDMI port
It is equipped with 2.4 GHz WiFi 802.11n (150 Mbit/s) and Bluetooth 4.1
(24 Mbit/s)
40 General Purpose Input/Output (GPIO) pins

2. Model Zero W/WH

1GHz, Single-core CPU


RaspberryPi Zero W was launched in 2017 with built in Wi-Fi and
Bluetooth modules over the RaspberryPi Zero and costed US $10
512MB RAM
Mini HDMI and USB On-The-Go ports
Micro USB power
HAT-compatible 40-pin header
Composite video and reset headers
CSI camera connector
802.11n wireless LAN
Bluetooth 4.0

RaspberryPi 3
1. Model B

SoC: Broadcom BCM2837


CPU: 4× ARM Cortex-A53, 1.2GHz
GPU: Broadcom VideoCore IV
RAM: 1GB LPDDR2 (900 MHz)
Networking: 10/100 Ethernet, 2.4GHz 802.11n wireless
Bluetooth: Bluetooth 4.1 Classic, Bluetooth Low Energy
Storage: microSD
GPIO: 40-pin header, populated
Ports: HDMI, 3.5mm analogue audio-video jack, 4× USB 2.0, Ethernet,
Camera Serial Interface (CSI), Display Serial Interface (DSI)
2. Model A+

Broadcom BCM2837B0, Cortex-A53 (ARMv8) 64-bit SoC @ 1.4GHz


512MB LPDDR2 SDRAM
2.4GHz and 5GHz IEEE 802.11.b/g/n/ac wireless LAN, Bluetooth
4.2/BLE
Extended 40-pin GPIO header
Full-size HDMI
Single USB 2.0 ports
CSI camera port for connecting a Raspberry Pi Camera Module
DSI display port for connecting a Raspberry Pi Touch Display
4-pole stereo output and composite video port
Micro SD port for loading your operating system and storing data
5V/2.5A DC power input
3. Model B+

SOC: Broadcom BCM2837B0, Cortex-A53 (ARMv8) 64-bit SoC


CPU: 1.4GHz 64-bit quad-core ARM Cortex-A53 CPU
RAM: 1GB LPDDR2 SDRAM
WIFI: Dual-band 802.11ac wireless LAN (2.4GHz and 5GHz ) and
Bluetooth 4.2
Ethernet: Gigabit Ethernet over USB 2.0 (max 300 Mbps). Power-over-
Ethernet support (with separate PoE HAT). Improved PXE network and
USB mass-storage booting.
Thermal management: Yes
Video: Yes – VideoCore IV 3D. Full-size HDMI
Audio: Yes
USB 2.0: 4 ports
GPIO: 40-pin
Power: 5V/2.5A DC power input
Operating system support: Linux and Unix
Installation of OS on RaspberryPi
The Foundation provides Raspbian, a Debian-based Linux distribution for
download, as well as third party Ubuntu, Windows 10 IOT Core, RISC OS, and
specialized media center distributions. It promotes Python and Scratch as the
main programming language, with support for many other languages.
If you order a Raspberry Pi without an SD card preloaded with New out Of Box
Software (NOOBS), you will need to provide your own SD card and manually
install an operating system. There are two ways to install Raspberry Pi:
 Noobs
 Raspbian
Raspbian is the foundation’s official supported Operating System based on
Debian. You can install it with NOOBS that is an easy installer for Raspbian or can
download it from the image by following the installation guide.

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 is an easy operating system installer


which contains Raspbian and LibreELEC. It also provides a selection of alternative
operating systems which are then downloaded from the internet and installed.

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/

Click on the Box that reads NOOBS


Download the zip or torrent file to obtain the full setup information of
NOOBS 3.0.1

Extract all the files to obtain the bootable setup

Formatting the SD Card and Copying Noobs


If the SD card on which you wish to install Raspbian currently has an older
version of Raspbian on it, you may wish to back up the files from the card
first, as they will be overwritten during this process.

Visit the SD Association’s website and download SD Formatter 4.0 for


Windows or Mac.

Follow the instructions to install the software.

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.

Extracting NOOBS from the zip archive

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.

Formatting The SD Card Using SD Card Formatter

For Windows users, it is recommended to format the SD card using the SD


Formatter Tool v5.0. You will need to set "FORMAT SIZE ADJUSTMENT"
option to "ON" in the "Options" menu to ensure that the entire SD card volume
is formatted, and not just a single partition. The updated size will be shown
after the format is complete.
WRITING NOOBS TO AN SD CARD:
Once you've downloaded the NOOBS zip file, you'll need to copy the contents to a
formatted SD card on your computer. To set up a blank SD card with NOOBS:
Format an SD card.
Download and extract the files from the NOOBS zip file.
Copy the extracted files onto the SD card that you just formatted, so that
this file is at the root directory of the SD card. Please note that in some
cases it may extract the files into a folder; if this is the case, then please
copy across the files from inside the
Folder rather than the folder itself.
On first boot, the "RECOVERY" FAT partition will be automatically resized
to a minimum, and a list of OSes that are available to install will be
displayed.

BOOTING FROM NOOBS AND INSTALLING RASPBIAN:


Once the files have been copied over, insert the micro SD card into your
Raspberry Pi and then plug it into a power source. Connect the converter
(HDMI to VJ) to it. A keyboard and mouse will be required to install an OS
with NOOBS, as will a HDMI display. Raspberry Pi is connected to the
Internet via Ethernet. You will be provided with a single option, once the
installer has loaded. Now Reboot the raspberry pi and a Window appears as

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.

Using the command “ssh [email protected]” we connect to a RaspberryPi that


is named “pi” and is present on the IP 172.16.30.2.
After connection, we run the command
o sudo apt-get install motion
o sudo apt install motion
Both commands perform the same task and go ahead to install the motion
module onto the Raspberry Pi.
The Motion module for the Linux system allows the device to create a
server for the given webcam feed and also allows us to live stream the
webcam data onto a local host or a web page (using IP Address)

HOW TO SETUP A RASPBERRY PI WEBCAM SERVER:

Configuring Motion

1. Now we need to make some edits to the configuration file


(motion.conf) sudo nano /etc/motion/motion.conf
2. Find the following lines and change them to the
following. daemon on
stream_localhost off
Note: Change the following two lines from on to off if you’re having issues with
the stream freezing whenever motion occurs.
output_pictures off
ffmpeg_output_movies off
Optional (Don’t include the text in brackets)
stream_maxrate 100 (This will allow for real-time streaming but requires
more bandwidth & resources)
framerate 100 (This will allow for 100 frames to be captured per second
allowing for smoother video)
width 640 (This changes the width of the image displayed)
height 480 (This changes the height of the image displayed)
3. Now we need to setup up the daemon. First, we need to edit the motion file.
sudo nano /etc/default/motion
4. Find the following line and change it to the
following: start_motion_daemon=yes
5. Once you’re done, simply save and exit by pressing ctrl+x then y (Yes), you can
also rename the file at this stage.
6. Now make sure the camera is connected and run the following line:
sudo service motion start
7. If you need to stop the service, simply run the following command:
sudo service motion stop
8. Now you should be able to check out the Webcam Stream at the IP address of
our Pi so in your browser go to the following address:
192.168.1.103:8081 (Default Address)
9. If the webpage isn’t loading, try restarting the service.
sudo service motion restart
10. If you’re using a Raspberry Pi camera, then you will need to do a few extra
steps that are mentioned below.

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

The WinSCP software is a useful tool as it allows us to communicate directly


to the host system. In our case the RaspberryPi and allows us to perform
several operations on the files that are present on the system. WinSCP can
be used to put programs from our system to the Raspberry Pi and Vice-
Versa. This in turn allows us to use windows features and applications to
work with the files present on the Raspberry Pi (Linux Debian).
For the WinSCP to work, the Pi need to have the SSH system active and a
terminal client installed onto the windows system.
For our purpose we can use two methods.

o PuTTY (Terminal for windows)


o We can download the official Ubuntu 18.04 LTS from the
Microsoft app store and run bash through it.
Useful SSH Putty Commands
1) How to find out where you are, the pwd command shows you present working
directory.

pwd

2) Change directory

cd

The cd command is used to navigate into a specified directory on your server.

Example: cd /home (moves you into the home folder)

3) The same directory

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

5) Go to the previous directory

cd –

Above command will navigate to the previous directory.

6) Go to Home folder

cd ~

Above command will navigate to the home directory on your server.

7) Go to root

cd /

Above command will navigate to root.


How to List Directories and Contents

8) List files

ls
usage: ls [option] [file]

Using the ls command in a folder will display all it’s content.

Example: ls /home.

Will return all content of the folder /home.

9) Show me all files in a directory


ls -a

10) Show contents with file size

ls -h

If you wish to see a directory’s contents with file sizes just type ls -h

11) How to see sub-directories recursively

ls -r

The ls -r command is used to see sub-directories recursively.

12) How to see files by file size

ls -is

13) List all folders in directory with details

ls -alh

How to Copy files/folders with Putty Commands

14) Copying a file

cp

To copy a file just use the cp ssh command.

Example:

cp filename.php /home/filename.php

15) Copy a folder with all files

cp -r
This one is used to copy the entire folder with all it’s contents.

16) Copy and rename

cp filename.php /home/filename2.php

How to Move files to different locations

17) Moving a file

mv

Example: mv page.php /home/page.php

18) Move and rename

mv page.php /home/newpage.php

19) Move file up one directory


mv filename ..

example: mv index.html/ ..
How to Create files/folders using Putty Commands

20) Create a folder

mkdir

example: mkdir new-folder

21) Create a file


touch

Use the touch command to create different files and file extensions

Example: touch index.php


How to Compress/Uncompress files?

22) Compressing folders


zip -r foldername.zip foldername

Example: zip -r newfolder.zip newfolder

23) uncompressing folders


unzip

Example: unzip newfolder.zip

24) Compressing folders using tar -czvf


tar -czvf foldername.tar.gz foldername

Example: tar -czvf wp-content.tar.gz wp-content

25) uncompressing folders using tar -czvf


tar -xvf foldername.tar.gz

Example: tar -xvf wp-content.tar.gz


How to Delete/Remove files?

26) Delete a file


rm

To delete a file on your server just use the rm command.

Example: rm index.php

27) Delete all files from a directory


rm *
This command is used to delete all contents from a directory.

Example: rm * foldername

28) Delete a folder/directory


rmdir

Use this command to remove directories.


How to change File permissions?

29) Change file permissions


chmod

Example: chmod 775 newfolder

30) Change permissions of folder and all files inside


chmod 755 folder name -R

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.

Hotspot creation using Raspberry pi:-


Requirements:
● Any Raspberry Pi, model B with power supply
● A boot SD card for the Raspberry Pi.
● A USB Wi-Fi device that supports "Access Point" mode; the Raspberry Pi 3
has a built-in AP Wi-Fi module.
● An Ethernet cable to connect to the local network.

HOW DOES IT WORK:


The Raspberry Pi is configured as a WiFi Hotspot, just like you would see in an
internet cafe. It allows you to connect to the internet over WiFi using the
Raspberry Pi as the bridge to the internet. The basic steps are-
● Enable a WiFi Access Point and broadcast on the channel of your choice
● Assign dynamic IP addresses to any device that connects to WiFi network
● Join the WiFi and Ethernet networks together by using Network Address
Translation
INSTRUCTIONS:
To configure a hotspot requires several steps:
1. Configure the wireless adapter with a static IP address
2. Install and configure a DHCP server
3. Install and configure the access point daemon
4. Configure IP routing between the wireless and Ethernet
In this example, the wireless network will use the address range 10.x.x.x and the
wired Ethernet will use the address range 172.168.1.x.

How to use your Raspberry Pi as a wireless access point

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.

How to use your Raspberry Pi as a wireless access point

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.

Step 1: Install and update Raspbian

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:

sudo apt-get update


sudo apt-get upgrade
If you get an upgrade, It’s a good idea to reboot with sudo reboot.

Step 2: Install hostapd and dnsmasq

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:

sudo apt-get install hostapd


sudo apt-get install

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:

sudo systemctl stop hostapd


sudo systemctl stop dnsmasq

Step 3: Configure a static IP for the wlan0 interface

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:

sudo nano /etc/dhcpcd.conf

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.

dnsmasq’s default configuration file contains a lot of unnecessary information, so


it’s easier for us to start from scratch. Let’s rename the default configuration file
and
write a new one:

sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig


sudo nano /etc/dnsmasq.conf

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.

Step 5: Configure the access point host software (hostapd)

Another config file! This time, we’re messing with the hostapd config file. Open ‘er
up:

sudo nano /etc/hostapd/hostapd.conf

This should create a brand new file. Type in this:

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:

sudo nano /etc/default/hostapd

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.

Step 6: Set up traffic forwarding

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:

sudo nano /etc/sysctl.conf

Now find this line:

#net.ipv4.ip_forward=1

…and delete the “#” – leaving the rest, so it just reads:

net.ipv4.ip_forward=1

Step 7: Add a new iptables rule

Next, we’re going to add IP masquerading for outbound traffic on eth0 using
iptables:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

…and save the new iptables rule:

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

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

Step 8: Enable internet connection

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.

To build the bridge, let’s install one more package:

sudo apt-get install bridge-utils

We’re ready to add a new bridge (called br0):

sudo brctl addbr br0

Next, we’ll connect the eth0 interface to our bridge:

sudo brctl addif br0 eth0

Finally, let’s edit the interfaces file:

sudo nano /etc/network/interfaces

…and add the following lines at the end of the file:

auto br0
iface br0 inet manual
bridge_ports eth0

Step 9: Reboot

Now that we’re ready, let’s reboot with sudo 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:

Python 2.7 (Most commonly used)


Python 3.7.3 (Latest)

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.

Major advantage of the Language “Python” is that it is both Scripting and


Programming language and hence can be understood by Web Browsers and Very
High Spec Devices.
Also Python saves a lot of programming time as it contains a lot of inbuilt
functions that save the programmer a lot of lines of code and time.

Python 2 Syntax

# Single line comments start with a number symbol.

""" Multiline strings can be written

using three "s, and are often used

as comments

"""

####################################################

# 1. Primitive Datatypes and Operators

####################################################
# You have numbers

3 # => 3

# Math is what you would expect

1 + 1 # => 2

8 - 1 # => 7

10 * 2 # => 20

35 / 5 # => 7

# Division is a bit tricky. It is integer division and floors the results

# automatically.

5 / 2 # => 2

# To fix division we need to learn about floats.

2.0 # This is a float

11.0 / 4.0 # => 2.75 ahhh...much better

# Result of integer division truncated down both for positive and negative.

5 // 3 # => 1

5.0 // 3.0 # => 1.0 # works on floats too

-5 // 3 # => -2

-5.0 // 3.0 # => -2.0

# Note that we can also import division module(Section 6 Modules)

# to carry out normal division with just one '/'.

from future import division


11 / 4 # => 2.75 ...normal division

11 // 4 # => 2 ...floored division

# Modulo operation

7 % 3 # => 1

# Exponentiation (x to the yth power)

2 ** 4 # => 16

# Enforce precedence with parentheses

(1 + 3) * 2 # => 8

# Boolean Operators

# Note "and" and "or" are case-sensitive

True and False # => False

False or True # => True

# Note using Bool operators with ints

0 and 2 # => 0

-5 or 0 # => -5

0 == False # => True

2 == True # => False

1 == True # => True

# negate with not


not True # => False

not False # => True

# Equality is ==

1 == 1 # => True

2 == 1 # => False

# Inequality is !=

1 != 1 # => False

2 != 1 # => True

# More comparisons

1 < 10 # => True

1 > 10 # => False

2 <= 2 # => True

2 >= 2 # => True

# Comparisons can be chained!

1 < 2 < 3 # => True

2 < 3 < 2 # => False

# Strings are created with " or '

"This is a string."

'This is also a string.'

# Strings can be added too!


"Hello " + "world!" # => "Hello world!"

# Strings can be added without using '+'

"Hello " "world!" # => "Hello world!"

# ... or multiplied

"Hello" * 3 # => "HelloHelloHello"

# A string can be treated like a list of characters

"This is a string"[0] # => 'T'

# You can find the length of a string

len("This is a string") # => 16

# String formatting with %

# Even though the % string operator will be deprecated on Python 3.1 and
removed

# later at some time, it may still be good to know how it works.

x = 'apple'

y = 'lemon'

z = "The items in the basket are %s and %s" % (x, y)

# A newer way to format strings is the format method.

# This method is the preferred way

"{} is a {}".format("This", "placeholder")

"{0} can be {1}".format("strings", "formatted")

# You can use keywords if you don't want to count.


"{name} wants to eat {food}".format(name="Bob", food="lasagna")

# None is an object

None # => None

# Don't use the equality "==" symbol to compare objects to None

# Use "is" instead

"etc" is None # => False

None is None # => True

# The 'is' operator tests for object identity. This isn't

# very useful when dealing with primitive values, but is

# very useful when dealing with objects.

# Any object can be used in a Boolean context.

# The following values are considered falsey:

# - None

# - zero of any numeric type (e.g., 0, 0L, 0.0,

0j) # - empty sequences (e.g., '', (), [])

# - empty containers (e.g., {}, set())

# - instances of user-defined classes meeting certain

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

bool(0) # => False


bool("") # => False

####################################################

# 2. Variables and Collections

####################################################

# Python has a print statement

print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!

# Simple way to get input data from console

input_string_var = raw_input(

"Enter some data: ") # Returns the data as a string

input_var = input("Enter some data: ") # Evaluates the data as python code

# Warning: Caution is recommended for input() method usage

# Note: In python 3, input() is deprecated and raw_input() is renamed to input()

# No need to declare variables before assigning to them.

some_var = 5 # Convention is to use lower_case_with_underscores

some_var # => 5

# Accessing a previously unassigned variable is an exception.

# See Control Flow to learn more about exception handling.

some_other_var # Raises a name error

# if can be used as an expression


# Equivalent of C's '?:' ternary operator

"yahoo!" if 3 > 2 else 2 # => "yahoo!"

# Lists store sequences

li = []

# You can start with a prefilled list

other_li = [4, 5, 6]

# Add stuff to the end of a list with append

li.append(1) # li is now [1]

li.append(2) # li is now [1, 2]

li.append(4) # li is now [1, 2, 4]

li.append(3) # li is now [1, 2, 4, 3]

# Remove from the end with pop

li.pop() # => 3 and li is now [1, 2, 4]

# Let's put it back

li.append(3) # li is now [1, 2, 4, 3] again.

# Access a list like you would any array

li[0] # => 1

# Assign new values to indexes that have already been initialized with =

li[0] = 42

li[0] # => 42

li[0] = 1 # Note: setting it back to the original value

# Look at the last element

li[-1] # => 3
# Looking out of bounds is an IndexError

li[4] # Raises an IndexError

# You can look at ranges with slice syntax.

# (It's a closed/open range for you mathy types.)

li[1:3] # => [2, 4]

# Omit the beginning

li[2:] # => [4, 3]

# Omit the end

li[:3] # => [1, 2, 4]

# Select every second entry

li[::2] # =>[1, 4]

# Reverse a copy of the list

li[::-1] # => [3, 4, 2, 1]

# Use any combination of these to make advanced slices

# li[start:end:step]

# Remove arbitrary elements from a list with "del"

del li[2] # li is now [1, 2, 3]

# You can add lists

li + other_li # => [1, 2, 3, 4, 5, 6]

# Note: values for li and for other_li are not modified.

# Concatenate lists with "extend()"


li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]

# Remove first occurrence of a value

li.remove(2) # li is now [1, 3, 4, 5, 6]

li.remove(2) # Raises a ValueError as 2 is not in the list

# Insert an element at a specific index

li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again

# Get the index of the first item found

li.index(2) # => 1

li.index(7) # Raises a ValueError as 7 is not in the list

# Check for existence in a list with "in"

1 in li # => True

# Examine the length with "len()"

len(li) # => 6

# Tuples are like lists but are immutable.

tup = (1, 2, 3)

tup[0] # => 1

tup[0] = 3 # Raises a TypeError

# You can do all those list thingies on tuples too

len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)

tup[:2] # => (1, 2)

2 in tup # => True

# You can unpack tuples (or lists) into variables

a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3

d, e, f = 4, 5, 6 # you can leave out the parentheses

# Tuples are created by default if you leave out the parentheses

g = 4, 5, 6 # => (4, 5, 6)

# Now look how easy it is to swap two values

e, d = d, e # d is now 5 and e is now 4

# Dictionaries store mappings

empty_dict = {}

# Here is a prefilled dictionary

filled_dict = {"one": 1, "two": 2, "three": 3}

# Look up values with []

filled_dict["one"] # => 1

# Get all keys as a list with "keys()"

filled_dict.keys() # => ["three", "two", "one"]

# Note - Dictionary key ordering is not guaranteed.

# Your results might not match this exactly.

# Get all values as a list with "values()"


filled_dict.values() # => [3, 2, 1]

# Note - Same as above regarding key ordering.

# Get all key-value pairs as a list of tuples with "items()"

filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]

# Check for existence of keys in a dictionary with "in"

"one" in filled_dict # => True

1 in filled_dict # => False

# Looking up a non-existing key is a KeyError

filled_dict["four"] # KeyError

# Use "get()" method to avoid the KeyError

filled_dict.get("one") # => 1

filled_dict.get("four") # => None

# The get method supports a default argument when the value is missing

filled_dict.get("one", 4) # => 1

filled_dict.get("four", 4) # => 4

# note that filled_dict.get("four") is still => None

# (get doesn't set the value in the dictionary)

# set the value of a key with a syntax similar to lists

filled_dict["four"] = 4 # now, filled_dict["four"] => 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

filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5

# You can declare sets (which are like unordered lists that cannot contain

# duplicate values) using the set object.

empty_set = set()

# Initialize a "set()" with a bunch of values

some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])

# order is not guaranteed, even though it may sometimes look sorted

another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4])

# Since Python 2.7, {} can be used to declare a set

filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}

# Add more items to a set

filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}

# Do set intersection with &

other_set = {3, 4, 5, 6}

filled_set & other_set # => {3, 4, 5}

# Do set union with |

filled_set | other_set # => {1, 2, 3, 4, 5, 6}

# Do set difference with -


{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}

# Do set symmetric difference with ^

{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}

# Check if set on the left is a superset of set on the right

{1, 2} >= {1, 2, 3} # => False

# Check if set on the left is a subset of set on the right

{1, 2} <= {1, 2, 3} # => True

# Check for existence in a set with in

2 in filled_set # => True

10 in filled_set # => False

10 not in filled_set # => True

# Check data type of variable

type(li) # => list

type(filled_dict) # => dict

type(5) # => int

####################################################

# 3. Control Flow

####################################################
# Let's just make a variable

some_var = 5

# Here is an if statement. Indentation is significant in python!

# prints "some_var is smaller than 10"

if some_var > 10:

print "some_var is totally bigger than 10."

elif some_var < 10: # This elif clause is optional.

print "some_var is smaller than 10."

else: # This is optional too.

print "some_var is indeed 10."

"""

For loops iterate over lists

prints:

dog is a mammal

cat is a mammal

mouse is a mammal

"""

for animal in ["dog", "cat", "mouse"]:

# You can use {0} to interpolate formatted strings. (See above.)

print "{0} is a mammal".format(animal)

"""

"range(number)" returns a list of numbers

from zero to the given number


prints:

"""

for i in range(4):

print i

"""

"range(lower, upper)" returns a list of numbers

from the lower number to the upper number

prints:

"""

for i in range(4, 8):

print i

"""

While loops go until a condition is no longer met.

prints:

1
2

"""

x=0

while x < 4:

print x

x += 1 # Shorthand for x = x + 1

# Handle exceptions with a try/except block

# Works on Python 2.6 and up:

try:

# Use "raise" to raise an error

raise IndexError("This is an index error")

except IndexError as e:

pass # Pass is just a no-op. Usually you would do recovery here.

except (TypeError, NameError):

pass # Multiple exceptions can be handled together, if required.

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

finally: # Execute under all circumstances

print "We can clean up resources here"

# Instead of try/finally to cleanup resources you can use a with statement

with open("myfile.txt") as f:

for line in f:
print line

####################################################

# 4. Functions

####################################################

# Use "def" to create new functions

def add(x, y):

print "x is {0} and y is {1}".format(x, y)

return x + y # Return values with a return statement

# Calling functions with parameters

add(5, 6) # => prints out "x is 5 and y is 6" and returns 11

# Another way to call functions is with keyword arguments

add(y=6, x=5) # Keyword arguments can arrive in any order.

# You can define functions that take a variable number of

# positional args, which will be interpreted as a tuple by using *

def varargs(*args):

return args
varargs(1, 2, 3) # => (1, 2, 3)

# You can define functions that take a variable number of

# keyword args, as well, which will be interpreted as a dict by using **

def keyword_args(**kwargs):

return kwargs

# Let's call it to see what happens

keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}

# You can do both at once, if you like

def all_the_args(*args, **kwargs):

print args

print kwargs

"""

all_the_args(1, 2, a=3, b=4) prints:

(1, 2)

{"a": 3, "b": 4}

"""

# When calling functions, you can do the opposite of args/kwargs!


# Use * to expand positional args and use ** to expand keyword args.

args = (1, 2, 3, 4)

kwargs = {"a": 3, "b": 4}

all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)

all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)

all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4)

# you can pass args and kwargs along to other functions that take args/kwargs

# by expanding them with * and ** respectively

def pass_all_the_args(*args, **kwargs):

all_the_args(*args, **kwargs)

print varargs(*args)

print keyword_args(**kwargs)

# Function Scope

x=5

def set_x(num):

# Local var x not the same as global variable x

x = num # => 43

print x # => 43
def set_global_x(num):

global x

print x # => 5

x = num # global var x is now set to 6

print x # => 6

set_x(43)

set_global_x(6)

# Python has first class functions

def create_adder(x):

def adder(y):

return x + y

return adder

add_10 = create_adder(10)

add_10(3) # => 13

# There are also anonymous functions

(lambda x: x > 2)(3) # => True

(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5


# There are built-in higher order functions

map(add_10, [1, 2, 3]) # => [11, 12, 13]

map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]

filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]

# We can use list comprehensions for nice maps and filters

[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]

[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]

# You can construct set and dict comprehensions as well.

{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}

{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

####################################################

# 5. Classes

####################################################

# We subclass from object to get a class.

class Human(object):

# A class attribute. It is shared by all instances of this class

species = "H. sapiens"

# Basic initializer, this is called when this class is instantiated.

# Note that the double leading and trailing underscores denote objects
# or attributes that are used by python but that live in user-controlled

# namespaces. You should not invent such names on your own.

def init (self, name):

# Assign the argument to the instance's name attribute

self.name = name

# Initialize property

self.age = 0

# An instance method. All methods take "self" as the first argument

def say(self, msg):

return "{0}: {1}".format(self.name, msg)

# A class method is shared among all instances

# They are called with the calling class as the first argument

@classmethod

def get_species(cls):

return cls.species

# A static method is called without a class or instance reference

@staticmethod

def grunt():

return "*grunt*"

# A property is just like a getter.

# It turns the method age() into an read-only attribute


# of the same name.

@property

def age(self):

return self._age

# This allows the property to be set

@age.setter

def age(self, age):

self._age = age

# This allows the property to be deleted

@age.deleter

def age(self):

del self._age

# Instantiate a class

i = Human(name="Ian")

print i.say("hi") # prints out "Ian: hi"

j = Human("Joel")

print j.say("hello") # prints out "Joel: hello"

# Call our class method

i.get_species() # => "H. sapiens"


# Change the shared attribute

Human.species = "H. neanderthalensis"

i.get_species() # => "H. neanderthalensis"

j.get_species() # => "H. neanderthalensis"

# Call the static method

Human.grunt() # => "*grunt*"

# Update the property

i.age = 42

# Get the property

i.age # => 42

# Delete the property

del i.age

i.age # => raises an AttributeError

####################################################

# 6. Modules

####################################################

# You can import modules

import math

print math.sqrt(16) # => 4.0


# You can get specific functions from a module

from math import ceil, floor

print ceil(3.7) # => 4.0

print floor(3.7) # => 3.0

# You can import all functions from a module.

# Warning: this is not recommended

from math import *

# You can shorten module names

import math as m

math.sqrt(16) == m.sqrt(16) # => True

# you can also test that the functions are equivalent

from math import sqrt

math.sqrt == m.sqrt == sqrt # => True

# Python modules are just ordinary python files. You

# can write your own, and import them. The name of the

# module is the same as the name of the file.

# You can find out which functions and attributes

# defines a module.
import math

dir(math)

# If you have a Python script named math.py in the same

# folder as your current script, the file math.py will

# be loaded instead of the built-in Python module.

# This happens because the local folder has priority

# over Python's built-in libraries.

####################################################

# 7. Advanced

####################################################

# Generators

# A generator "generates" values as they are requested instead of storing

# everything up front

# The following method (*NOT* a generator) will double all values and store it

# in `double_arr`. For large size of iterables, that might get huge!

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

# of them back to be checked by our condition

for value in double_numbers(range(1000000)): # `test_non_generator`

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

for value in double_numbers_generator(xrange(1000000)): # `test_generator`

print value

if value > 5:

break
# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in
`test_generator`?

# Just as `double_numbers_generator` is the generator version of


`double_numbers`

# We have `xrange` as the generator version of `range`

# `range` would return back and array with 1000000 values for us to use

# `xrange` would generate 1000000 values for us as we request / iterate over


those items

# Just as you can create a list comprehension, you can create generator

# comprehensions as well.

values = (-x for x in [1, 2, 3, 4, 5])

for x in values:

print(x) # prints -1 -2 -3 -4 -5 to console/terminal

# You can also cast a generator comprehension directly to a list.

values = (-x for x in [1, 2, 3, 4, 5])

gen_to_list = list(values)

print(gen_to_list) # => [-1, -2, -3, -4, -5]

# Decorators

# A decorator is a higher order function, which accepts and returns a function.

# Simple usage example – add_apples decorator will add 'Apple' element into

# fruits list returned by get_fruits target function.

def add_apples(func):

def get_fruits():
fruits = func()

fruits.append('Apple')

return fruits

return get_fruits

@add_apples

def get_fruits():

return ['Banana', 'Mango', 'Orange']

# Prints out the list of fruits with 'Apple' element in it:

# Banana, Mango, Orange, Apple

print ', '.join(get_fruits())

# in this example beg wraps say

# Beg will call say. If say_please is True then it will change the returned

# message

from functools import wraps

def beg(target_function):

@wraps(target_function)

def wrapper(*args, **kwargs):

msg, say_please = target_function(*args, **kwargs)

if say_please:

return "{} {}".format(msg, "Please! I am poor :(")

return msg
return wrapper

@beg

def say(say_please=False):

msg = "Can you buy me a beer?"

return msg, say_please

print say() # Can you buy me a beer?

print say(say_please=True) # Can you buy me a beer? Please! I am poor :(

HOW TO DOWNLOAD AND INSTALL


PYTHON:-
Python: Version 3.6.2
The Python download requires about 30 Mb of disk space; keep it on your
machine, in case you need to re-install Python. When installed, Python requires
about an additional 90 Mb of disk space.
Downloading
1. Click Python Download.
The following page will appear in your browser.
2. Click the Download Python 3.6.2 button.
The file named python-3.6.2.exe should start downloading into your standard
download folder. This file is about 30 Mb so it might take a while to download
fully if you are on a slow internet connection (it took me about 10 seconds over a
cable modem).
The file should appear as

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?

4. Click the Yes button.


A new Python 3.6.2 (32-bit) Setup pop-up window will appear with a Setup
Progress message and a progress bar.
During installation, it will show the various components it is installing and move
the progress bar towards completion. Soon, a new Python 3.6.2 (32-bit) Setup
pop-up window will appear with a Setup was successful message.

5. Click the Close button.


Python should now be installed.
Verifying
To try to verify installation,
1. Navigate to the directory C:\Users\Pattis\
Gf9m5PCwpwb1EG9XyJgwVosLWYX7URUBcFon36-32 (or to whatever
directory Python was installed: see the pop-up window for Installing step 3).
2. Double-click the icon/file python.exe.
The following pop-up window will appear.

INSTALL PYTHON DEVELOPMENT TOOLS:


To program the GPIO pins on Raspberry Pi with Python, there is a Raspberry Pi
GPIO Python library that is made available. For this, open a terminal on the
Raspberry Pi either via the desktop or by using SSH. (default credentials are
pi/raspberry). Run the following commands to install some basic Python
development tools:
> sudo apt-get update
> apt-get install python-dev python-pip
> pip install python
INSTALL PYTHON DEVELOPMENT TOOLS:
To program the GPIO pins on Raspberry Pi with Python, there is a Raspberry Pi
GPIO Python library that is made available. For this, open a terminal on the
Raspberry Pi either via the desktop or by using SSH. (default credentials are
pi/raspberry). Run the following commands to install some basic Python
development tools:
> sudo apt-get update
> apt-get install python-dev python-pip
> pip install python
INSTALL GPIO LIBRARY:
The RPi.GPIO Python library allows you to easily configure and read-write the
input/output pins on the Pi’s GPIO header within a Python script. Thankfully this
library is now including in the standard Raspbian image. If it is required to install
the RPi GPIO library, there are two methods to install it-

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.

Triggered with Ctrl + P , it is possible to:

 Type part of a file name to open it.


 Type @ to jump to symbols, # to search within the file, and : to go to a line
number.

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:

 A popup is displayed when hovering over a symbol


 Pressing F12 when the caret is on a symbol
 The Goto Symbol in Project functionality

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.

Show the Command Palette with Ctrl + Shift + P .

POWERFUL API AND PACKAGE ECOSYSTEM


Sublime Text has a powerful, Python API that allows plugins to augment built-in functionality.
Package Control can be installed via the command palette, providing simple access to
thousands of packages built by the community.

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.

INSTANT PROJECT SWITCH


Projects in Sublime Text capture the full contents of the workspace, including modified and
unsaved files. You can switch between projects in a manner similar to Goto Anything, and the
switch is instant, with no save prompts - all your modifications will be restored next time the
project is opened.

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

Teletype for Atom


Great things happen when developers work together—from teaching and sharing
knowledge to building better software. Teletype for Atom makes collaborating on
code just as easy as it is to code alone, right from your editor.
Share your workspace and edit code together in real time. To start
collaborating, open Teletype in Atom and install the package.
GitHub for Atom
A text editor is at the core of a developer’s toolbox, but it doesn't usually work
alone. Work with Git and GitHub directly from Atom with the GitHub package.

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!

Everything you would expect


Cross-platform editing
Atom works across operating systems. Use it on OS X, Windows, or Linux.
Built-in package manager
Search for and install new packages or create your own right from Atom.

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.

Make it your editor


Packages
Choose from thousands of open source packages that add new features and
functionality to Atom, or build a package from scratch and publish it for everyone
else to use.
Themes
Atom comes pre-installed with four UI and eight syntax themes in both dark and
light colors. Can't find what you're looking for? Install themes created by the
Atom community or create your own.
Customization
It's easy to customize and style Atom. Tweak the look and feel of your UI with
CSS/Less, and add major features with HTML and JavaScript.

See how to set up Atom

Under the hood


Atom is a desktop application built with HTML, JavaScript, CSS, and Node.js
integration. It runs on Electron, a framework for building cross platform apps
using web technologies.

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.

Introduction to Raspberry Pi SPI


Overview
The Raspberry Pi is equipped with one SPI bus that has 2 chip selects.
The SPI master driver is disabled by default on Raspbian. To enable it, use raspi-
config, or ensure the line dtparam=spi=on isn't commented out
in /boot/config.txt, and reboot. If the SPI driver was loaded, you should see the
device /dev/spidev0.0.
The SPI bus is available on the P1 Header:

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

# Write binary 1, 2 and 3


echo -ne "\x01\x02\x03" > /dev/spidev0.0

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

SCLK - Serial CLocK


CE - Chip Enable (often called Chip
Select) MOSI - Master Out Slave In
MISO - Master In Slave Out
MOMI - Master Out Master
In

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:

SCLK = Core Clock / CDIV


If CDIV is set to 0, the divisor is 65536. The divisor must be a power of 2.
Odd numbers rounded down. The maximum SPI clock rate is of the APB clock.

Errata: "must be a power of 2" probably should be "must be a multiple of 2"


See the Linux driver section for more info.
Chip Select
Setup and Hold times related to the automatic assertion and de-assertion of the
CS lines when operating in DMA mode are as follows:
 The CS line will be asserted at least 3 core clock cycles before the msb of the
first byte of the transfer.
 The CS line will be de-asserted no earlier than 1 core clock cycle after the
trailing edge of the final clock pulse.
Linux driver
The default Linux driver is spi-bcm2708.
The following information was valid 2014-07-05.
Speed
The driver supports the following speeds:

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

SPI_CPOL Clock polarity


SPI_CPHA Clock phase
SPI_CS_HIGH - Chip Select active high SPI_NO_CS- 1 device per bus, no Chip Select
SPI_3WIRE- Bidirectional mode, data in and out pin shared

Bidirectional or "3-wire" mode is supported by the spi-bcm2835 kernel module.


Please note that in this mode, either the tx or rx field of the spi_transfer struct
must be a NULL pointer, since only half-duplex communication is possible.
Otherwise, the transfer will fail. The spidev_test.c source code does not consider
this correctly, and therefore does not work at all in 3-wire mode.
Supported bits per word
 8 - Normal
 9 - This is supported using LoSSI mode.
Transfer modes
Only interrupt mode is supported.
Deprecated warning
The following appears in the kernel log:

bcm2708_spi bcm2708_spi.0: master is unqueued, this is deprecated

SPI driver latency


This thread discusses latency problems.
DMA capable driver
This is a fork of spi-bcm2708 which enables DMA support for SPI client drivers
that support DMA.
https://github.com/notro/spi-bcm2708 (wiki)
Troubleshooting
Loopback test
This can be used to test SPI send and receive. Put a wire between MOSI and MISO.
It does not test CE0 and CE1.

wget https://raw.githubusercontent.com/raspberrypi/linux/rpi-
3.10.y/Documentation/spi/spidev_test.c

gcc -o spidev_test spidev_test.c

./spidev_test -D /dev/spidev0.0
spi mode: 0

bits per word: 8


max speed: 500000 Hz (500 KHz)

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

Introduction to Raspberry Pi PWM


PWM (Pulse Width Modulation) is a modulation technique by which the width of
pulse is varied while keeping the frequency constant.
Through PWM technique, we can control the power delivered to the load by using
ON-OFF signal.
The PWM signals can be used for applications such as controlling the speed of DC
motors, changing intensity of an LED, controlling Servo motors, etc.
The GIF shown below depicts the use of PWM for intensity control of an LED.

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:

GPIO Pin PWM0/PWM1

GPIO12 PWM0

GPIO18 PWM0

GPIO13 PWM1

GPIO19 PWM1
The PWM pins on Raspberry Pi 40-pin P1Header is shown in below figure,

Raspberry Pi PWM Pins


The PWM pins on Raspberry Pi are shared with audio subsystem. Thus, we can
have either PWM output or Audio output.
Interfacing Diagram

Control LED Brightness using PWM on Raspberry Pi


Example
Here, we are going to generate PWM on Raspberry Pi. This PWM output is
connected to an LED which will show change in intensity.
Let’s generate PWM using C and Python language.
Generate PWM using Python
The PWM generated by Python on Raspberry Pi is software PWM. This PWM has
timing resolution of 1 us which is better than Software PWM generated using C
(WiringPi library).
Python Program

import RPi.GPIO as GPIO


from time import sleep

ledpin = 12 # PWM pin connected to LED


GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD)
#disable warnings #set pin numbering system

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)

for duty in range(100,-1,-1):


pi_pwm.ChangeDutyCycle(duty) sleep(0.01)
sleep(0.5)

PWM Functions in Python


Create PWM Object
Create an Object of class PWM which is a part of RPi.GPIO library. Here, we have
created Object of name pi_pwm. We can provide any name for Object.
E.g.
pi_pwm = GPIO.PWM (Pin no., frequency)
Where,
o Pin no. – PWM pin no on which PWM will be generated.
o Frequency – frequency of PWM
Now, we can call PWM functions of RPi.GPIO library by using PWM object.
Note: The PWM which is generated here is Software PWM and can generate on
any GPIO pin.
start (Duty Cycle)
It is used to start PWM generation of specified Duty Cycle.
ChangeDutyCycle(Duty Cycle)
This function is used to change the Duty Cycle of signal. We have to provide Duty
Cycle in the range of 0-100.
ChangeFrequency(frequency)
This function is used to change the frequency (in Hz) of PWM. This function we
have not used in above program. But, we can use it for changing the frequency.
stop()
This function is used to stop the PWM generation.

Inter IC (I2C) Communication Protocol

Inter IC (i2c) (IIC) is important serial communication protocol in modern


electronic systems. Philips invented this protocol in 1986. The objective of
reducing the cost of production of television remote control motivated Philips to
invent this protocol. IIC is a serial bus interface, can be implemented in software,
but most of the microcontrollers support IIC by incorporating it as hard IP
(Intellectual Property). IIC can be used to interface microcontroller with RTC,
EEPROM and different variety of sensors. IIC is used to interface chips on
motherboard, generally between a processor chip and any peripheral which
supports IIC. IIC is very reliable wireline communication protocol for an on board
or short distances. I2C is a serial protocol for two-wire interface to connect low-
speed devices like microcontrollers, EEPROMs, A/D and D/A converters, I/O
interfaces and other similar peripherals in embedded systems IIC protocol uses
two pins for data transfer: Serial Data Line (SDA) and Serial Clock Line (SCL). The
reduction in number of pins in comparison with parallel data transfer is evident.
This reduces the cost of production, package size and power consumption. IIC is
also best suited protocol for battery operated devices. IIC is also referred as two
wire serial interface (TWI).
PROGRAMMING WITH PYTHON ON
RASPBERRY PI
You can write a Python file in a standard editor like Sublime or Nano, and run it as
a Python script from the command line.
pi@raspberrypi ~ $
This (above) is the command prompt. A CLI or command line interface is actually
a very quick and efficient way to use a computer.
To start, just navigate to the directory where the file is saved (use cd and ls for
guidance).
TIP: You can use the TAB key for autocomplete as you enter commands.
Then, run the program (e.g. hello) with python using the command
> python hello.py

● Few commands which we are going to use in PYTHON program:

○ import RPi.GPIO as GPIO


We are going to import GPIO file from library, above function enables us to
program GPIO pins of PI. We are also renaming “RPi.GPIO” to “GPIO”, so in the
program whenever we want to refer to GPIO pins we will use the word ‘GPIO’.

○ 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:

print "Hello World"

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:

Humidity sensor Polymer humidity capacitor

Temperature sensor Thermistor

Supply voltage 3.3 to 5.5V DC


Operating range humidity 0 to-100 % RH , temperature - 40 to 80 deg
Celsius
Output signal digital signal via 1- wire bus
Resolution or humidity 0.1% RH ; temperature 0.1 Celsius
sensitivity
Repeatability humidity +/- 1% RH; temperature +/- 0.2 Celsius
Sensing period Average: 2 s
Accuracy humidity +/- 2 % RH (Max +/- 5 % RH) ,
Model DHT22
Sensor Length small size 14 x 18 x 5.5 mm; big size 22 x 28 x 5 mm
(millimetre)
DS18B20
The DS18B20 is a 1-wire programmable Temperature sensor from maxim
integrated. It is widely used to measure temperature in hard environments like in
chemical solutions, mines or soil etc. The constriction of the sensor is rugged and
also can be purchased with a waterproof option making the mounting process
easy. It can measure a wide range of temperature from -55°C to +125° with a
decent accuracy of ±5°C. Each sensor has a unique address and requires only one
pin of the MCU to transfer data so it a very good choice for measuring
temperature at multiple points without compromising much of your digital pins
on the microcontroller.

How to use the DS18B20 Sensor


The sensor works with the method of 1-Wire communication. It requires only the
data pin connected to the microcontroller with a pull up resistor and the other
two pins are used for power as shown below.

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

Measuring temperature at hard environments


Liquid temperature measurement
Applications where temperature has to be measured at multiple
points

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.

On the Top Left we find an option to create a new project.


We proceed with that option and create a new project.

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)

After setting all permissions we create the JSON file.


The Service account ID is used in the programs in order to access the
services that are available in the dashboard.

We primarily use the services of Google Spreadsheets and Google Drive to


Display and Store data on the cloud.
The above given code is the inclusion of the necessary libraries for the
google services to run smoothly. In python sometimes we might need to
segregate the libraries and purge an older version of “Pysan”. This removes
the error. Further we download the gspread, oauth2client and
Adafruit_DHT libraries that are required for the Spreadsheet.

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.

The next option is Devices that shows connected devices.


On clicking on one of the devices we can see all data that is sent over to the
cloud by the Raspberry Pi or the Node MCU.

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

Adafruit IO comes with a variety of things we need to setup before we can


get into the actual sending and retrieving of data. These are:
o Feeds
o Dashboard
o Triggers
o AIO Keys
Feeds are the most essential of the services that are given by Adafruit IO.
We use the feeds to send the data from the device to the cloud.
We first create feeds on the website. As the feeds are created, they are
automatically assigned keys. These keys are used as parameters for the feed
variables in the program and the data is sent over.

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.

Data to ThingSpeak is sent through the creation of channels and variables


on the website.
The website offers you with a variety of options and the API Key. The code
for the API Authentication is also given on the right hand side.
We use the predefined channels in the program by setting them up as
arguments and sending the data over the internet.

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.

We go to the applets page and create applets according to our needs.


IFTTT connects a lot of clouds together like particle and data fron
those can be taken in as input.

IFTTT cloud helps us in making applets that we can interact with


from our mobile devices or through our systems.
Node MCU (ESP8266)
NodeMCU is an open source LUA based firmware developed for ESP8266 wifi
chip. By exploring functionality with ESP8266 chip, NodeMCU firmware comes
with ESP8266 Development board/kit i.e. NodeMCU Development board.

NodeMCU Development Board/kit v0.9 (Version1)


Since NodeMCU is open source platform, their hardware design is open for
edit/modify/build.
NodeMCU Dev Kit/board consist of ESP8266 wifi enabled chip. The ESP8266 is a
low-cost Wi-Fi chip developed by Espressif Systems with TCP/IP protocol. For
more information about ESP8266, you can refer ESP8266 WiFi Module.
There is Version2 (V2) available for NodeMCU Dev Kit i.e. NodeMCU Development
Board v1.0 (Version2), which usually comes in black colored PCB.
NodeMCU Development Board/kit v1.0 (Version2)

For more information about NodeMCU Boards available in market


refer NodeMCU Development Boards
NodeMCU Dev Kit has Arduino like Analog (i.e. A0) and Digital (D0-D8) pins on its
board.
It supports serial communication protocols i.e. UART, SPI, I2C etc.
Using such serial protocols we can connect it with serial devices like I2C enabled
LCD display, Magnetometer HMC5883, MPU-6050 Gyro meter + Accelerometer,
RTC chips, GPS modules, touch screen displays, SD cards etc.
How to start with NodeMCU?
NodeMCU Development board is featured with wifi capability, analog pin, digital
pins and serial communication protocols.
To get start with using NodeMCU for IoT applications first we need to know about
how to write/download NodeMCU firmware in NodeMCU Development Boards.
And before that where this NodeMCU firmware will get as per our requirement.
There is online NodeMCU custom builds available using which we can easily get
our custom NodeMCU firmware as per our requirement.
To know more about how to build custom NodeMCU firmware online and
download it refer Getting started with NodeMCU
How to write codes for NodeMCU?
After setting up ESP8266 with Node-MCU firmware, let’s see the IDE (Integrated
Development Environment) required for development of NodeMCU.
NodeMCU with ESPlorer IDE
Lua scripts are generally used to code the NodeMCU. Lua is an open source,
lightweight, embeddable scripting language built on top of C programming
language.
For more information about how to write Lua script for NodeMCU refer Getting
started with NodeMCU using ESPlorerIDE
NodeMCU with Arduino IDE
Here is another way of developing NodeMCU with a well-known IDE i.e. Arduino
IDE. We can also develop applications on NodeMCU using Arduino development
environment. This makes easy for Arduino developers than learning new
language and IDE for NodeMCU.
For more information about how to write Arduino sketch for NodeMCU
refer Getting started with NodeMCU using ArduinoIDE

Difference in using ESPlorer and Arduino IDE


Well, there is a programming language difference we can say while developing
application for NodeMCU using ESPlorer IDE and Arduino IDE.
We need to code in C\C++ programming language if we are using Arduino IDE for
developing NodeMCU applications and Lua language if we are using ESPlorer IDE.
Basically, NodeMCU is Lua Interpreter, so it can understand Lua script easily.
When we write Lua scripts for NodeMCU and send/upload it to NodeMCU, then
they will get executes sequentially. It will not build binary firmware file of code
for NodeMCU to write. It will send Lua script as it is to NodeMCU to get execute.
In Arduino IDE when we write and compile code, ESP8266 toolchain in
background creates binary firmware file of code we wrote. And when we upload
it to NodeMCU then it will flash all NodeMCU firmware with newly generated
binary firmware code. In fact, it writes the complete firmware.
That’s the reason why NodeMCU not accept further Lua scripts/code after it is
getting flashed by Arduino IDE. After getting flashed by Arduino sketch/code it
will be no more Lua interpreter and we got error if we try to upload Lua scripts.
To again start with Lua script, we need to flash it with NodeMCU firmware.
Since Arduino IDE compile and upload/writes complete firmware, it takes more
time than ESPlorer IDE.

Node MCU With Aurdino IDE


NodeMCU is Lua based firmware of ESP8266. Generally, ESPlorer IDE is referred
for writing Lua scripts for NodeMCU. It requires to get familiar with ESPlorer IDE
and Lua scripting language.
There is another way of developing NodeMCU with a well-known IDE i.e. Arduino
IDE. We can also develop NodeMCU applications using Arduino development
environment. This makes things easy for Arduino developers than learning new
language and IDE for NodeMCU.
Let’s see about setting up Arduino IDE with NodeMCU.
First Download Arduino IDE (version
1.6+) https://www.arduino.cc/en/Main/Software
Open Arduino IDE and Go to File -> Preference.

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.

NodeMCU connection with PC


After setting up Arduino IDE for NodeMCU, open Arduino IDE and write simple
sketch of serial print as shown in below figure.
Arduino Sketch
void setup()
{
Serial.begin(9600); /* initialise serial communication */
}

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.

NodeMCU DevKit GPIOs


Below table gives NodeMCU Dev Kit IO pins and ESP8266 internal GPIO pins
mapping
Pin Names on NodeMCU ESP8266 Internal GPIO Pin
Development Kit number
D0 GPIO16
D1 GPIO5
Pin Names on NodeMCU ESP8266 Internal GPIO Pin
Development Kit number
D2 GPIO4
D3 GPIO0
D4 GPIO2
D5 GPIO14
D6 GPIO12
D7 GPIO13
D8 GPIO15
D9/RX GPIO3
D10/TX GPIO1
D11/SD2 GPIO9
D12/SD3 GPIO10

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

delay(1000); // Wait for a second


digitalWrite(LED_Pin, HIGH);// Turn the LED off
delay(1000); // Wait for a second
}

NodeMCU PWM with Arduino IDE


Pulse Width Modulation (PWM) is a technique by which width of a pulse is varied
while keeping the frequency of the wave constant.
PWM Generation
A period of a pulse consists of an ON cycle (VCC) and an OFF cycle (GND). The
fraction for which the signal is ON over a period is known as a duty cycle.

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

NodeMCU PWM Pins


Arduino function for NodeMCU PWM
analogWrite(pin, dutycycle): Enables software PWM on the specified pin. duty
cycleis in the range from 0 to PWMRANGE, i.e. 1023 by default.
analogWrite(pin, 0): Disables PWM on specified pin.
analogWriteRange(new_range): This function is used to change PWM range (duty
cycle).
analogWriteFreq(new_frequency): PWM frequency is 1kHz by default. Call this
function to change it with new frequency.PWM frequency is in the range 1 –
1000Khz.
Example
Let’s write an Arduino sketch to set PWM on 6thpin of NodeMCU and vary it’s
duty cycle with the potentiometer connected to the ADC pin of NodeMCU. Here
we connect LED on PWM pin to visualize effect (Brightness of LED) of PWM
variation.

LED Brightness Control using NodeMCU PWM

Arduino Sketch for PWM


uint8_t LEDpin = D6;

/* By default PWM frequency is 1000Hz and we are using same


for this application hence no need to set */

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

NodeMCU SPI with Arduino IDE


The Serial Peripheral Interface (SPI) is a bus interface connection protocol
originally started by Motorola Corp.
SPI Interface uses four wires for communication. Hence it is also known as four
wire serial communication protocol.
SPI is a full duplex master-slave communication protocol. This means that only a
single master and a single slave can communicate on the interface bus at the same
time.
SPI enabled devices work in two basic modes of SPI operation i.e. SPI Master
Mode and SPI Slave Mode.
Master Device is responsible for initiation of communication. Master Device
generates Serial Clock for synchronous data transfer. Master Device can handle
multiple slave devices on the bus by selecting them one by one.
NodeMCU based ESP8266 has Hardware SPI with four pins available for SPI
communication. With this SPI interface, we can connect any SPI enabled device
with NodeMCU and make communication possible with it.
ESP8266 has SPI pins (SD1, CMD, SD0, CLK) which are exclusively used for Quad-
SPI communication with flash memory on ESP-12E, hence, they can’t be used for
SPI applications. We can use Hardware SPI interface for user end applications.
Below figure shows Quad SPI interface pins that are internally used for flash. It
consists quad i/o (4-bit data bus) i.e. four (SDIO_DATA0 – SDIO_DATA3)
bidirectional (i/p and o/p) data signals with synchronize clock (SDIO_CLK) and
chip select pin (SDIO_CMD). It is mostly used to get more bandwidth/throughput
than dual i/o (2-bit data bus) interface.
NodeMCU SPI Pins
NodeMCU SPI Pins

MISO (Master In Slave Out)


Master receives data and slave transmits data through this pin.
MOSI (Master Out Slave In)
Master transmits data and slave receives data through this pin.
SCLK (Serial Clock)
Master generates this clock for the communication, which is used by
slave.
Only master can initiate serial clock.
CS (Chip Select)
Master can select slave device through this pin to start communication
with it.

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.

NodeMCU Arduino SPI Interfacing Diagram

Arduino sketch for NodeMCU Master SPI


#include<SPI.h>

char buff[]="Hello Slave\n";

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

Arduino Sketch for Arduino Uno slave SPI


#include <SPI.h>

char buff [100];


volatile byte index;
volatile bool receivedone; /* use reception complete flag */

void setup (void)


{
Serial.begin (9600);
SPCR |= bit(SPE); /* Enable SPI */
pinMode(MISO, OUTPUT); /* Make MISO pin as OUTPUT
*/ index = 0;
receivedone = false;
SPI.attachInterrupt(); /* Attach SPI interrupt */
}

void loop (void)


{
if (receivedone) /* Check and print received buffer if any */
{
buff[index] = 0;
Serial.println(buff);
index = 0;
receivedone = false;
}
}

// SPI interrupt routine


ISR (SPI_STC_vect)
{
uint8_t oldsrg = SREG;
cli();
char c = SPDR;
if (index <sizeof buff)
{
buff [index++] = c;
if (c == '\n'){ /* Check for newline character as end of msg
*/ receivedone = true;
}
}
SREG = oldsrg;
}

Slave Output Window


This output is received at slave device which is transmitted from master device.
NodeMCU I2C with Arduino IDE
I2C (Inter-Integrated Circuit) is serial bus interface connection protocol. It is also
called as TWI (two wire interface) since it uses only two wires for
communication. Those two wires are SDA (serial data) and SCL (serial clock).
I2C is acknowledgment based communication protocol i.e. transmitter checks for
an acknowledgment from the receiver after transmitting data to know whether
data is received by receiver successfully.
I2Cworks in two modes namely,

 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

NodeMCU Arduino I2C interface

Arduino Sketch for NodeMCU (Master I2C Device)


#include <Wire.h>

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

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


while(Wire.available()){
char c = Wire.read();
Serial.print(c);
}
Serial.println();
delay(1000);
}

Arduino Sketch for Arduino Uno (Slave I2C Device)


#include <Wire.h>

void setup() {
Wire.begin(8);
/* join i2c bus with address 8 */
Wire.onReceive(receiveEvent); /* register receive event */
Wire.onRequest(requestEvent); /* register request event */

Serial.begin(9600); /* start serial for debug */


}

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

Serial.print(c); /* print the character */


}
Serial.println();
/* to newline */
}

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

Output window of serial monitor at Master device (NodeMCU)


HTTP Client on NodeMCU with Arduino IDE
HTTP (Hypertext Transfer Protocol) is a standard Application protocol which
functions as request-response protocol between client and server.
HTTP client helps sending HTTP requests and receiving HTTP responses from
HTTP server.
It is widely used in IoT based embedded applications like Home Automation,
vehicle engine parameter monitoring remotely for analysis, etc.
NodeMCU is an open source IoT platform. It is a firmware which runs on ESP8266
Wi-Fi SoC from Espressif Systems. It has on board wi-fi available through which
IoT applications becomes easy to build.
Example
Let’s write a C/C++ based Arduino sketch for NodeMCU as an HTTP Client and
GET/POST the data from/to the thingspeak server.
Here, we are using Thingspeak server for HTTP Client demo purpose.
Thingspeak is an open IOT platform where anyone can visualize and analyze live
data from their sensor devices. Also, we can perform data analysis on data posted
by remote devices with Matlab code in Thingspeak. To learn more about
Thingspeak refer link
https://thingspeak.com/pages/learn_more
Just sign up and create channel.We have below channel and write key on
Thingspeak for data send and receive.

 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.

ArduinoSketch for HTTP Client Get

#include <ESP8266WiFi.h>

/*Put your SSID & Password*/


const char* ssid = "ssid"; // Enter SSID here
const char* password = "password"; //Enter Password
here

const char* server = "api.thingspeak.com";

/* Set GET link with channel ID */


const char* _getLink = "http://api.thingspeak.com/channels/309236/feeds/last.t
xt";

WiFiClient client;

void setup() {
Serial.begin(9600);
delay(1000);

Serial.println("Connecting to ");
Serial.println(ssid);

//connect to your local wi-fi network


WiFi.begin(ssid, password);

//check wi-fi is connected to wi-fi network


while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}

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

Output Window for HTTP Get


Below is the Arduino serial monitor window which shows last updated data
received from thingspeak server.

Arduino Sketch for HTTP Client Post

#include <ESP8266WiFi.h>

String apiKey = "1EYZIS5OCRJSKZHG"; gspeak//


API
replace
key, with your channel’s thin
/*Put your SSID & Password*/
const char* ssid = "ssid"; // Enter SSID here
const char* password = "password"; // Enter Password here

const char* server = "api.thingspeak.com";


int Sample;

WiFiClient client;

void setup() {
Serial.begin(9600);
delay(1000);

Serial.println("Connecting to ");
Serial.println(ssid);

//connect to your local wi-fi network


WiFi.begin(ssid, password);

//check wi-fi is connected to wi-fi network


while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}

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

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
}
client.stop();

Serial.println("Waiting…"); // thingspeak needs minimum 15 sec delay betwe


en updates

delay(20000);
}

Output Window for HTTP Post


Below is the output window of counts at thingspeak server.
HTTP Server on NodeMCU with Arduino IDE
The Hypertext Transfer Protocol (HTTP) is standard application layer protocol
which functions as a request response protocol in between server and client.
It is widely used in IoT (Internet of Things) embedded applications, where every
sensor is connected to a server and we have access to control them over the
internet.
NodeMCU has Wi-Fi functionality available on board. With this Wi-Fi functionality
NodeMCU can connect to any wi-fi network as client or it can create a network to
which other wi-fi enabled devices can connect.

NodeMCU as HTTP Server using Wi-Fi AP mode


NodeMCU wi-fi has Access Point (AP) mode through which it can create Wireless
LAN to which any wi-fi enabled device can connect as shown in below figure.
NodeMCU as HTTP Server using Wi-Fi AP mode
We can set SSID and Password for AP mode which will be used to authenticate
other devices while connecting to it.

NodeMCU as HTTP Server using Wi-Fi STA mode


NodeMCU has Station (STA) mode using which it can connect to existing wi-fi
network and can act as HTTP server with IP address assigned by that network.
NodeMCU as HTTP Server using Wi-Fi STA mode
NodeMCU gets IP from Wi-Fi router to which it is connected. With this IP address,
it can act as an HTTP server to which any wi-fi device can connect.

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.

HTML Code Snippet for LED ON

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

HTML Code Snippet for LED OFF

<!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"

Arduino Sketch for HTTP server with wi-fi AP mode

#include <ESP8266WiFi.h>
#include
<ESP8266WebServer.h>

/* Put your SSID & Password */


const char* ssid = "NodeMCU"; // Enter SSID here
const char* password = "12345678"; //Enter Password here

/* Put IP Address details */


IPAddress local_ip(192,168,2,1);
IPAddress gateway(192,168,2,1);
IPAddress
subnet(255,255,255,0);
ESP8266WebServer server(80);

uint8_t LEDpin = D2;


bool LEDstatus = LOW;

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

String SendHTML(uint8_t led){


String ptr = "<!DOCTYPE html>\n";
ptr +="<html>\n";
ptr +="<head>\n";
ptr +="<title>LED Control</title>\n";
ptr +="</head>\n";
ptr +="<body>\n";
ptr +="<h1>LED</h1>\n";
ptr +="<p>Click to switch LED on and off.</p>\n";
ptr +="<form method=\"get\">\n";
if(led)
ptr +="<input type=\"button\" value=\"LED OFF\" onclick=\"window.location.h
ref='/ledoff'\">\n";
else
ptr +="<input type=\"button\" value=\"LED ON\"
onclick=\"window.location.hr ef='/ledon'\">\n";
ptr +="</form>\n";
ptr +="</body>\
n"; ptr
+="</html>\n";
return ptr;

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.

Arduino Sketch for HTTP server with wi-fi STA mode

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

/*Put your SSID & Password*/


const char* ssid = "ssid"; // Enter SSID here
const char* password = "password"; //Enter Password here

ESP8266WebServer server(80);

uint8_t LEDpin = D2;


bool LEDstatus = LOW;

void setup() {
Serial.begin(9600);
delay(100);
pinMode(LEDpin, OUTPUT);

Serial.println("Connecting to ");
Serial.println(ssid);

//connect to your local wi-fi network


WiFi.begin(ssid, password);

//check wi-fi is connected to wi-fi network


while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: "); Serial.println(WiFi.localIP());
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");
}

String SendHTML(uint8_t led){


String ptr = "<!DOCTYPE html>\n";
ptr +="<html>\n";
ptr +="<head>\n";
ptr +="<title>LED Control</title>\n";
ptr +="</head>\n";
ptr +="<body>\n";
ptr +="<h1>LED</h1>\n";
ptr +="<p>Click to switch LED on and off.</p>\n";
ptr +="<form method=\"get\">\n";
if(led)
ptr +="<input type=\"button\" value=\"LED OFF\" onclick=\"window.location.h
ref='/ledoff'\">\n";
else
ptr +="<input type=\"button\" value=\"LED ON\" onclick=\"window.location.hr
ef='/ledon'\">\n";
ptr +="</form>\n";
ptr +="</body>\n";
ptr +="</html>\n";
return ptr;
}

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.

 It is quicker (faster) than other request-response based APIs like HTTP.


 It is developed on the base of TCP/IP protocol.
 It allows remote location devices to connect, subscribe, publish etc. to a
specific topic on the server with the help of message broker.
 MQTT Broker/Message broker is a module in between the sender and the
receiver. It is an element for message validation, transformation and
routing.
 The broker is responsible for distributing messages to the interested clients
(subscribed clients) of their interested topic.

For example, if temperature sensor publishes the temperature data (message) on


the topic “temperature” then interested clients who have subscribed to
“temperature” topic get that published temperature data as shown in above
figure.
MQTT is widely used in IoT (Internet of Things) embedded applications, where
every sensor is connected to a server and we have access to control them over the
internet.
NodeMCU is an open source IoT platform. It is a firmware which runs on ESP8266
Wi-Fi SoC from Espressif Systems. It has on board wi-fi available through which
IoT applications becomes easy to build.
The MQTT Client module of NodeMCU is as according to version 3.1.1 of the
MQTT protocol. Make sure that your broker supports and is correctly configured
for version 3.1.1. let’s see the functions used for MQTT on NodeMCU.
MQTT Packet Formation
MQTT uses many packet formats that used to connect to the server and subscribe
or publish to the topic on the server.
Refer below link for MQTT OASIS standard. It will help to understand MQTT packet
formations.
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-
os.html#_Toc398718027

Example
Let’s write Arduino program to configure NodeMCU as MQTT Client to

1. Control LED brightness from remote location and


2. Sending voltage across POT(Potentiometer) in digital form to remote
location from Adafruit dashboard.

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

Install required libraries


First refer Getting Started with NodeMCU using Arduino IDE if you are not
installed NodeMCU board packages in Arduino IDE.
Here we are using Adafruit libraries for above example. We will need to install
the Adafruit IO, Adafruit MQTT, and ArduinoHttpClient libraries using the
Arduino Library Manager.

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

Arduino Sketch for MQTT Client


/*****************************************
Adafruit MQTT Library ESP8266 Example**********
https://github.com/esp8266/Arduino
Must use ESP8266 Arduino
& Feather
from:
Works great with Adafruit's Huzzah ESP
---->
----> https://www.adafruit.com/product/2471
https://
board
products
Adafruitfrom Adafruit!
invests and resources
time and open-source hardware
providing thisbyopen
purchasingde,
source MIT license, all text abo
please support
****************************************************/
co
Adafruit
#include
Written<ESP8266WiFi.h> #include
by Tony DiCola for Adafruit"Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h"
Industries.
/************************* WiFi Access Point *********************************/

#define WLAN_SSID "...your SSID..."


#define WLAN_PASS "...your
password..."

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER "io.adafruit.com"


#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "...your AIO username (see
https://accounts.adafruit.c om)..."
#define AIO_KEY "...your AIO key..."

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.


WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

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

/****************************** Feeds ***************************************/

// Setup a feed called 'potValue' for publishing.


// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish potValue = Adafruit_MQTT_Publish(&mqtt, AIO_USERNA
ME "/feeds/potValue");
// Setup a feed called 'ledBrightness' for subscribing to changes.
Adafruit_MQTT_Subscribe ledBrightness = Adafruit_MQTT_Subscribe(&mqtt, AIO_
USERNAME "/feeds/ledBrightness");

/*************************** Sketch Code ************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration


// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

uint8_t ledPin = D6;


uint16_t potAdcValue = 0;
uint16_t ledBrightValue = 0;

void setup() {
Serial.begin(9600);
delay(10);

Serial.println(F("Adafruit MQTT demo"));

// Connect to WiFi access point.


Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

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

// Setup MQTT subscription for ledBrightness feed.


mqtt.subscribe(&ledBrightness);
}

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

// this is our 'wait for incoming subscription packets' busy subloop


// try to spend your time here

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

// Now we can publish stuff!


uint16_t AdcValue = analogRead(A0);
if((AdcValue > (potAdcValue + 7)) || (AdcValue < (potAdcValue - 7))){
potAdcValue = AdcValue;
Serial.print(F("Sending pot val "));
Serial.print(potAdcValue);
Serial.print("...");
if (! potValue.publish(potAdcValue)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
}
// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
/*
if(! mqtt.ping())
mqtt.disconnect();
}{
*/
}

// Function to connect and reconnect as necessary to the MQTT server.


// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;

// Stop if already connected.


if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

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

X---------- The End------------X

You might also like