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

Unit 4

The document provides an introduction to Python, highlighting its features, versions, and installation process. It also discusses various IoT tools and devices, detailing their functionalities and applications in IoT development. Key tools mentioned include Arduino, Node-RED, and Eclipse IoT, which facilitate the creation and management of IoT applications.

Uploaded by

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

Unit 4

The document provides an introduction to Python, highlighting its features, versions, and installation process. It also discusses various IoT tools and devices, detailing their functionalities and applications in IoT development. Key tools mentioned include Arduino, Node-RED, and Eclipse IoT, which facilitate the creation and management of IoT applications.

Uploaded by

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

ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

Introduction to Python
Python is a widely used general-purpose, high level programming language. It was initially designed by
Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for
emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.

There are two major Python versions- Python 2 and Python 3.

• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new features.

Beginning with Python programming:

1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. There
are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ or http://codepad.org/
that can be used to start Python without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/

2) Writing first program:

# Script Begins

Statement1 Statement2

Statement3

# Script Ends

Why to use Python:


CEC368 IOT BASED SYSTEMS DESIGN
ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY
The following are the primary factors to use python in day-to-day life:

1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple inheritance.

2. Indentation:Indentation is one of the greatest feature in python


3. It‟s free (open source)
Downloading python and installing python is free and easy

4. It‟s Powerful
• Dynamic typing
• Built-in types and tools
• Library utilities
• Third party utilities (e.g. Numeric, NumPy, sciPy)
• Automatic memory management
5. It‟s Portable
• Python runs virtually every major platform used today
• As long as you have a compaitable python interpreter installed, python programs will run
in exactly the same manner, irrespective of platform.

6. It‟s easy to use and learn


• No intermediate compile
• Python Programs are compiled automatically to an intermediate form called byte code,
which the interpreter then reads.

• This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages. Structure and syntax are pretty intuitive and
easy to grasp.

7. Interpreted Language
Python is processed at runtime by python Interpreter

8. Interactive Programming Language


Users can interact with the python interpreter directly for writing the programs

9. Straight forward syntax


CEC368 IOT BASED SYSTEMS DESIGN
ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY
The formation of python syntax is simple and straight forward which also makes it popular.

Installation:

There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)

Working with Python

Python Code Execution:

Python‟s traditional runtime execution model: Source code you type is translated to byte code, which is then
run by the Python Virtual Machine (PVM). Your code is automatically compiled, but then it is interpreted.

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY
Source Byte code Runtime

m.py m.pyc

PVM

Source code extension is .py

Byte code extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:

• Interactive Mode

• Script Mode

Running Python in interactive mode:

Without passing python script file to the interpreter, directly execute code to Python prompt. Once you‟re
inside the python interpreter, then you can start.

>>> print("hello world") hello world


# Relevant output is displayed on subsequent lines without the >>> symbol

>>> x=[0,1,2]

# Quantities stored in memory are not displayed by default. >>> x


#If a quantity is stored in memory, typing its name will display it. [0, 1, 2]
>>> 2+3

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to
indicate that it is ready. If the programmer types 2+6, the interpreter replies 8.

Running Python in script mode:

Alternatively, programmers can store Python script source code in a file with the .py extension,
and use the interpreter to execute the contents of the file. To execute the script by the interpreter, you have to
tell the interpreter the name of the file. For example, if you have a script name MyFile.py and you're working on
Unix, to run the script you have to type:
python MyFile.py

Working with the interactive mode is better when Python programmers deal with small pieces of code as you
can type and execute them immediately, but when the code is more than 2-4 lines, using the script for coding
can help to modify and use the code in future.

Example:

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

Introduction to Different IoT Tools

IoT development means combining hardware parts and software programs in such a way that the
final product could monitor specific values, collect and transfer data, analyze given data and
cause the physical device to act correspondingly. Creating such systems is a true challenge.

Moreover, the Internet of Things has already been transformed into an industry in its own right,
so the need for reliable and comprehensive developer toolkits has also increased. IoT
development tools needed to create complex applications are represented by IoT hardware
devices (boards, SoM, SoC, sensors, gateways, trackers, and more), IoT app development
platforms, IoT operating systems (e.g., Embedded Linux) and programming languages.

IoT Tools and Devices

The 15 most popular tools currently used for IoT projects are

 Arduino

 Flutter

 Kinoma

 Tessel 2

 M2MLabs Mainspring

 Raspberry Pi OS (ex. Raspbian)

 Node-RED

 Eclipse IoT

 SiteWhere

 DeviceHive

 Home Assistant

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

 OpenRemote

 ThingsBoard

 MilesightDeviceHub

 Zetta

1. Arduino

Arduino is the leading company on the IoT market that produces electronic devices and software
for them. Arduino hardware offerings include microcontroller boards, modules, shields and kits.
Hardware specifications are suitable for creating various projects, such as robotics and home
automation.

Software products are represented by:

Arduino IDE — an open-source prototyping platform, which can be used to easily write code
compatible with any Arduino board.

