Module 4: Developing IoTs
Introduction to Python
Python is a High-level programming language, Interpreted language, Object-oriented
language and General-purpose language. It was developed by Guido van Rossum (1991).
Key Features
o Easy to learn and read
o Platform independent
o Large library support
o Supports IoT, AI, ML, Web, Embedded systems
o Open source
Python Operators
Operators are used to perform operations on variables(operands).
Python provides the following operators:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
8. Unary operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations
Assignment Operators
Assignment operators are used to assign values to variables:
Comparison/Relational Operators
Comparison operators are used to compare two values:
It either returns True or False according to the condition.
Logical Operators
Logical operators are used to combine conditional statements
Operator Description Example Ex:
x=5
and True if both are true x and y
True if at least one is print(x > 3 and x < 4)
or x or y
true print(x > 3 or x < 4)
Inverts the Boolean print(not(x==5))
not value, returns False if not x
Output:
the result is True
False
True
False
Unary Operators
• Unary operators work with a single operand.
Example:
x=5
print(-x) # -5
• In Python, the unary operator is mostly used for negation (-).
Output: -5
Membership operators
They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the
value.
Bitwise operators
These operators act upon the individual bits (0 & 1) of their
operands.
It operates bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise Complements (~)
Bitwise Left shift (<<)
Bitwise Right shift (>>)
Identity operators
Identity operators are used to check if two values refer to the same
object in memory.
Decision making (or) conditional Statements
Decision making is required when we want to execute a code only if a
certain condition is satisfied.
Jumps from one part of the program to another depending on whether a
particular condition is satisfied or not.
1. The if statement
2. The if else statement
3. if...elif...else Statement
4. Nested if statements
if statement Nested if statement
num=int(input("Enter a number: "))
num = 3
if num>0: if(num>=0):
print(num, "is a positive number.") if(num<=30):
print("This is always printed.")
print(num,"is in the range 0-30")
if...else Statement
Determine the larger of two numbers Nested if-else statement
a= int(input(“Enter the value of a: “)) num = -3
b= int(input(“Enter the value of b: “)) if num >= 0:
if(a>b): if num == 0:
large=a print("The number is zero.")
else: else:
large=b
print(f"{num} is a positive number.")
print(“Large= ”,large)
else:
print(f"{num} is a negative number.")
if...elif...else Statement
a=int(input("enter numbers"))
b=int(input("enter numbers"))
c=int(input("enter numbers"))
if(a>b and a>c):
print(a,"is big")
elif b>c:
print(b,"is big")
else:
print(c,"is big")
Loops in Python
Python has two primitive loops
1. While
2. for
Examples:
2. num = int(input("Enter a number:
1. numbers = [6, 5, 3, 8]
"))
sum = 0
for i in numbers: sum = 0
sum = sum+i
print("The sum is", sum) while num > 0:
digit = num % 10
sum=sum+digit
num= num//10
print("Sum of digits:", sum)
Functions
• In Python, function is a group of related statements that perform a specific task.
• A function is a piece of code that groups a set of statements so they can be run/called more than once in
a program
• A function is a block of code which only runs when it is called.
• Python has a DRY (Don’t Repeat Yourself) principle.
• The benefit of using a function is reusability and modularity.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• Python support two types of functions
1. Built-in function: The functions which come along with Python itself are called a built-in function or
predefined function. Eg.: range(), append(), type(), input(), len()
2. User-defined function
Example of User defined function:
def calculator(a, b):
add = a + b
sub = a - b
mul = a * b
return add,sub,mul
# call function
# take return value in variable
res1,res2,res3 = calculator(20, 5)
print("Addition :", res1)
print("Subtraction:", res2)
print("Multiplication :", res3)
Introduction to IoT Tools
IoT tools help in:
1. Device programming
2. Data collection
3. Communication
4. Monitoring
5. Visualization
Introduction to IoT Tools
IoT Tools and Devices Eclipse IoT
Arduino SiteWhere
Flutter DeviceHive
Kinoma Home Assistant
Tessel 2
OpenRemote
M2MLabs Mainspring
ThingsBoard
Raspberry Pi OS (ex.
Raspbian) MilesightDeviceHub
Node-RED Zetta
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.
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.
• It has a long-range wireless transmitter and can be used 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.
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.
Tessel 2
• To create connected devices, you can also use Tessel 2 which is a programmable microcontroller
supporting JavaScript, [Link] 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.
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.
• It ensures long-term data storage and retrieval thanks to a scalable Apache Cassandra database.
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.
Node-RED
• Node-RED is a free programming tool based on [Link] and designed to integrate distributed IoT
hardware and software systems and automate their interaction.
• Node-RED offers repositories, interfaces for connecting to MQTT, logic sets and format parsers, as
well as the ability to write custom components.
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.
• Eclipse IoT projects focus on working with the Lua programming language.
SiteWhere
• It 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.
• It can be deployed locally or to the cloud platforms, including Azure, AWS, GCP.
DeviceHive
• It covers end-to-end IoT services, including:
o Prototyping and production at scale
o Connection of any devices via MQTT, REST API, WebSockets
o Integration with cloud platforms and third-party systems
o 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.
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.
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.
Things Board
• The Things Board IoT platform uses MQTT, CoAP and HTTP protocols to connect devices and handle
data from them.
• It offers configurable dashboards, charts, maps and widgets and provides robust real-time
visualization of your data.
• In addition, custom widgets can be created 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.
Milesight DeviceHub
• 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.
• Both the cloud and on-premises versions of the platform are available.
Zetta
• Zetta is a platform for designing APIs for IoT devices.
• The platform is based on [Link] 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.
Implementing IoT concepts with python.
Blink an LED connected to GPIO pin 4 on a Raspberry Pi.
from gpiozero import LED
from signal import pause
led = LED(4)
[Link]()
pause()
Operate a buzzer connected to a Raspberry Pi and make it beep continuously.
from gpiozero import Buzzer
from signal import pause
buzzer = Buzzer(4)
[Link](0.5, 0.5)
pause()
Detect motion using a PIR (Passive Infrared) motion sensor connected to a Raspberry Pi
from gpiozero import MotionSensor
from signal import pause
motion_sensor = MotionSensor(4)
def motion():
print("Motion detected")
def no_motion():
print("Motion stopped")
print("Readying sensor...")
motion_sensor.wait_for_no_motion()
print("Sensor ready")
motion_sensor.when_motion = motion
motion_sensor.when_no_motion = no_motion
pause()
This Python program creates a motion detection alarm system using Raspberry Pi. When motion is detected, an
LED blinks, a buzzer beeps, and the motion time is recorded in a CSV file.
A smart irrigation system is designed using a Raspberry Pi, a soil moisture sensor, a water pump (via relay), and a
push button override. Write a Python program such that when the moisture level falls below a threshold, the
pump gradually turns ON for controlled watering, runs for a specified duration, and then stops; additionally, if the
push button is pressed, manual watering should be activated, and in the absence of further input, the system
should safely return to automatic mode.
A smart ventilation control system uses a Raspberry Pi, two gas sensors placed at different locations (indoor and
outdoor), and a Servo Motor to control a window flap. Write a Python program such that the window opens to 120°
if indoor air quality is worse than outdoor (to allow fresh air), closes to 0° if outdoor air is worse, and remains at 60°
if both conditions are similar; additionally, the system should transmit air quality readings and window position to
an IoT cloud platform via Wi-Fi for real-time monitoring.
import time # Function to set servo angle # Simulated sensor readings (replace with real
import random # Used here to simulate sensor def set_angle(angle): sensor code)
values def read_indoor_air():
duty = 2 + (angle / 18)
import requests return [Link](200, 500)
[Link](SERVO_PIN, True)
import [Link] as GPIO
[Link](duty)
def read_outdoor_air():
[Link](1)
# GPIO setup return [Link](200, 500)
[Link](SERVO_PIN, False)
SERVO_PIN = 18
[Link](0)
[Link]([Link])
[Link](SERVO_PIN, [Link])
pwm = [Link](SERVO_PIN, 50) # 50Hz
frequency
[Link](0)
# IoT cloud configuration # Move servo
API_KEY = "YOUR_API_KEY" set_angle(angle)
URL = "[Link]
print(f"Indoor: {indoor}, Outdoor: {outdoor}, Window: {angle}°")
while True:
indoor = read_indoor_air()
# Send data to IoT cloud
outdoor = read_outdoor_air()
payload = {
# Decision logic "api_key": API_KEY,
if indoor > outdoor + 20: "field1": indoor,
angle = 120 "field2": outdoor,
status = "Open (Fresh air needed)" "field3": angle
}
elif outdoor > indoor + 20:
angle = 0 [Link](URL, params=payload)
status = "Closed (Outdoor air worse)"
[Link](15)
else:
angle = 60
except KeyboardInterrupt:
status = "Partially Open"
[Link]()
[Link]()
Blink an LED (Basic ESP32 Program)
from machine import Pin
import time
led = Pin(2, [Link]) # GPIO2 (built-in LED in many boards)
while True:
[Link]() # Turn LED ON
[Link](1) # Wait for 1 second
[Link]() # Turn LED OFF
[Link](1) # Wait for 1 second
Distance Measurement using Ultrasonic Sensor (ESP32 Program)
from machine import Pin, time_pulse_us
import time # Convert to distance (cm)
distance = (duration * 0.0343) / 2
# Define pins return distance
trig = Pin(5, [Link])
echo = Pin(18, [Link]) while True:
led = Pin(2, [Link]) dist = get_distance()
print("Distance:", dist, "cm")
def get_distance():
# Send trigger pulse if dist < 20:
[Link]() [Link]() # Object is near
time.sleep_us(2) else:
[Link]() [Link]() # Object is far
time.sleep_us(10)
[Link]() [Link](1)
# Measure echo time
duration = time_pulse_us(echo, 1)
Thank You