Book Image

Practical Python Programming for IoT

By : Gary Smart
Book Image

Practical Python Programming for IoT

By: Gary Smart

Overview of this book

The age of connected devices is here, be it fitness bands or smart homes. It's now more important than ever to understand how hardware components interact with the internet to collect and analyze user data. The Internet of Things (IoT), combined with the popular open source language Python, can be used to build powerful and intelligent IoT systems with intuitive interfaces. This book consists of three parts, with the first focusing on the "Internet" component of IoT. You'll get to grips with end-to-end IoT app development to control an LED over the internet, before learning how to build RESTful APIs, WebSocket APIs, and MQTT services in Python. The second part delves into the fundamentals behind electronics and GPIO interfacing. As you progress to the last part, you'll focus on the "Things" aspect of IoT, where you will learn how to connect and control a range of electronic sensors and actuators using Python. You'll also explore a variety of topics, such as motor control, ultrasonic sensors, and temperature measurement. Finally, you'll get up to speed with advanced IoT programming techniques in Python, integrate with IoT visualization and automation platforms, and build a comprehensive IoT project. By the end of this book, you'll be well-versed with IoT development and have the knowledge you need to build sophisticated IoT systems using Python.
Table of Contents (20 chapters)
1
Section 1: Programming with Python and the Raspberry Pi
6
Section 2: Practical Electronics for Interacting with the Physical World
9
Section 3: IoT Playground - Practical Examples to Interact with the Physical World

Running and exploring the HC-SR04 example code

The example code for the HC-SR04 can be found in the chapter11/hc-sr04.py file. Please review the source code before proceeding to get a broad understanding of what this file contains.

Place a solid object in front of the HC-SR04 (about 10 cm) and run the code in a terminal. As you move the object nearer or further from the sensor, the distance printed in the terminal will change, as indicated here:

(venv) python hc-sr04.py
Press Control + C to Exit
9.6898cm, 3.8149"
9.7755cm, 3.8486"
10.3342cm, 4.0686"
11.5532cm, 4.5485"
12.3422cm, 4.8591"
...

Let's review the code.

Firstly, we define the TRIG_GPIO and ECHO_GPIO pins on line 1, and the VELOCITY constant for the speed of sound at line 2. We're using 343 meters per second.

Our code is using 343 m/s for the speed of sound, while the datasheet suggests the value 340 m/s. You will also find other HC-SR04 examples and libraries that use slightly different...