Arduino Cloud — a single platform that enables the wireless communication of IoT devices, as
well as their remote control and data collection.

IoT Cloud Remote — an application for creating dashboards to control cloud-connected devices.

Web Editor — an application for coding from a browser.

2. Flutter

Another hardware product for IoT solutions is Flutter — a programmable processor core. The
board is based on Arduino, has a powerful ARM processor, built-in battery charging and a
security chip. A long-range wireless transmitter makes this board the perfect fit for wireless
networks of sensors.

Flutter offers:

Basic control module,Pro control module,Complete kits (Quick Start Kit, Vehicle Control Kits)

accessory boards (the Bluetooth adapter, the Breakout, the Remote Control, the Explorer),

a solar panel, a cylindrical battery and other accessories.

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

3. Kinoma

A group of software engineers from Marvell Technology, Inc., a leading manufacturer of


memory devices, microcontrollers, telecom equipment and semiconductor devices, has
developed a line of open-source Kinoma software and hardware products for the Internet of
Things and embedded solutions.

Kinoma Create — a hardware platform for prototyping IoT devices. It’s powered by JavaScript
and has an integrated SD card, speaker, microphone, Bluetooth and Wi-Fi. It enables the
interaction of devices with cloud platforms via the WebSocket internet protocol.

Kinoma Studio — an integrated development environment (IDE) that provides the hardware
simulator and sensor library, allowing developers to create robust applications.

Kinoma Connect — an application for Android and iOS supporting IoT devices.

4. Tessel 2

To create connected devices, you can also use Tessel 2 — a programmable microcontroller
supporting JavaScript, Node.js libraries and other languages. It runs Linux and provides access to
many NPM modules with all their capabilities.

Tessel 2 can be extended by external hardware (sensors, peripherals) due to a built-in


module and USB ports. It also provides Wi-Fi and Ethernet connectivity, a MediaTek router,
64MB of RAM and 32MB of Flash. Convenient command-line tools simplify prototyping.

5. M2MLabs Mainspring

The development of machine-to-machine applications is easy with the M2MLabs Mainspring


framework. This open-source Java-based framework is widely used for building fleet
management apps and remote monitoring projects. It enables flexible device configuration and
supports the reliable connection between machines. App prototyping is very quick with
M2MLabs Mainspring. Moreover, it ensures long-term data storage and retrieval thanks to a
scalable Apache Cassandra database.

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

6. Raspberry Pi OS (ex. Raspbian)

Raspberry Pi OS, formerly known as Raspbian, is the official operating system for the Raspberry
Pi hardware. A 32-bit version is available currently, with a 64-bit version in active development.
This is a free, Debian-based system. Raspberry includes basic programs and utilities to make the
hardware run, but it also compiles thousands of packages and pre-compiled software for easy
installation.

7. Node-RED

Node-RED is a free programming tool based on Node.js and designed to integrate distributed
IoT hardware and software systems and automate their interaction. It works primarily in Linux
environments but can be installed on Android and Windows as well (you’ll only need a Linux
subsystem for WIndows). Node-RED offers out-of-the-box repositories, interfaces for
connecting to MQTT, logic sets and format parsers, as well as the ability to write custom
components.

8. Eclipse IoT

A wide range of open-source projects for IoT development is gathered under the Eclipse
umbrella. They include software development platforms, frameworks, services, standards, tools
for building digital twins, fog computing and edge computing solutions, and many more. Eclipse
IoT projects focus on working with the Lua programming language, which is considered a good
fit for Internet of Things projects.

9. SiteWhere

SiteWhere is an open-source multi-tenant platform for building, deploying and supporting IoT
applications at the industrial level. The platform uses technologies such as the Docker
framework, Kubernetes, microservices and Apache Kafka. SiteWhere facilitates big data
transfer, storage, processing and integration, device management and event handling. You can
deploy SitePlatform locally or to the cloud platforms, including Azure, AWS, GCP.

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

10. DeviceHive

The DeviceHive platform covers end-to-end IoT services, including:

 Prototyping and production at scale

 Connection of any devices via MQTT, REST API, WebSockets

 Integration with cloud platforms and third-party systems

 Real-time data analytics using the best data solutions such as Apache Spark and Kafka.

DeviceHive offers public, private, or hybrid cloud deployment models, a container-based


architecture managed by Kubernetes, and support to libraries written in various languages. You
can use this scalable and device-agnostic platform for implementing IoT projects of any
complexity.

11. Home Assistant

Home Assistant is a comprehensive home automation software system. This single center
integrates smart home devices, providing local control and security. Home Assistant offers
convenient mobile applications that enable the remote management of your devices and send
notifications if something goes wrong. You can also extend the functionality of this tool by
integrating it with additional apps.

12. OpenRemote

Open Remote is a platform you can use to create and manage IoT monitoring applications. The
primary domains leveraging the tool are smart city and mobility, energy management and asset
management.

OpenRemote is offered under an open-source or a commercial license. The team behind it


also provides a range of services from concept development to implementation and product
maintenance.

