41,99 €
Build clever, collaborative, and powerful automation systems with the Raspberry Pi and Python.
This Learning Path takes you on a journey in the world of robotics and teaches you all that you can achieve with Raspberry Pi and Python.
It teaches you to harness the power of Python with the Raspberry Pi 3 and the Raspberry Pi zero to build superlative automation systems that can transform your business. You will learn to create text classifiers, predict sentiment in words, and develop applications with the Tkinter library. Things will get more interesting when you build a human face detection and recognition system and a home automation system in Python, where different appliances are controlled using the Raspberry Pi. With such diverse robotics projects, you'll grasp the basics of robotics and its functions, and understand the integration of robotics with the IoT environment.
By the end of this Learning Path, you will have covered everything from configuring a robotic controller, to creating a self-driven robotic vehicle using Python.
This Learning Path is specially designed for Python developers who want to take their skills to the next level by creating robots that can enhance people’s lives. Familiarity with Python and electronics will aid understanding the concepts in this Learning Path.
Tim Cox works as a software engineer and is passionate about programming. He holds a bachelor's degree in electronics and electrical engineering and has a rich career in developing embedded software for a range of industries. To support the vision behind the Raspberry Pi and to encourage a new generation of engineers, Tim co-founded the MagPi magazine (the official magazine for the Raspberry Pi). He also produces electronic kits through his site PiHardware. Dr. Steven Lawrence Fernandes holds a bachelor's degree in electronics and communication engineering, a master's degree in microelectronics, and a Ph.D. in computer vision and machine learning. His Ph.D work "Match composite sketch with drone images" has received patent notification (Patent Application Number: 2983/CHE/2015). has post the doctoral research experience working in deep learning at the University of Alabama at Birmingham, USA. He received the prestigious US award from the Society for Design and Process Science for his outstanding service contributions in 2017 and Young Scientist Award by Vision Group on Science and Technology in 2014. He has also received a research grant from the Institution of Engineers. Sai Yamanoor is an embedded systems engineer working for a private startup school in the San Francisco Bay Area, where he builds devices that help students achieve their full potential. He completed his undergraduate work in mechatronics engineering from Sri Krishna College of Engineering and Technology, Coimbatore, India and his graduate studies in mechanical engineering at Carnegie Mellon University, Pittsburgh PA. His interests, deeply rooted in DIY and open software and hardware cultures, include developing gadgets and apps that improve the quality of life, Internet of Things, crowdfunding, education, and new technologies. In his spare time, he plays with various devices and architectures, such as the Raspberry Pi, Arduino, Galileo, Android devices and others. Sai has earlier published a book titled Raspberry Pi Mechatronics Projects. Srihari Yamanoor is a mechanical engineer, working on medical devices, sustainability, and robotics in the San Francisco Bay Area. He completed his undergraduate studies in mechanical engineering from PSG College of Technology, Coimbatore, India and graduate studies in mechanical engineering at Stanford University. He is certified in SolidWorks, simulation, sustainable design, PDM as well as in quality and reliability engineering and auditing. His has a wide range of interests, from DIY, crowdfunding, AI, travelling, photography to gardening and ecology. Prof. Diwakar Vaish is a robotics scientist and the inventor of Manav, India's first indigenous humanoid robot. He has invented the world's first mind-controlled wheelchair, brain cloning, and the world's cheapest ventilator. He has also been a guest lecturer at over 13 IITs and various other institutions. He is the founder of A-SET Robotics, a leading robotics research company based in New Delhi.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 692
Veröffentlichungsjahr: 2019
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors nor Packt Publishing or its dealers and distributors will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavoured to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: February 2019
Production reference: 1250219
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83855-579-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Tim Cox works as a software engineer and is passionate about programming. He holds a bachelor's degree in electronics and electrical engineering and has a rich career in developing embedded software for a range of industries. To support the vision behind the Raspberry Pi and to encourage a new generation of engineers, Tim co-founded the MagPi magazine (the official magazine for the Raspberry Pi). He also produces electronic kits through his site PiHardware.
Dr. Steven Lawrence Fernandes holds a bachelor's degree in electronics and communication engineering, a master's degree in microelectronics, and a Ph.D. in computer vision and machine learning. His Ph.D work "Match composite sketch with drone images" has received patent notification (Patent Application Number: 2983/CHE/2015). has post the doctoral research experience working in deep learning at the University of Alabama at Birmingham, USA. He received the prestigious US award from the Society for Design and Process Science for his outstanding service contributions in 2017 and Young Scientist Award by Vision Group on Science and Technology in 2014. He has also received a research grant from the Institution of Engineers.
Sai Yamanoor is an embedded systems engineer working for a private startup school in the San Francisco Bay Area, where he builds devices that help students achieve their full potential. He completed his undergraduate work in mechatronics engineering from Sri Krishna College of Engineering and Technology, Coimbatore, India and his graduate studies in mechanical engineering at Carnegie Mellon University, Pittsburgh PA. His interests, deeply rooted in DIY and open software and hardware cultures, include developing gadgets and apps that improve the quality of life, Internet of Things, crowdfunding, education, and new technologies. In his spare time, he plays with various devices and architectures, such as the Raspberry Pi, Arduino, Galileo, Android devices and others. Sai has earlier published a book titled Raspberry Pi Mechatronics Projects.
Srihari Yamanoor is a mechanical engineer, working on medical devices, sustainability, and robotics in the San Francisco Bay Area. He completed his undergraduate studies in mechanical engineering from PSG College of Technology, Coimbatore, India and graduate studies in mechanical engineering at Stanford University. He is certified in SolidWorks, simulation, sustainable design, PDM as well as in quality and reliability engineering and auditing. His has a wide range of interests, from DIY, crowdfunding, AI, travelling, photography to gardening and ecology.
Prof. Diwakar Vaish is a robotics scientist and the inventor of Manav, India's first indigenous humanoid robot. He has invented the world's first mind-controlled wheelchair, brain cloning, and the world's cheapest ventilator. He has also been a guest lecturer at over 13 IITs and various other institutions. He is the founder of A-SET Robotics, a leading robotics research company based in New Delhi.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Getting Started with Python for the Internet of Things
About Packt
Why subscribe?
Packt.com
Contributors
About the authors
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with a Raspberry Pi 3 Computer
Introduction
Introducing Raspberry Pi
What's with the name?
Why Python?
Python 2 and Python 3
Which version of Python should you use?
The Raspberry Pi family – a brief history of Pi
Which Pi to choose?
Connecting to Raspberry Pi
Getting ready
How to do it...
There's more...
Secondary hardware connections
Using NOOBS to set up your Raspberry Pi SD card
Getting ready
How to do it...
How it works...
There's more...
Changing the default user password
Ensuring that you shut down safely
Preparing an SD card manually
Expanding the system to fit in your SD card
Accessing the RECOVERY/BOOT partition
Using the tools to back up your SD card in case of failure
Networking and connecting your Raspberry Pi to the internet via an Ethernet port, using a CAT6 Ethernet cable
Getting ready
How to do it...
There's more...
Using built-in Wi-Fi and Bluetooth on Raspberry Pi
Getting ready
How to do it...
Connecting to your Wi-Fi network
Connecting to Bluetooth devices
Configuring your network manually
Getting ready
How to do it...
There's more...
Networking directly to a laptop or computer
Getting ready
How to do it...
How it works...
There's more...
Direct network link
See also
Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi dongle
Getting ready
How to do it...
There's more...
Using USB wired network adapters
Connecting to the internet through a proxy server
Getting ready
How to do it...
How it works...
There's more...
Connecting remotely to Raspberry Pi over the network using VNC
Getting ready
How to do it...
There's more...
Connecting remotely to Raspberry Pi over the network using SSH (and X11 forwarding)
Getting ready
How to do it...
How it works...
There's more...
Running multiple programs with X11 forwarding
Running as a desktop with X11 forwarding
Running Pygame and Tkinter with X11 forwarding
Sharing the home folder of Raspberry Pi with SMB
Getting ready
How to do it...
Keeping Raspberry Pi up to date
Getting ready
How to do it...
There's more...
Dividing Text Data and Building Text Classifiers
Introduction
Building a text classifier
How to do it...
How it works...
See also
Pre-processing data using tokenization
How to do it...
Stemming text data
How to do it...
Dividing text using chunking
How to do it...
Building a bag-of-words model
How to do it...
Applications of text classifiers
Using Python for Automation and Productivity
Introduction
Using Tkinter to create graphical user interfaces
Getting ready
How to do it...
How it works...
Creating a graphical application – Start menu
Getting ready
How to do it...
How it works...
There's more...
Displaying photo information in an application
Getting ready
How to do it...
How it works...
There's more...
Organizing your photos automatically
Getting ready
How to do it...
How it works...
Predicting Sentiments in Words
Building a Naive Bayes classifier
How to do it...
See also
Logistic regression classifier
How to do it...
Splitting the dataset for training and testing
How to do it...
Evaluating the accuracy using cross-validation
How to do it...
Analyzing the sentiment of a sentence
How to do it...
Identifying patterns in text using topic modeling
How to do it...
Applications of sentiment analysis
Detecting Edges and Contours in Images
Introduction
Loading, displaying, and saving images
How to do it...
Image flipping
How to do it...
Image scaling
How to do it...
Erosion and dilation
How to do it...
Image segmentation
How to do it...
Blurring and sharpening images
How to do it...
Detecting edges in images
How to do it...
How it works...
See also
Histogram equalization
How to do it…
Detecting corners in images
How to do it...
Building Face Detector and Face Recognition Applications
Introduction
Building a face detector application
How to do it...
Building a face recognition application
How to do it...
How it works...
See also
Applications of a face recognition system
Using Python to Drive Hardware
Introduction
Controlling an LED
Getting ready
How to do it...
How it works...
There's more...
Controlling the GPIO current
Responding to a button
Getting ready
Trying a speaker or headphone with Raspberry Pi
How to do it...
How it works...
There's more...
Safe voltages
Pull-up and pull-down resistor circuits
Protection resistors
A controlled shutdown button
Getting ready
How to do it...
How it works...
There's more...
Resetting and rebooting Raspberry Pi
Adding extra functions
The GPIO keypad input
Getting ready
How to do it...
How it works...
There's more...
Generating other key combinations
Emulating mouse events
Multiplexed color LEDs
Getting ready
How to do it...
How it works...
There's more...
Hardware multiplexing
Displaying random patterns
Mixing multiple colors
Writing messages using persistence of vision
Getting ready
How to do it...
How it works...
Sensing and Displaying Real-World Data
Introduction
Using devices with the I2C bus
Getting ready
How to do it...
How it works...
There's more...
Using multiple I2C devices
I2C bus and level shifting
Using just the PCF8591 chip or adding alternative sensors
Reading analog data using an analog-to-digital converter
Getting ready
How to do it...
How it works...
There's more...
Gathering analog data without hardware
Logging and plotting data
Getting ready
How to do it...
How it works...
There's more...
Plotting live data
Scaling and calibrating data
Extending the Raspberry Pi GPIO with an I/O expander
Getting ready
How to do it...
How it works...
There's more...
I/O expander voltages and limits
Using your own I/O expander module
Directly controlling an LCD alphanumeric display
Capturing data in an SQLite database
Getting ready
How to do it...
How it works...
There's more...
The CREATE TABLE command
The INSERT command
The SELECT command
The WHERE command
The UPDATE command
The DELETE command
The DROP command
Viewing data from your own webserver
Getting ready
How to do it...
How it works...
There's more...
Security
Using MySQL instead
Sensing and sending data to online services
Getting ready
How to do it...
How it works...
See also
Building Neural Network Modules for Optical Character Recognition
Introduction
Visualizing optical characters
How to do it...
Building an optical character recognizer using neural networks
How to do it...
How it works...
See also
Applications of an OCR system
Arithmetic Operations, Loops, and Blinky Lights
Hardware required for this chapter
Arithmetic operations
Bitwise operators in Python
Logical operators
Data types and variables in Python
Reading inputs from the user
The formatted string output
The str.format() method
An exercise for the reader
Another exercise for the reader
Concatenating strings
Loops in Python
A for loop
Indentation
Nested loops
A while loop
Raspberry Pi's GPIO
Blinky lights
Code
The applications of GPIO control
Summary
Conditional Statements, Functions, and Lists
Conditional statements
An if-else statement
if-elif-else statement
Breaking out of loops
The applications of conditional statements: executing tasks using GPIO
Breaking out a loop by counting button presses
Functions in Python
Passing arguments to a function:
Returning values from a function
The scope of variables in a function
GPIO callback functions
DC motor control in Python
Some mini-project challenges for the reader
Summary
Communication Interfaces
UART – serial port
Raspberry Pi Zero's UART port
Setting up the Raspberry Pi Zero serial port
Example 1 – interfacing a carbon dioxide sensor to the Raspberry Pi
Python code for serial port communication
I2C communication
Example 2 – PiGlow
Installing libraries
Example
Example 3 – Sensorian add-on hardware for the Raspberry Pi
I2C drivers for the lux sensor
Challenge
The SPI interface
Example 4 – writing to external memory chip
Challenge to the reader
Summary
Data Types and Object-Oriented Programming in Python
Lists
Operations that could be performed on a list
Append element to list:
Remove element from list:
Retrieving the index of an element
Popping an element from the list
Counting the instances of an element:
Inserting element at a specific position:
Challenge to the reader
Extending a list
Clearing the elements of a list
Sorting the elements of a list
Reverse the order of elements in list
Create copies of a list
Accessing list elements
Accessing a set of elements within a list
List membership
Let's build a simple game!
Dictionaries
Tuples
Sets
OOP in Python
Revisiting the student ID card example
Class
Adding methods to a class
Doc strings in Python
self
Speaker controller
Light control daemon
Summary
File I/O and Python Utilities
File I/O
Reading from a file
Reading lines
Writing to a file
Appending to a file
seek
Read n bytes
r+
Challenge to the reader
The with keyword
configparser
Challenge to the reader
Reading/writing to CSV files
Writing to CSV files
Reading from CSV files
Python utilities
The os module
Checking a file's existence
Checking for a folder's existence
Deleting files
Killing a process
Monitoring a process
The glob module
Challenge to the reader
The shutil module
The subprocess module
The sys module
Summary
Requests and Web Frameworks
The try/except keywords
try...except...else
try...except...else...finally
Connecting to the Internet – web requests
The application of requests – retrieving weather information
The application of requests – publishing events to the Internet
Flask web framework
Installing Flask
Building our first example
Controlling appliances using the Flask framework
Summary
Awesome Things You Could Develop Using Python
Image processing using a Raspberry Pi Zero
OpenCV
The verification of the installation
A challenge to the reader
Installing the camera to the Raspberry Zero
Speech recognition
Automating routing tasks
Improving daily commute
A challenge to the reader
Project challenge
Improving your vocabulary
A challenge to the reader
Project challenge
Logging
Threading in Python
PEP8 style guide for Python
Verifying PEP8 guidelines
Summary
Robotics 101
The hardware arsenal
Setting up Raspberry Pi
Let's program
Playing with voltage
Summary
Using GPIOs as Input
A deeper dive into GPIOs
Interfacing the PIR sensor
Interfacing the ultrasonic proximity sensor
Interfacing through I2C
Summary 
Making a Gardener Robot
Working with solenoids
Making the robot
Making it more intelligent
Making it truly intelligent
Summary
Basics of Motors
The basics
Getting it rolling
Changing the speed 
Summary
Bluetooth-Controlled Robotic Car
Basics of the vehicle
Getting the vehicle ready
Controlling the vehicle by Bluetooth
Summary
Sensor Interface for Obstacle Avoidance
Infrared proximity sensor
Autonomous emergency braking
Giving the car self-steering capabilities
Making it fully autonomous
Summary
Making Your Own Area Scanner
Servo motor
Lists
Looking around 
LIDAR on an autonomous vehicle 
Summary
Basic Switching
Making Jarvis wake you up 
Working with relay and PIR sensor
Making the alarm irritating
Making it even more irritating
Summary
Recognizing Humans with Jarvis
Turn on the light Jarvis
Understanding motion
Perfecting motion
Controlling the intensity
Intelligent temperature control
Adding more 
Summary
Making Jarvis IoT Enabled
Basics of IoT
The MQTT protocol
Setting up the MQTT broker
Making an IoT-based intrusion detector
Controlling the home
Summary
Giving Voice to Jarvis
Basic installation
Automatic delivery answering machine 
Making an interactive door – answering robot
Making Jarvis understand our voice
Summary
Gesture Recognition
Electric field sensing
Using the Flick HAT
Gesture recognition-based automation
Summary
Machine Learning
Making a dataset
Predicting using a dataset
Making your home learn
Home learning and automation
Summary
Making a Robotic Arm
Basics of a robotic arm
Degrees of freedom
Power house
Voltage
Capacity
Power-to-weight ratio
Maximum charge and discharge rate
Chemical composition
Finding the limits
Making the robot safe
Programming multiple frames
Speed control
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This Learning Path takes you on a journey in the world of robotics and teaches you all that you can achieve with Raspberry Pi and Python.
It teaches you to harness the power of Python with the Raspberry Pi 3 and the Raspberry Pi zero to build superlative automation systems that can transform your business. You will learn to create text classifiers, predict sentiment in words, and develop applications with the Tkinter library. Things will get more interesting when you build a human face detection and recognition system and a home automation system in Python, where different appliances are controlled using the Raspberry Pi. With such diverse robotics projects, you'll grasp the basics of robotics and its functions, and understand the integration of robotics with the IoT environment.
By the end of this Learning Path, you will have covered everything from configuring a robotic controller, to creating a self-driven robotic vehicle using Python.
This Learning Path includes content from the following Packt products:
Raspberry Pi 3 Cookbook for Python Programmers - Third Edition by Tim Cox, Dr. Steven Lawrence Fernandes
Python Programming with Raspberry Pi by Sai Yamanoor, Srihari Yamanoor
Python Robotics Projects by Prof. Diwakar Vaish
This book is specially designed for Python developers who want to take their skills to the next level by creating robots that can enhance people’s lives. Familiarity with Python and electronics will aid understanding the concepts in this Learning Path.
Chapter 1, Getting Started with a Raspberry Pi 3 Computer, introduces the Raspberry Pi and explores the various ways in which it can be set up and used.
Chapter 2, Dividing Text Data and Building Text Classifiers, guides us to build a text classifier; it can classify text using the bag-of-words model.
Chapter 3, Using Python for Automation and Productivity, explains how to use graphical user interfaces to create your own applications and utilities.
Chapter 4, Predicting Sentiments in Words, explains how Naive Bayes classifiers and logistic regression classifiers are constructed to analyze the sentiment in words
Chapter 5, Detecting Edges and Contours in Images, describes in detail how images are loaded, displayed, and saved. It provides detailed implementations of erosion and dilation, image segmentation, histogram equalization, edge detection, detecting corners in images, and more.
Chapter 6, Building Face Detector and Face Recognition Applications, explains how human faces can be detected from webcams and recognized using images stored in a database.
Chapter 7, Using Python to Drive Hardware, establishes the fact that to experience the Raspberry Pi at its best, we really have to use it with our own electronics. This chapter discusses how to create circuits with LEDs and switches, and how to use them to indicate the status of a system and provide control. Finally, it shows us how to create our own game controller, light display, and a persistence-of-vision text display.
Chapter 8, Sensing and Displaying Real-World Data, explains how to use an analog-todigital converter to provide sensor readings to the Raspberry Pi. We discover how to store and graph the data in real time, as well as display it on an LCD text display. Next, we record the data in a SQL database and display it in our own web server. Finally, we transfer the data to the internet, which will allow us to view and share the captured data anywhere in the world.
Chapter 9, Building a Neural Network Module for Optical Character Recognition, introduces neural network implementation on Raspberry Pi 3. Optical characters are detected, displayed, and recognized using neural networks
Chapter 10, Arithmetic Operations, Loops, and Blinky Lights, walks through the arithmetic operations in Python and loops in Python. In the second half of the chapter, we will discuss the Raspberry Pi Zero’s GPIO interface and then learn to blink an LED using a GPIO pin.
Chapter 11, Conditional Statements, Functions, and Lists, discusses the types of conditional statements, variables, and logical operators in Python. We will also discuss functions in Python. Then, we will learn to write a function that is used to control DC motors using the Raspberry Pi Zero.
Chapter 12, Communication Interfaces, covers all the communication interfaces available on the Raspberry Pi Zero. This includes the I2C, UART, and the SPI interface. These communication interfaces are widely used to interface sensors. Hence, we will demonstrate the operation of each interface using a sensor as an example.
Chapter 13, Data Types and Object-Oriented Programming in Python, discusses object-oriented programming in Python and the advantages of object-oriented programming. We will discuss this using a practical example.
Chapter 14, File I/O and Python Utilities, discusses reading and writing to files. We discuss creating and updating config files. We will also discuss some utilities available in Python.
Chapter 15, Requests and Web Frameworks, discusses libraries and frameworks that enable retrieving data from the Web. We will discuss an example, fetching local weather information. We will also discuss running a web server on the Raspberry Pi Zero.
Chapter 16, Awesome Things You Could Develop Using Python, discusses libraries and frameworks that enable retrieving data from the web. We will discuss examples such as fetching the local weather information. We will also discuss running a web server on the Raspberry Pi Zero
Chapter 17, Robotics 101, will make you understand the basics of our hardware and Python. Using simple LEDs, we will start to make simple programs in Python.
Chapter 18, Using GPIOs as Input, will discuss how to connect various sensors, starting with interfacing a switch through an ultrasonic range finder and finally to a light sensor (LDR) using an analog-to-digital converter.
Chapter 19, Making a Gardener Robot, will use various sensors, such as a soil humidity sensor, and a temperature sensor to sense the climate, and using a solenoid valve controlled by a relay, we will be making a robot that waters the garden whenever required.
Chapter 20, Basics of Motors, will discuss the working of motor and how it can be driven by a motor driver, how a full H bridge motor driver works, and also how the speed control mechanism works in the motor driver. While doing all this, we will control a motor and make it move in a different direction at different speeds.
Chapter 21, Bluetooth-Controlled Robotic Car, will teach more about steering and controlling a robotic vehicle, and the concepts of a skid-steer mechanism will be implemented. You will also learn how to use the Bluetooth onboard our Raspberry Pi and connect it to your mobile phone. Finally, using an app, we will control our robotic vehicle using our mobile phone.
Chapter 22, Sensor Interface for Obstacle Avoidance, will provide an insight into how we can use IR proximity sensors to determine distances. Also, we will make smart algorithms to sense distance on all sides and then move in the direction where the distance is greatest.
Chapter 23, Making Your Own Area Scanner, will teach you the basics of servo motors and how they can be controlled. Using servo motor, we will make an area scanner, in other words, a homemade LIDAR. Using this home-built sensor, we would make a self navigating car.
Chapter 24, Basic Switching, will control the equipment at your home with simple logic. Finally, we will make an alarm that will wake you up in the natural way by lights. This will have a smart automatic snooze.
Chapter 25, Recognizing Humans with Jarvis, will teach you how to control devices at your home with a room occupancy sensor that we will build at home using an IR proximity sensor. We will then make this occupancy sensor smart and ready to count the number of people in the room and only switch off the lights or other equipment once no one is left in the room.
Chapter 26, Making Jarvis IoT Enabled, will provide you with insights into the concepts of IoT and MQTT server through which we will be able to monitor our home based on events. Also, you will learn how to control the devices in our home while sitting anywhere in the world.
Chapter 27, Giving Voice to Jarvis, will teach you how the system can be made capable of synthesizing speech. Also, you will learn how you can make the system recognize our speech, and based on it, everything in the home can be controlled.
Chapter 28, Gesture Recognition, will make you identify the gestures made on the board using electric waves, and based on those gestures, the smart home will be controlled.
Chapter 29, Machine Learning, will make you understand the concepts of machine learning and especially the k-nearest algorithm. Using this algorithm, you will understand how data can be given to the system and predictions can be made based on it . Finally, you will execute a program to generate its own data by the inputs of the users over the course of time, and based on that data, it will start automatically controlling the home without any human intervention.
Chapter 30, Making a Robotic Arm, will help you make a robotic hand. You will understand how to set the physical limits of the servos for protection purposes, and we will then make a program in which you will control the robot will be controlled based on different frames. Finally, you will go ahead and understand how to control speed of motion of the robot.
To start using this book, Readers are expected to know the basics of Python programming. It would be beneficial for readers to have a basic understanding of machine learning, computer vision, and neural networks.The following hardware is recommended as well:
A laptop computer, with any OS
Raspberry Pi
A microSD card, either 8 GB or 16 GB
A USB keyboard, mouse and a WiFi card
A display with HDMI input
Power supply, minimum 500 mA
Display cables and other accessories
Readers will have to download and install RASPBIAN STRETCH WITH DESKTOP; this will give us the GUI interface for Raspberry Pi
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/GettingStartedwithPythonfortheInternetofThings.In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalogue of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
In this chapter, we will cover the following topics:
Connecting peripherals to Raspberry Pi
Using NOOBS to set up your Raspberry Pi SD card
Networking and connecting your Raspberry Pi to the internet via the LAN connector
Using built-in Wi-Fi and Bluetooth on Raspberry Pi
Configuring your network manually
Networking directly to a laptop or computer
Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi dongle
Connecting to the internet through a proxy server
Connecting remotely to Raspberry Pi over the network using VNC
Connecting remotely to Raspberry Pi over the network using SSH (and X11 forwarding)
Sharing the home folder of Raspberry Pi with SMB
Keeping Raspberry Pi up to date
This chapter introduces Raspberry Pi 3 and the process of setting it up for the first time. We will connect Raspberry Pi to a suitable display, power, and peripherals. We will install an operating system on an SD card. This is required for the system to boot. Next, we will ensure that we can connect successfully to the internet through a local network.
Finally, we will make use of the network to provide ways to remotely connect to and/or control Raspberry Pi from other computers and devices, as well as to ensure that the system is kept up to date.
Once you have completed the steps within this chapter, your Raspberry Pi will be ready for you to use for programming. If you already have your Raspberry Pi set up and running, ensure that you take a look through the following sections, as there are many helpful tips.
The Raspberry Pi is a single-board computer created by the Raspberry Pi Foundation, a charity formed with the primary purpose of re-introducing low-level computer skills to children in the UK. The aim was to rekindle the microcomputer revolution of the 1980s, which produced a whole generation of skilled programmers.
Even before the computer was released at the end of February 2012, it was clear that Raspberry Pi had gained a huge following worldwide and, at the time of writing this book, has sold over 10 million units. The following image shows several different Raspberry Pi models:
The name, Raspberry Pi, was a combination of the desire to create an alternative computer with a fruit-based name (such as Apple, BlackBerry, and Apricot) and a nod to the original concept of a simple computer that could be programmed using Python (shortened to Pi).
In this book, we will take this little computer, find out how to set it up, and then explore its capabilities chapter by chapter, using the Python programming language.
It is often asked, "Why has Python been selected as the language to use on Raspberry Pi?" The fact is that Python is just one of the many programming languages that can be used on Raspberry Pi.
There are many programming languages that you can choose, from high-level graphical block programming, such as Scratch, to traditional C, right down to BASIC, and even the raw machine code assembler. A good programmer often has to be code multilingual to be able to play to the strengths and weaknesses of each language to best meet the needs of their desired application. It is useful to understand how different languages (and programming techniques) try to overcome the challenge of converting what you want into what you get, as this is what you are trying to do as well while you program.
Python has been selected as a good place to start when learning about programming, as it provides a rich set of coding tools while still allowing simple programs to be written without fuss. This allows beginners to gradually be introduced to the concepts and methods on which modern programming languages are based without requiring them to know it all from the start. It is very modular with lots of additional libraries that can be imported to quickly extend the functionality. You will find that, over time, this encourages you to do the same, and you will want to create your own modules that you can plug into your own programs, thus taking your first steps into structured programming.
Python addresses formatting and presentation concerns. As indentation will add better readability, indents matter a lot in Python. They define how blocks of code are grouped together. Generally, Python is slow; since it is interpreted, it takes time to create a module while it is running the program. This can be a problem if you need to respond to time-critical events. However, you can precompile Python or use modules written in other languages to overcome this.
It hides the details; this is both an advantage and a disadvantage. It is excellent for beginners but can be difficult when you have to second-guess aspects such as datatypes. However, this in turn forces you to consider all the possibilities, which can be a good thing.
A massive source of confusion for beginners is that there are two versions of Python on Raspberry Pi (Version 2.7 and Version 3.6), which are not compatible with each other, so code written for Python 2.7 may not run with Python 3.6 (and vice versa).
The Python Software Foundation is continuously working to improve and move forward with the language, which sometimes means they have to sacrifice backward compatibility to embrace new improvements (and, importantly, remove redundant and legacy ways of doing things).
There are many tools that will ease the transition from Python 2 to Python 3, including converters such as2to3, which will parse and update your code to use Python 3 methods. This process is not perfect, and in some cases you'll need to manually rewrite sections and fully retest everything. You can write the code and libraries that will support both. Theimport __future__statement allows you to import the friendly methods of Python 3 and run them using Python 2.7.
Essentially, the selection of which version to use will depend on what you intend to do. For instance, you may require Python 2.7 libraries, which are not yet available for Python 3.6. Python 3 has been available since 2008, so these tend to be older or larger libraries that have not been translated. In many cases, there are new alternatives to legacy libraries; however, their support can vary.
In this book, we have used Python 3.6, which is also compatible with Python 3.5 and 3.3.
Since its release, Raspberry Pi has come in various iterations, featuring both small and large updates and improvements to the original Raspberry Pi Model B unit. Although it can be confusing at first, there are three basic types of Raspberry Pi available (and one special model).
The main flagship model is called Model B. This has all the connections and features, as well as the maximum RAM and the latest processor. Over the years, there have been several versions, most notably Model B (which had 256 MB and then 512 MB RAM) and then Model B+ (which increased the 26-pin GPIO to 40 pins, switched to using a microSD card slot, and had four USB ports instead of two). These original models all used the Broadcom BCM2835 system on chip (SOC), consisting of a single core 700 MHz ARM11 and VideoCore IV graphical processing unit (GPU).
The release of Raspberry Pi 2 Model B (also referred to as 2B) in 2015 introduced a new Broadcom BCM2836 SOC, providing a quad-core 32-bit ARM Cortex A7 1.2 GHz processor and GPU, with 1 GB of RAM. The improved SOC added support for Ubuntu and Windows 10 IoT. Finally, we had the latest Raspberry Pi 3 Model B, using another new Broadcom BCM2837 SOC, which provides a quad-core 64-bit ARM Cortex-A53 and GPU, alongside on-board Wi-Fi and Bluetooth.
Model A has always been targeted as a cut-down version. While having the same SOC as Model B, there are limited connections consisting of a single USB port and no wired network (LAN). Model A+ again added more GPIO pins and a microSD slot. However, the RAM was later upgraded to 512 MB of RAM and again there was only a single USB port/no LAN. The Broadcom BCM2835 SOC on Model A has not been updated so far (so is still a single core ARM11); however, a Model 3A (most likely using the BCM2837).
The Pi Zero is an ultra-compact version of Raspberry Pi intended for embedded applications where cost and space are a premium. It has the same 40-pin GPIO and microSD card slot as the other models, but lacks the on-board display (CSI and DSI) connection. It does still have HDMI (via a mini-HDMI) and a single micro USB on-the-go (OTG) connection. Although not present in the first revision of the Pi Zero, the most recent model also includes a CSI connection for the on-board camera.
The special model is known as the compute module. This takes the form of a 200-pin SODIMM card. It is intended for industrial use or within commercial products, where all the external interfaces would be provided by a host/motherboard, into which the module would be inserted. Example products include the Slice Media Player (http://fiveninjas.com) and the OTTO camera. The current module uses the BCM2835, although an updated compute module (CM3).
The Raspberry Pi Wikipedia page provides a full list of the all different variants and their specifications:https://en.wikipedia.org/wiki/Raspberry_Pi#Specifications
Also, the Raspberry Pi product page gives you the details about the models available and the accessories' specifications:https://www.raspberrypi.org/products/
All sections of this book are compatible will all current versions of Raspberry Pi, but Model 3B is recommended as the best model to start with. This offers the best performance (particularly useful for the GPU examples in OpenCV examples used in Chapter 5, Detecting Edges and Contours in Images), lots of connections, and built-in Wi-Fi, which can be very convenient.
Pi Zero is recommended for projects where you want low power usage or reduced weight/size but do not need the full processing power of Model 3B. However, due to its ultra-low cost, Pi Zero is ideal for deploying a completed project after you have developed it.
There are many ways to wire up Raspberry Pi and use the various interfaces to view and control content. For typical use, most users will require power, display (with audio), and a method of input such as a keyboard and mouse. To access the internet, refer to the Networking and connecting your Raspberry Pi to the internet via the LAN connector or Using built-in Wi-Fi and Bluetooth on Raspberry Pi recipes.
Before you can use your Raspberry Pi, you will need an SD card with an operating system installed or with the New Out Of Box System (NOOBS) on it, as discussed in the Using NOOBS to set up your Raspberry Pi SD card recipe.
The following section will detail the types of devices you can connect to Raspberry Pi and, importantly, how and where to plug them in.
As you will discover later, once you have your Raspberry Pi set up, you may decide to connect remotely and use it through a network link, in which case you only need power and a network connection. Refer to the following sections: Connecting remotely to Raspberry Pi over the Network using VNC and Connecting Remotely to Raspberry Pi over the Network using SSH (and X11 Forwarding).
The layout of Raspberry Pi is shown in the following diagram:
More information about the preceding figure is listed as follows:
Display
: The Raspberry Pi supports the following three main display connections; if both HDMI and composite video are connected, it will default to HDMI only:
HDMI
: For best results, use a TV or monitor that has an HDMI connection, thus allowing the best resolution display (1080p) and also digital audio output. If your display has a DVI connection, you may be able to use an adapter to connect through the HDMI. There are several types of DVI connection; some support analogue (DVI-A), some digital (DVI-D), and some both (DVI-I). Raspberry Pi is only able to provide a digital signal through the HDMI, so an HDMI-to-DVI-D adapter is recommended (shown with a tick mark in the following screenshot). This lacks the four extra analogue pins (shown with a cross mark in the following screenshot), thus allowing it to fit into both DVI-D and DVI-I type sockets:
If you wish to use an older monitor (with a VGA connection), an additional HDMI-to-VGA converter is required. Raspberry Pi also supports a rudimentary VGA adaptor (VGA Gert666 Adaptor), which is driven directly off of the GPIO pins. However, this does use up all but four pins of the 40-pin header (older 26-pin models will not support the VGA output):
Analogue
: An alternative display method is to use the analogue composite video connection (via the phono socket); this can also be attached to an S-Video or European SCART adapter. However, the analogue video output has a maximum resolution of 640 x 480 pixels, so it is not ideal for general use:
When using the RCA connection or a DVI input, audio has to be provided separately by the analogue audio connection. To simplify the manufacturing process (by avoiding through-hole components), the Pi Zero does not have analogue audio or an RCA socket for analogue video (although they can be added with some modifications):
Direct Display DSI
: A touch display produced by Raspberry Pi Foundation will connect directly into the DSI socket. This can be connected and used at the same time as the HDMI or analogue video output to create a dual display setup.
Stereo analogue audio (all except Pi Zero)
: This provides an analogue audio output for headphones or amplified speakers. The audio can be switched via Raspberry Pi configuration tool on the desktop between analog (stereo socket) and digital (HDMI), or via the command line using
amixer
or
alsamixer
.
man amixer
Some commands also support the --help option for more concise help, shown as follows:
amixer --help
Network (excluding models A and Pi Zero)
: The network connection is discussed in the
Networking and connecting your Raspberry Pi to the internet via the LAN connector
recipe later in this chapter. If we use the Model A Raspberry Pi, it is possible to add a USB network adapter to add wired or even wireless networking (refer to the
Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi dongle
recipe).
Onboard Wi-Fi and Bluetooth (Model 3 B only)
: The Model 3 B has built-in 802.11n Wi-Fi and Bluetooth 4.1; see the
Using the built-in Wi-Fi and Bluetooth on Raspberry Pi
recipe.
USB (1x Model A/Zero, 2x Model 1 B, 4x Model 2 B and 3 B)
: Using a keyboard and mouse:
Raspberry Pi should work with most USB keyboards and mice. You can also use wireless mice and keyboards, which use RF dongles. However, additional configuration is required for items that use the Bluetooth dongles.
If there is a lack of power supplied by your power supply or the devices are drawing too much current, you may experience the keyboard keys appearing to stick, and, in severe cases, corruption of the SD card.
You can identify a revision 1 board, as it lacks the four mounting holes that are present in the later models.
Debian Linux (upon which Raspbian is based) supports many common USB devices, such as flash storage drives, hard-disk drives (external power may be required), cameras, printers, Bluetooth, and Wi-Fi adapters. Some devices will be detected automatically, while others will require drivers to be installed.
Micro USB power
: The Raspberry Pi requires a 5V power supply that can comfortably supply at least 1,000 mA (1,500 mA or more is recommended, particularly with the more power-hungry Model 2 and Model 3) with a micro USB connection. It is possible to power the unit using portable battery packs, such as the ones suitable for powering or recharging tablets. Again, ensure that they can supply 5V at 1,000 mA or over.
You should aim to make all other connections to Raspberry Pi before connecting the power. However, USB devices, audio, and networks may be connected and removed while it is running, without problems.
In addition to the standard primary connections you would expect to see on a computer, Raspberry Pi also has a number of other connections.
Each of the following connections provides additional interfaces for Raspberry Pi:
20 x 2 GPIO pin header (Model A+, B+, 2 B, 3 B, and Pi Zero)
: This is the main 40-pin GPIO header of Raspberry Pi used for interfacing directly with hardware components. The chapters in this book are also compatible with older models of Raspberry Pi that have a 13 x 2 GPIO pin header.
P5 8 x 2 GPIO pin header (Model 1 B revision 2.0 only)
: We do not use this in the book.
Reset connection
: This is present on later models (no pins fitted). A reset is triggered when Pin 1 (reset) and Pin 2 (GND) are connected together. We use this in the
A controlled shutdown button
concept in
Chapter 7
,
Using Python to Drive Hardware
.
GPU/LAN JTAG
: The
Joint Test Action Group
(
JTAG
) is a programming and debugging interface used to configure and test processors. These are present on newer models as surface pads. A specialist JTAG device is required to use this interface. We do not use this in the book.
Direct camera CSI
: This connection supports Raspberry Pi Camera Module. Note that the Pi Zero has a smaller CSI connector than the other models, so it requires a different ribbon connector.
Direct Display DSI
: This connection supports a directly connected display, such as a 7-inch 800 x 600 capacitive touch screen.
The Raspberry Pi requires the operating system to be loaded onto an SD card before it starts up. The easiest way to set up the SD card is to use NOOBS; you may find that you can buy an SD card with NOOBS already loaded on it.
NOOBS provides an initial start menu that provides options to install several of the available operating systems on to your SD card.
Since NOOBS creates a RECOVERY partition to keep the original installation images, an 8 GB SD card or larger is recommended. You will also need an SD card reader (experience has shown that some built-in card readers can cause issues, so an external USB type reader is recommended).
If you are using an SD card that you have used previously, you may need to reformat it to remove any previous partitions and data. NOOBS expects the SD card to consist of a single FAT32 partition.
If using Windows or macOS X, you can use the SD Association's formatter, as shown in the following screenshot (available at https://www.sdcard.org/downloads/formatter_4/):
From the Option Setting dialog box, set FORMAT SIZE ADJUSTMENT. This will remove all the SD card partitions that were created previously.
If using Linux, you can use gparted to clear any previous partitions and reformat it as a FAT32 partition.
The full NOOBS package (typically just over 1 GB) contains Raspbian, the most popular Raspberry Pi operating system image built in. A lite version of NOOBS is also available that has no preloaded operating systems (although a smaller initial download of 20 MB and a network connection on Raspberry Pi are required to directly download the operating system you intend to use).
NOOBS is available at http://www.raspberrypi.org/downloads, with the documentation available at https://github.com/raspberrypi/noobs.
By performing the following steps, we will prepare the SD card to run NOOBS. This will then allow us to select and install the operating system we want to use:
Get your SD card ready.
On a freshly formatted or new SD card, copy the contents of the
NOOBS_vX.zip
file. When it has finished copying, you should end up with something like the following screenshot of the SD card:
You can now put the card into your Raspberry Pi, connect it to a keyboard and display, and turn the power on. Refer to the
Connecting to Raspberry Pi
recipe for details on what you need, and how to do this.
By default, NOOBS will display via the HDMI connection. If you have another type of screen (or you don't see anything), you will need to manually select the output type by pressing 1, 2, 3, or 4, according to the following functions:
Key 1 stands for the
Standard HDMI
mode (the default mode)
Key 2 stands for the
Safe HDMI
mode (alternative HDMI settings if the output has not been detected)
Key 3 stands for
Composite PAL
(for connections made via the RCA analogue video connection)
Key 4 stands for
Composite NTSC
(again, for connections via the RCA connector)
This display setting will also be set for the installed operating system.
After a short while, you will see the NOOBS selection screen that lists the available distributions (the offline version only includes Raspbian). There are many more distributions that are available, but only the selected ones are available directly through the NOOBS system. Click on Raspbian, as this is the operating system being used in this book.
Press Enter or click on Install OS, and confirm that you wish to overwrite all the data on the card. This will overwrite any distributions previously installed using NOOBS but will not remove the NOOBS system; you can return to it at any time by pressing Shift when you turn the power on.
It will take around 20 to 40 minutes to write the data to the card depending on its speed. When it completes and the Image Applied Successfully message appears, click on OK, and Raspberry Pi will start to boot into Raspberry Pi Desktop.
The purpose of writing the image file to the SD card in this manner is to ensure that the SD card is formatted with the expected filesystem partitions and files required to correctly boot the operating system.
When Raspberry Pi powers up, it loads some special code contained within the GPU's internal memory (commonly referred to as binary blob by Raspberry Pi Foundation). The binary blob provides the instructions required to read the BOOT partition on the SD card, which (in the case of a NOOBS install) will load NOOBS from the RECOVERY partition. If at this point Shift is pressed, NOOBS will load the recovery and installation menu. Otherwise, NOOBS will begin loading the OS as specified by the preferences stored in the SETTINGS partition.
When loading the operating system, it will boot via the BOOT partition, using the settings defined in config.txt and options in cmdline.txt to finally load to the desktop on the root partition. Refer to the following diagram:
NOOBS allows the user to optionally install multiple operating systems on the same card and provides a boot menu to choose between them (with an option to set a default value in the event of a time-out period).