13. Things Board

The Things Board IoT platform uses MQTT, CoAP and HTTP protocols to connect devices and
handle data from them. Out-of-the-box configurable dashboards, charts, maps and widgets

CEC368 IOT BASED SYSTEMS DESIGN


ROHINI COLLEGE OF ENGINEERNG AND TECHNOLOGY

provide you with robust real-time visualization of your data, which you can share with partners.
In addition, you can create custom widgets using the built-in editor.

Things Board Rule Engine allows you to create rule chains and event-based workflows for the
perfect match with your use case requirements. The platform can support multiple tenants and
millions of devices. Cloud and on-prem deployment is available. You can choose a monolithic
architecture for a small project or a microservices architecture for a highly scalable project.

14. MilesightDeviceHub

Milesight is a leading global provider of surveillance cameras, AI systems, IoT hardware and
software products. DeviceHub is among the company’s key software solutions. This is a
connectivity suite that enables the deployment of multiple devices, their real-time monitoring
and remote upgrading. With DeviceHub, you get comprehensive reports on monitored devices
and take insightful actions. Both the cloud and on-premises versions of the platform are
available.

15. Zetta

Zetta is a platform for designing APIs for IoT devices. The platform is based on Node.js and
combines reactive programming, WebSockets and REST APIs. A Zetta server can run in the
cloud or locally on hardware such as Raspberry Pi or Intel Edison.

The development process is simplified due to abstractions and direct access to protocols
and conventions. Visualization tools ensure the continuous monitoring of device behavior and
timely reaction to abnormalities. With Zetta, you can create data-intensive mobile, device and
cloud applications and integrate smaller systems into one coherent system.

CEC368 IOT BASED SYSTEMS DESIGN


Rohini College of Engineering and Technology Department of ECE

Developing applications through IoT tools


Here are some top-class IoT development tools that can
be applied by both developers and for all those who want
to pursue IoT as a hobby.

1. Eclipse IoT:

As an IoT developer, if you are intended to build IoT


devices, Cloud platforms, and Gateways, then Eclipse
IoT can be your top chance. Acknowledged as a
collaboration of numerous companies and individuals
who are striving towards the development and
demonstration of IoT open technologies, Eclipse IoT can
make all your IoT desires come true.

Empowering you to improve, promote and adopt open


source IoT technologies, Eclipse IoT is an instrument that
can assist you to gain technical expertise. Just look into
the huge assembly of services and outlines delivered by
the Eclipse team and you are all incorporated.

2. Node-RED:

Node-RED is an uncomplicated open-source


visualization tool for the combination of devices for the
Internet of Things. The tool, developed by IBM’s
Emerging Technology department, enables you to link,
hardware, an API or online service. Node-RED renders a
user-friendly interface for developers to connect devices
efficiently and swiftly. Node-RED is developed on
node.js, a server-side JavaScript platform extensively
Rohini College of Engineering and Technology Department of ECE

used in IoT projects and also can be operated in the


cloud.

Node-RED could be applied, for example, for the creation


of a chat application using the Bluemix environment, the
IBM cloud platform to develop, manage and execute
applications of all kinds.

3. Arduino:

If you are looking to build a computer that can sense and


execute a better command over the real world when
associated with your normal stand-alone computer, the
Arduino can be your smart choice. Offering a
comprehensive mixture of IoT hardware and software,
Arduino is an open-source prototyping and simple-to-use
IoT platform. Arduino runs through a set of hardware
stipulations that can be implemented to interactive
electronics. The software of Arduino appears in the form
of the Arduino programming language and Integrated
Development Environment (IDE).

4. Tessel 2:

This is a hardware provider that can be utilized to build


fundamental IoT solutions and prototypes. Tessel 2 lends
a helping hand through its copious sensors and modules.
This is a board which can handle up to a dozen modules
including the RFID, camera, GPS and the accelerometer.

All those Java developers who are expert with Node.JS


can utilize this device as Tessel can be processed using
Node.JS. This way, Tessel can be managed to churn out
Rohini College of Engineering and Technology Department of ECE

a host of server and hardware firmware IoT solutions.


Marked as a robust IoT platform, you can leverage all the
libraries of Node.JS to reveal a host of devices; within a
concern of minutes. It occurs with two processors, the
Tessel hardware makes use of a 580MHz MediaTek
MT7620n and 48MHz Atmel SAMD21 coprocessor.
While one can be utilized to run your firmware
applications at an accelerated speed, the other gains its
use in executing better input/output control and the
efficient administration of power.

5. Kinomo Create:

It is a device which can join two devices without the


widespread knowledge of JavaScript. Kinoma Create
comprises of everything which is necessary for growing
small IoT applications like connecting light, temperature
or movement sensors for a special purpose with mobile
notifications in case of any modifications. It has been
extensively used for developing a synthesizer, a camera
trap which takes a photo if an object disturbs the laser
beam and a programmed alarm signal for warning
individuals in case of any circumstances.

6. OpenSCADA:

This tool is a portion of the SCADA project by Eclipse IoT


industry groups. It is independent of any platform and is
known for security and extensibility along with a
contemporary design. OpenSCADA also manages to edit
and debugging and appears with front-end applications,
back-end applications, libraries, configuration tools, and
interface applications. Its diverse tools can be
Rohini College of Engineering and Technology Department of ECE

consolidated with the evolution of high-level IoT


applications. Unlike other IDEs, OpenSCADA supports
several programming languages and consists of sub-
projects like Atlantis, Utgard, Orilla and so on.

7. Raspbian:

This IoT IDE is designed for Raspberry Pi board by IoT


tech enthusiasts. With over 35,000 packages and various
examples accompanying accelerated installation with the
use of pre-compiled software makes it an essential IoT
development tools. Frequently, it is considered as an
excellent tool for Raspberry Pi for IoT app development.
Another best part regarding this tool is that it is below
constant development and has extended the reach for
computing so that users can obtain supreme benefits.

8. Device Hive:

Device Hive was launched in 2012 which is a free open


source machine to machine (M2M) communication
framework. It is recognized as one of the most favored
IoT app development platforms. It is usually a cloud-
based API that you can manage remotely without the lack
of network configuration. The same implies to the
libraries, gateways and administration protocols. Often, it
is used for security, automation, smart home tech, and
sensors. Additionally, it also holds a dynamic community
and myriads of online resources accessible to help you
out.

9. PlatformIO:
Rohini College of Engineering and Technology Department of ECE

Succeeding in the list of top IoT development tools and


platforms in PlatformIO which is a cross-platform IoT
development environment. This platform comes with a
build system, held by a library manager and IDE. You
have an option to port the IDE on the head of the Atom
editor or you can go forward and install it as a plug-in.

The best portion of PlatformIO is that it is compatible with


more than 200 boards. Coming with an excellent
debugging combination, PlatformIO is important of a
serial port monitor. All those who are applying PlatformIO
consistently reveal one feeling and that is – “ PlatformIO
speeds up the development process of an IoT application,
equipping us to deliver IoT solutions in record time”.

10. IBM Watson:

Last in the listing of top IoT development tools, but surely


not the least is IBM Watson, an API that enables you to
append a host of cognitive computing highlights to your
IoT applications. This is an innovative tool that can further
be applied to predict the future.

Interpreting the tasks of IoT developers, IBM Watson


through its infinite services serves to reveal chatbots
which can understand the original language. These
chatbots can later be expanded on to messaging
platforms and websites which can be observed on several
devices. It is by IBM Watson that IoT developers can
successfully and quickly build cognitive search and
content analytics engines.

Summary:
Rohini College of Engineering and Technology Department of ECE

We live in the internet era where we can get anything and


everything when we require it. This is where the Internet
of Things comes in picture. It has the capacities to
combine different devices all concurrently which can
make human lives much easier. Because of this, the
exponential growth in IoT devices is recognized making it
an indispensable technology of the future. By these
innovative tools, developers and all those who fascinate
IoT can stay ahead of their times by growing a
contributing part of the latest technology standard shift.
Rohini College of Engineering and Technology Department of ECE

Embedded Devices (System) in (IoT)


It is essential to know about the embedded devices while learning the IoT or building
the projects on IoT. The embedded devices are the objects that build the unique
computing system. These systems may or may not connect to the Internet.

An embedded device system generally runs as a single application. However, these


devices can connect through the internet connection, and able communicate through
other network devices.

Embedded System Hardware


The embedded system can be of type microcontroller or type microprocessor. Both of
these types contain an integrated circuit (IC).

The essential component of the embedded system is a RISC family microcontroller like
Motorola 68HC11, PIC 16F84, Atmel 8051 and many more. The most important factor
that differentiates these microcontrollers with the microprocessor like 8085 is their
internal read and writable memory. The essential embedded device components and
system architecture are specified below.
Rohini College of Engineering and Technology Department of ECE

Fig: Basic Embedded System

Embedded System Software


The embedded system that uses the devices for the operating system is based on the
language platform, mainly where the real-time operation would be performed.
Manufacturers build embedded software in electronics, e.g., cars, telephones, modems,
appliances, etc. The embedded system software can be as simple as lighting controls
running using an 8-bit microcontroller. It can also be complicated software for missiles,
process control systems, airplanes etc.
Rohini College of Engineering and Technology Department of ECE

Implementation Of Internet of Things with


Python
Generally, prototypes or real-life Internet of Things (IoT) systems have to be designed
and developed swiftly and competently. Whenever this occurs, two activities instantly
come to life: One is to program the IoT devices, and another is to organize a backend
to interact with these devices.

In both activities, we can utilize the Python programming language for their
development. Or we can utilize a functional and practical edition of MicroPython in
order to work on devices with small computing resources, and accordingly, at a very
low price.

In the following tutorial, we will understand the use of Python in programming Internet
of Things (IoT) devices and create a backend for them to work.

But before we get to that, let us briefly discuss the importance of IoT.

Understand the importance of the Internet of Things


The term "Internet of Things" was first coined in the year 1999 by Kevin Ashton. Ever
since the importance and scale of IoT have exploded, one of the chief indicators is that
the market size of the IoT was $151 billion in 2018, with a steady increment year after
year. As per the predictions of marketers, the IoT market could cross the $561 billion
mark by 2022.

Back in the day, we could explain IoT with examples as shown below:

"We can utilize the phone to turn a light bulb on and off in the room."

Nowadays, hardly anyone would be amazed by a smart electricity meter that transmits
readings of the consumption of the electricity, uploads that information to the cloud,
and produces monthly bills sent directly to the e-mail.

IoT is increasingly utilized across industries in order to streamline processes and make
them more efficient. For instance, manufacturing production lines and agriculture are
great examples of various industries taking benefit of the different features of IoT. In
the particular scenario of agriculture, IoT helps in coordinating harvesters with trucks
that have elevators to handle grains efficiently.
Rohini College of Engineering and Technology Department of ECE

Why use Python in the Internet of Things?


For many developers, Python is considered as the language of preference in the
market. It is simple to learn, has clean syntax, and has a large online community
supporting it. Python becomes a great choice when it comes to IoT. We can either use
it for the backend side of development or the software development of devices.
Moreover, Python is available to work on Linux devices, and we can make use of
MicroPython for microcontrollers.

Python is the coding language that we can use to reduce the volume of data that we
need to deal with, accessible in the cloud. Python recognizes the needs regardless of
whether we create the IoT project from scratch or interact with actuators, sensors, and
accessories.

Some of the many benefits of working with Python for IoT devices are a large number
of libraries for all types of platforms and the speed it offers at which we can develop
the code.

Python is a great ally for developing device prototypes. Even if we rewrite some of the
scripts while producing to C, C++ or Java to improve performance, the system will
generally function perfectly in Python.

What are the best solutions for IoT in Python?


Some of the best solutions for IoT in the Python programming language are as follows:

1. Python on Raspberry Pi
2. Python on PyBoard
3. ESP8266, ESP32 with Micropython

We will discuss each solution in brief.

Python on Raspberry Pi
The primary objective of running Python on an IoT device that pops up in mind is
grabbing the Raspberry Pi from the table. Python is pre-installed in the operating
system, and the only objective left for us is to write the coding script.

In this scenario, we can control the I/O ports on the expansion bar of the Raspberry Pi.
Fortunately, the board supports wireless communication (Bluetooth and WiFi) and
Ethernet. We can also connect a monitor to the HDMI output, a specialized 3.2"
320x240 TFT LCD, or a low energy consumption E-Ink 2.13" 250x122 display for
Raspberry Pi.
Rohini College of Engineering and Technology Department of ECE

AD

There are controllers available in a large variety of computing power and budgets. We
can choose these controllers for the IoT system - ranging from the fast Raspberry Pi 4
Model B 8 GB to the smallest Raspberry Pi Zero, all supporting the Python
programming language. In case of necessity, we can install the earlier version of Python
2.7 for past compatibility.

Let us consider the following snippet of Python code where we have used the GPIO
Zero library in order to control the I/O ports.

Example:

1. # importing the required modules


2. from gpiozero import Button
3. from time import sleep
4.
5. # creating an object of Button
6. the_button = Button(2)
7.
8. # using the if-else statement
9. while True:
10. if the_button.is_pressed:
11. print("Button Pressed")
12. else:
13. print("Button Released")
14. sleep(1)

Explanation:

The above example demonstrates the receiving and processing of the signals by
pressing the button on the second pin at the moment of release.

AD

The benefits of utilizing this approach are the availability of a large variety of
development utilities, libraries and communications for the most complex devices
based on Raspberry Pi involving video processing from cameras.

Python on PyBoard
Another great solution for Python in IoT devices is the PyBoard with an STM32F405RG
microcontroller.
Rohini College of Engineering and Technology Department of ECE

The PyBoard is considered a compact as well as a powerful electronics development


board. It works on MicroPython. The PyBoard connects to the PC through USB,
providing us with a USB flash drive to store the Python scripts and a serial Python
prompt (a REPL) for instant programming. This works with Windows, MacOS, and Linux.

PyBoard executes MicroPython, which is a lightweight implementation of the standard


CPython interpreter. The official documentation also says: "MicroPython is a lean and
efficient implementation of the Python 3 programming language that includes a small
subset of the Python standard library and is optimized to run on microcontrollers and
in constrained environments. The MicroPythonpyboard is a compact electronic circuit
board that runs MicroPython on the bare metal, giving you a low-level Python
operating system that can be used to control all kinds of electronic projects.
MicroPython is packed full of advanced features such as an interactive prompt,
arbitrary precision integers, closures, list comprehension, generators, exception
handling and more. Yet it is compact enough to fit and run within just 256k of code
space and 16k of RAM."

MicroPython is an entire rewrite of the Python (version 3.4) programming language to


fit and execute on a microcontroller. It involves various optimization for efficiency and
consumes quite less RAM.

MicroPython executes bare-metal on the PyBoard, necessarily providing us with an


Operating System based on Python. The in-built pyb module consists of functions and
classes in order to control the peripherals available on the board, like I2C, UART, ADC,
DAC, and SPI.

The board's dimensions are impressive, taking up around two quarters, 33mm x 43mm
and weighing only 6 grams.

ESP8266, ESP32 with MicoPython


Another option could be using ESP8266 and ESP 32 to run Python. We have to create
a device based on the Internet of Things with low power consumption, great
capabilities, and integration with wireless Wi-Fi networks. More precisely, we can use
MicroPython.

Once we installed Python on the system, we can use the pip installer in the command
line in order to install the esptool module. The syntax for the same is shown below:

Syntax:

1. $ pip install esptool


Rohini College of Engineering and Technology Department of ECE

The installation procedure of the MicroPython is pretty easy. We can download the
firmware from the website and install it with the help of esptool, not forgetting to
format the board before installing it.

We can also use one of the IDEs used for developing with MircoPython. The complete
procedure of development is carried out on a working computer, and then it is
compiled and saved in the memory of an ESP8266 or ESP32 microcontroller.

Let us consider the following example to see how simple the script might look like:

Example:

1. # importing the required modules


2. from machine import Pin
3. import time
4.
5. # creating an object of Pin
6. ledPin = Pin(2, Pin.OUT)
7.
8. # using some functions
9. while True:
10. ledPin.on()
11. time.sleep(1)
12. ledPin.off()
13. time.sleep(1)

Explanation:

In the above snippet of code, we have imported the Pin module from
the machine library along with the time module. We have then created an object
of Pin and execute some functions on it.

MicroPython imposes many restrictions compared to regular Python; however, in


general, we can easily write the necessary functionality on the client-side and execute
it effectively on ESP microcontrollers. This option is relatively more cost-effective than
buying PyBoard.

AD

Understanding the use of Python in IoT Backend


Rohini College of Engineering and Technology Department of ECE

We can use Python as a Backend programming language for the Internet of Things in
many ways. Some of them are as follows:

MQTT protocol with Python


One of the most popular connection methods for IoT devices is MQTT, and it is a
protocol used for effective implementation with Python.

The MQTT protocol is a machine-to-machine (M2M)/Internet of Things connectivity


protocol designed as a highly lightweight publish/subscribe messaging transport. It is
used to connect to remote locations where a small code footprint is needed, and
network bandwidth is premium.

The Python client library called Eclipse Paho MQTT implements versions 3.1, 3.1.1,
and 5.0 of the MQTT protocol.

The code of the Poho library offers a client class that allows applications to link to an
MQTT broker in order to publish messages, subscribe to topics, and receive published
messages. It also delivers some helper functions to make things simpler in publishing
one-off messages to MQTT servers.

Moreover, this library supports Python 2.7.9 and above or 3.5 and above. The
integration of images with older 2.7 versions of Python is straightforward.

IoT backend on Flask in Python


We can also use the Flask microframework to write the backend for the IoT systems.
The Flask microframework is a quick and hassle-free tool that easily set up server-side
I/O information, and it is also packed with many functionalities that make work more
efficient.

We can start by deciding the requests we have to serve from the IoT devices. We then
have to set up the Flask microframework and write a block of code. The GET method
will then return information as per the request from the side of the client.

In several cases, we are best off focusing on the RESTful protocol while working with
the IoT devices. This allows us to simplify the exchange between the components of
the system and helps us to expand the system of exchanging information in the future.

Let us consider a task that has arisen as follows: Display information from IoT devices
on a web page. The Flask microframework will rescue us again with its core template
mechanism where we can design the required web page with the data display involving
graphics.
Rohini College of Engineering and Technology Department of ECE

The disadvantage of utilizing this method is the potential lack of starting the data
transfer from the server to the device. Thus, the IoT must periodically and
independently pull from the server. Rest easy, as there are keys to report this risk. We
can utilize web sockets or a Python library for Pushsafer. PushSafer is an easy and safe
way to send and receive push notifications in real-time to Android, iOS, and Windows
devices (mobile as well as desktop), including internet browsers such as Google
Chrome, Mozilla Firefox, Opera, and many more.

Microsoft Azure IoT backend in Python


Microsoft has released a new open-source extension for IoT to extend the capabilities
of Azure CLI 2.0. Azure CLI 2.0 involves commands to interact with the Azure Resource
Manager and endpoints of management.

For instance, we can utilize Azure CLI 2.0 to build an Azure Virtual Machine or IoT Hub.
The extension of CLI allows an Azure service to complement Azure CLI by providing
users access to additional capabilities specified to services.

The Extension of IoT offers programmers command-line access to the capabilities of


the IoT Edge, IoT Hub and IoT Hub Device Provisioning Service.

Azure CLI 2.0 allows instant management of resources of Azure IoT Hub, devices
provisioning services instances, and associated hubs. The new IoT extension enriches
Azure CLI 2.0 with features such as device management and all IoT Edge capabilities:

1. Azure CLI 2.0 IoT capabilities - Control Plane


2. Managing instances of IoT Hub, consumer - groups and jobs
3. Managing instances of device provisioning service, access-policies, Linked - hub
and certificates
4. New features for extensions - data plane
5. Managing device and edge module identities and their respective twin
definitions
6. Querying IoT Hub for details like device and module jobs, twins, and messaging
routing
7. Invoking methods of device and module
8. Generating SAS tokens and grabbing connection strings
9. Cloud-to-device and Device-to-cloud messaging
10. Device file uploading
11. Device simulation for testing
Rohini College of Engineering and Technology Department of ECE

Amazing hacks of Python


In this tutorial, we will learn how awesome a Python language is for coding. We will
discuss some of its amazing hacks, making Python the best among other languages.

Hacks of Python
Following are some amazingly cool hacks of Python that can make work easy for
users and developers:

1. List Comprehensions: It is the best and efficient technique for getting rid of writing
pointless lines of program.

List comprehension consists of the following parts:

Output expression
Input sequence
A member of the input sequence represented by a variable
The optional predicate parts.
Example:

import functools as FT

# First, filter odd numbers


list_1 = filter(lambda K : K % 2 == 1, range(10, 30))
print ("List: ", list(list_1))

# Then we will filter the odd square which is divisible by 5


list_1 = filter(lambda K : K % 5 == 0,
[K ** 2 for K in range(1, 11) if K % 2 == 1])
print ("ODD SQUARE WHICH IS DIVISIBLE BY 5: ", list(list_1))

# Here, we will filter negative numbers


list_1 = filter((lambda K : K < 0), range(-10, 10))
print ("Filter negative numbers: ", list(list_1))
Rohini College of Engineering and Technology Department of ECE

# Now, implement by using the max() function


print ("Maximum Number in the List: ")
print (FT.reduce(lambda S, T: S if (S > T) else T, [14, 11, 65, 110, 105]))
Output:

List: [11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
ODD SQUARE WHICH IS DIVISIBLE BY 5: [25]
Filter negative numbers: [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
Maximum Number in the List:
110
2. Printing a List: Lists are not printed according to our requirements; they are always
printed in unnecessary square brackets and single quotes. But in Python, we have a
solution for printing lists efficiently by using the join method of string. The "join
method" can turn the list into a string by classifying every item into a string and
connecting them with the string on which the join method is used.

Example:

# First declare the list:


ABC = ['LPG', 'WWF', 'XYZ', 'MPG']

# Then, we will print the list:


print ("The Simple List: ", ABC)

# HEre, we will Print the list by using join method


print ('The List by using join method: %s' % ', ' .join(ABC))

# we can directly apply Join Function on the List:


print ('Directly applying the join method: ', (", " .join(ABC)))
Output:

The Simple List: ['LPG', 'WWF', 'XYZ', 'MPG']


The List by using join method: LPG, WWF, XYZ, MPG
Directly applying the join method: LPG, WWF, XYZ, MPG
Rohini College of Engineering and Technology Department of ECE

3. Transpose a Matrix: In Python, a user can implement the matrix as a nested list,
which means a list inside a list. Every element of the list is treated as a row of the
matrix.

Example:

M_1 = [[5, 3], [1, 2], [9, 8]]


print ("Matrix 1: ")
for row in M_1 :

print (row)
rez_1 = [[M_1[K][L] for K in range(len(M_1))] for L in range(len(M_1[0]))]
print ("\n")
print ("Matrix 2: ")
for row in rez_1:

print (row)
Output:

Matrix 1:
[5, 3]
[1, 2]
[9, 8]

Matrix 2:
[5, 1, 9]
[3, 2, 8]
4. artition of List into "N" Groups: The users can use the iter() function as an iterator
over the sequence.

Example:

# First, we will Declare the list:


Rohini College of Engineering and Technology Department of ECE

LIST_1 = ['E_1', 'E_2', 'E_3', 'E_4', 'E_5', 'E_6']

partition_1 = list(zip (*[iter(LIST_1)] * 2))


print ("List after partitioning into different of groups of two elements: ", partition_1)
Output:

List after partitioning into different of groups of two elements: [('E_1', 'E_2'), ('E_3',
'E_4'), ('E_5', 'E_6')]
Explanation:

In the above code, we used "[iter(LIST_1)] * 2" which produced different groups
containing two elements of the 'LIST_1[]' list. That is, the lists of length two will be
generated using the elements from the first list.
AD

5. Print more than One Item of List simultaneously

Example:

list_1 = [11, 13, 15, 17]


list_2 = [12, 14, 16, 18]

# Here, we will use zip() function which will take 2 equal length list
# and then merge them together into pairs
for K, L in zip(list_1, list_2):
print (K, L)
Output:

11 12
13 14
15 16
17 18
6. Take the String as Input and Convert it into List:
Rohini College of Engineering and Technology Department of ECE

Example:
AD

# Reading a string from input as int format


# after splitting it's elements by white-spaces
print ("Input: ")
formatted_list_1 = list(map (int, input().split()))
print ("Output as Formatted list: ", formatted_list_1)
Output:

Input:
10 12 14 16 18 20 22
Output as Formatted list: [10, 12, 14, 16, 18, 20, 22]
7. Convert List of Lists into Single List:

Example:

# importing the itertools


import itertools as IT

# Declaring the list geek


LIST_1 = [[1, 2], [3, 4], [5, 6]]

# chain.from_iterable() function will return the


# elements of nested list
# and iterate it from first list
# of iterable till the last
# end of the list

list_2 = list(IT.chain.from_iterable(LIST_1))
print ("Iterated list of 'LIST_1': ", list_2)
Output:

Iterated list of 'LIST_1': [1, 2, 3, 4, 5, 6]


Rohini College of Engineering and Technology Department of ECE

8. Print the Repeated Characters: Suppose our task is to print the patterns like
"122333444455555666666". We can easily print this pattern in Python without using
for loop.

Example:

print ("1" + "2" * 2 + "3" * 3 + "4" * 4 + "5" * 5 + "6" * 6)


Output:

122333444455555666666
Rohini College of Engineering and Technology Department of ECE

Implementation of IoT with Raspberry Pi

What is Raspberry Pi?

Short for RPi, it is a credit-card-sized single-board computer built by


the Raspberry Pi Foundation in association with Broadcom in the United
Kingdom. It can do most of the things your typical desktop does, such as
handling spreadsheets, word-processing, and games.

Raspberry Pi also has the capacity to play videos in high-definition. It


can run several versions of Linux and is used to teach kids worldwide how
to program. In fact, that was one of the biggest reasons why the idea of
Raspberry Pi was conceived. But more on that later.

In addition, it has inputs and outputs for sensors so that you can attach
all sorts of hardware to it. The General Purpose Input/Output (GPIO) pins on
Raspberry Pi allow you to connect status lights, switches, analog signals,
and more. You can use C++ or Python to control the board to sense or control
devices attached to it.

Invented to stimulate the teaching of basic computer science in


schools, Raspberry Pi has since then been used in many applications,
including hobbyist projects, hardware platforms for electronics design,
embedded devices, and robotics.

Implementation of IoT with Raspberry Pi :

Internet of Things
Creating an interactive environment

Network of devices connected together

Sensor
Electronic element

Converts physical quantity into electrical signals

Can be analog or digital


Rohini College of Engineering and Technology Department of ECE

Actuator
Mechanical/Electro-mechanical device

Converts energy into motion

Mainly used to provide controlled motion to other components

System Overview
Sensor and actuator interfaced with Raspberry Pi

Read data from the sensor

Control the actuator according to the reading from the sensor

Connect the actuator to a device

Requirements
DHT Sensor

4.7K ohm resistor

Relay

Jumper wires

Raspberry Pi

Mini fan

DHT Sensor
Digital Humidity and Temperature Sensor (DHT)

PIN 1,2,3,4 (from left to right)

PIN 1-3.3V - 5V Power supply

PIN 2- Data

PIN 3- Null

PIN 4 - Ground
Rohini College of Engineering and Technology Department of ECE

Relay
Mechanical/electromechanical switch
3 output terminals (left to right)
NO (normal open)

Common

NC (normal close)

Temperature Dependent Auto Cooling System

Sensor interface with Raspberry Pi

Connct pin 1 of DHT sensor to the 3.3V pin of Raspberry Pi

Connect pin 2 of DHT sensor to any input pins of Raspberry Pi

Connect pin 4 of DHT sensor to the ground pin of the Raspberry Pi

Relay interface with Raspberry Pi


Connect the VCC pin of relay to the 5V supply pin of Raspberry Pi

Connect the GND (ground) pin of relay to the ground pin of Raspberry
Pi

Connect the input/signal pin of Relay to the assigned output pin of


Raspberry Pi

Adafruit provides a library to work with the DHT22 sensor

IoT uses of Raspberry Pi :

Raspberry Pi computers feature a set of General Purpose Input Output


(GPIO) pins that provide connections to external electronic devices and
therefore the development of IoT solutions. These GPIO pins can be
connected to external sensors using either jumper wires or a ribbon cable.
These subsequently connect the Pi to a breadboard (a solder-less, plug-and-
play electronics board), enabling various application possibilities.
Rohini College of Engineering and Technology Department of ECE

One such application is a Raspberry Pi IoT server. “With an in-built


quadcore processor, Raspberry Pi can serve as the ‘Internet Gateway’ for
IoT devices”, says Sanam Malhotra from Oodles AI. “Powered by a cloud
network, Pi acts as a web server for uploading and transiting sensor data on
IoT platforms. Custom code, an operating system, a Python library, and a
cloud network are all it takes to use Pi Computer as a web server.

“Businesses can easily run and control IoT applications like smart
home devices, weather stations, agricultural designs, and more using
Raspberry Pi”, she adds.

You might also like