MicroPython Cookbook - Marwan Alsabbagh - E-Book

MicroPython Cookbook E-Book

Marwan Alsabbagh

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

MicroPython is an open source implementation of Python 3 that runs in embedded environments. With MicroPython, you can write clean and simple Python code to control hardware instead of using complex low-level languages such as C and C++. This book guides you through all the major applications of the MicroPython platform to build and program projects that use microcontrollers.
This MicroPython book covers recipes that will help you experiment with the programming environment and hardware programmed in MicroPython. You'll find tips and techniques for building a variety of objects and prototypes that can sense and respond to touch, sound, position, heat, and light. This book will take you through the uses of MicroPython with a variety of popular input devices and sensors. You'll learn techniques to handle time delays and sensor readings, and apply advanced coding techniques to create complex projects. As you advance, you'll deal with Internet of Things (IoT) devices and integration with other online web services. In addition to this, you'll use MicroPython to make music with bananas and create portable multiplayer video games that incorporate sound and light animations into the gameplay.
By the end of this book, you'll have mastered the tips and tricks to troubleshoot your development problems and take your MicroPython project to the next level.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 435

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



MicroPython Cookbook
Over 110 practical recipes for programming embedded systems and microcontrollers with Python
Marwan Alsabbagh
BIRMINGHAM - MUMBAI

MicroPython Cookbook

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 author, 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 endeavored 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.

Commissioning Editor: Richa TripathiAcquisition Editor: Chaitanya NairContent Development Editor: Ruvika RaoTechnical Editor: Romy DiasCopy Editor:Safis EditingProject Coordinator:Vaidehi SawantProofreader: Safis EditingIndexer:Darshana JainGraphics: Alishon MendonsaProduction Coordinator: Alishon Mendonsa

First published: May 2019

Production reference: 1170519

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-83864-995-1

www.packtpub.com

mapt.io

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.

Why subscribe?

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

Packt.com

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.

Contributors

About the author

Marwan Alsabbagh has been coding in some form or other since before the web existed and has continued to develop software, with a particular passion for Python, his preferred programming language, for over a decade. He has been a speaker at a number of global Python conferences, where he has been known to present microcontroller projects with a healthy dose of humor and stage theatrics. The snow globe intruder alert system, which he created with his creative and curious daughters, was one of his favorite MicroPython projects. His research interests include software engineering, microcontrollers, and 3D printing.

I could not have reached this far in my life or in creating this book if it was not for the support of my loving family. Thank you for putting up with all the bananas I stole to make a whole chapter on programming microcontrollers with bananas.

About the reviewers

Arunkumar NT is 43 years of age, has completed his M.Sc. (Phy) and MBA (Finance), and is currently pursuing his CMA and CS qualifications. He has over 20 years' corporate experience and 2 years' experience of teaching MBA students. He is an entrepreneur and has previously worked for Airtel, Citi Finance, and ICICI Bank. He has also worked on the Python for Finance book.

I would like to thank my parents (my father for his support as a backup and filtering system, and my mother for her trust despite my repeated failures), my brothers (Anand NT for his critical acknowledgement and Prabhanjan NT for his love and support), my wife (Bharathi K), and my children (Vardhini AT and Charvangi AT). I would also like to thank my gurus (Prof. Badwe (deceased) and Prof. Sundararajan) and, of course, not forgetting my friends—Dr. Sreepathi B and Anand Karnawat.

Bhaumik Vaidya is an experienced computer vision engineer and mentor. He has worked extensively on OpenCV and the TensorFlow library to solve computer vision problems. He is a University gold medalist at the master's level, and is now doing his PhD on the acceleration of computer vision algorithms built using OpenCV and deep learning libraries, such as TensorFlow and Keras, on GPUs. He, along with his PhD mentor, has also received an NVIDIA Jetson TX1, which is an embedded development platform, as a research grant from NVIDIA. He has previously worked in the VLSI domain as an ASIC verification engineer. He has published numerous research papers in reputable journals, has filed two provisional patents, and has written one book on computer vision and GPU programming.

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

MicroPython Cookbook

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewers

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

Download the color images

Conventions used

Sections

Getting ready

How to do it...

How it works...

There's more...

See also

Get in touch

Reviews

Getting started with MicroPython

What is MicroPython?

What is a microcontroller?

What is CircuitPython?

What is the Circuit Playground Express?

Where to buy

References

Flashing the microcontroller firmware

Getting ready

How to do it...

How it works...

There's more...

See also

Executing your first program

Getting ready

How to do it...

How it works...

There's more...

See also

Using screen to access the REPL

Getting ready

How to do it...

How it works...

There's more...

See also

Using Mu to access the REPL

Getting ready

How to do it...

How it works...

There's more...

See also

Executing commands in the REPL

Getting ready

How to do it...

How it works...

There's more...

See also

Using the auto-reload feature

Getting ready

How to do it...

How it works...

There's more...

See also

Updating the CircuitPython Library

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling LEDs

The Adafruit Circuit Playground Express layout

Turning on the pin 13 LED

Getting ready

How to do it...

How it works...

There's more...

See also

Setting the brightness of the NeoPixel

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling the color of a single NeoPixel

Getting ready

How to do it...

How it works...

There's more...

See also

Displaying an LED color using the RGB and hex code

Getting ready

How to do it...

How it works...

There's more...

See also

Setting an LED color using color names

Getting ready

How to do it...

How it works...

There's more...

See also

Setting all NeoPixels to the same color

Getting ready

How to do it...

How it works...

There's more...

See also

Setting a range of NeoPixels to one color

Getting ready

How to do it...

How it works...

There's more...

See also

Generating random NeoPixel LED colors

Getting ready

How to do it...

How it works...

There's more...

See also

Creating LED animations with random colors

Getting ready

How to do it...

How it works...

There's more...

See also

Creating LED animations with rainbow colors

Getting ready

How to do it...

How it works...

There's more...

See also

Creating Sound and Music

The Adafruit Circuit Playground Express layout

Making a beeping sound

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling tone, frequency, and duration

Getting ready

How to do it...

How it works...

There's more...

See also

Playing a musical note

Getting ready

How to do it...

How it works...

There's more...

See also

Playing a melody

Getting ready

How to do it...

How it works...

There's more...

See also

Sounding the alarm

Getting ready

How to do it...

How it works...

There's more...

See also

Playing WAV files

Getting ready

How to do it...

How it works...

There's more...

See also

Converting MP3 files to WAV files

Getting ready

How to do it...

How it works...

There's more...

See also

Starting and stopping tones

Getting ready

How to do it...

How it works...

There's more...

See also

Interacting with Buttons

The Adafruit Circuit Playground Express layout

Detecting push button presses

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling LEDs with push buttons

Getting ready

How to do it...

How it works...

There's more...

See also

Reading a slide switch

Getting ready

How to do it...

How it works...

There's more...

See also

Calling functions on the button state change

Getting ready

How to do it...

How it works...

There's more...

See also

Moving active LEDs with push buttons

Getting ready

How to do it...

How it works...

There's more...

See also

Playing a beep on the button press

Getting ready

How to do it...

How it works...

There's more...

See also

Detecting touch on a touchpad

Getting ready

How to do it...

How it works...

There's more...

See also

Monitoring the touchpad raw measurements

Getting ready

How to do it...

How it works...

There's more...

See also

Adjusting the touch threshold

Getting ready

How to do it...

How it works...

There's more...

See also

Reading Sensor Data

Circuit Playground Express sensors

Reading temperature readings

Getting ready

How to do it...

How it works...

There's more...

See also

Reading brightness levels from the light sensor

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a light meter

Getting ready

How to do it...

How it works...

There's more...

See also

Reading data from the motion sensor

Getting ready

How to do it...

How it works...

There's more...

See also

Detecting a single or double tap

Getting ready

How to do it...

How it works...

There's more...

See also

Detecting a shake

Getting ready

How to do it...

How it works...

There's more...

See also

Beeping on a shake

Getting ready

How to do it...

How it works...

There's more...

See also

Button Bash Game

Technical requirements

Circuit Playground Express power

Creating a class to detect a button state change

Getting ready

How to do it...

How it works...

There's more...

See also

Creating your own Python modules

Getting ready

How to do it...

How it works...

There's more...

See also

Adding button interactions to the event loop

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a generator to get pixel colors

Getting ready

How to do it...

How it works...

There's more...

See also

Showing scores with the ScoreBoard class

Getting ready

How to do it...

How it works...

There's more...

See also

Detecting winners with the ScoreBoard class

Getting ready

How to do it...

How it works...

There's more...

See also

Adding the ScoreBoard class to the event loop

Getting ready

How to do it...

How it works...

There's more...

See also

Fruity Tunes

Technical requirements

Circuit Playground Express touchpads

Creating a class to react to touch events

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a function to enable speaker output

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a function to play audio files

Getting ready

How to do it...

How it works...

There's more...

See also

Using the NeoPixel object to control pixels

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a touch handler to play sounds

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a touch handler to light up pixels

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an event loop to handle all touch events

Getting ready

How to do it...

How it works...

There's more...

See also

Let's Move It, Move It

Technical requirements

DC motors

Servos

Adafruit CRICKIT

Where to buy

Tuning a servo to the correct pulse width

Getting ready

How to do it...

How it works...

There's more...

See also

Setting the actuation range of a servo

Getting ready

How to do it...

How it works...

There's more...

See also

Setting the angle of a servo

Getting ready

How to do it...

How it works...

There's more...

See also

Sweeping a servo

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling servos with buttons

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling multiple servos

Getting ready

How to do it...

How it works...

There's more...

See also

Turning on a DC motor

Getting ready

How to do it...

How it works...

There's more...

See also

Setting the speed and direction of a DC motor

Getting ready

How to do it....

How it works...

There's more...

See also

Controlling a DC motor with buttons

Getting ready

How to do it...

How it works...

There's more...

See also

Coding on the micro:bit

Technical requirements

The micro:bit

Using Mu to flash code onto the micro:bit

Getting ready

How to do it...

How it works...

There's more...

See also

Using Mu to get a REPL on the micro:bit

Getting ready

How to do it...

How it works...

There's more...

See also

Displaying a single character on the LED display

Getting ready

How to do it...

How it works...

There's more...

See also

Displaying a built-in image

Getting ready

How to do it...

How it works...

There's more...

See also

Displaying scrolling text

Getting ready

How to do it...

How it works...

There's more...

See also

Showing which button has been pressed

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a countdown timer

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling the ESP8266

Technical requirements

The Adafruit Feather HUZZAH ESP8266

Where can you buy these?

Using the REPL over a serial connection

Getting ready

How to do it...

How it works...

There's more...

See also

Scanning for available Wi-Fi networks

Getting ready

How to do it...

How it works...

There's more...

See also

Configuring settings for AP mode

Getting ready

How to do it...

How it works...

There's more...

See also

Connecting to an existing Wi-Fi network

Getting ready

How to do it...

How it works...

There's more...

See also

Using the WebREPL over Wi-Fi

Getting ready

How to do it...

How it works...

There's more...

See also

Transferring files with the WebREPL CLI

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling the blue and red LEDs

Getting ready

How to do it...

How it works...

There's more...

See also

Interacting with the Filesystem

Technical requirements

Remounting the filesystem

Getting ready

How to do it...

How it works...

There's more...

See also

Listing files

Getting ready

How to do it...

How it works...

There's more...

See also

Removing files

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a directory

Getting ready

How to do it...

How it works...

There's more...

See also

Reading a file's contents

Getting ready

How to do it...

How it works...

There's more...

See also

Writing a file's contents

Getting ready

How to do it...

How it works...

There's more...

See also

Calculating disk usage

Getting ready

How to do it...

How it works...

There's more...

See also

Networking

Technical requirements

Performing a DNS lookup

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a function to wait for internet connectivity

Getting ready

How to do it...

How it works...

There's more...

See also

Performing an HTTP request using raw sockets

Getting ready

How to do it...

How it works...

There's more...

See also

Performing an HTTP request using the urequests library

Getting ready

How to do it...

How it works...

There's more...

See also

Fetching JSON data from a RESTful web service

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an HTTP server

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a web handler module

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling LEDs through the web server

Getting ready

How to do it...

How it works...

There's more...

See also

Developing a RESTful API to control the LEDs

Getting ready

How to do it...

How it works...

There's more...

See also

Interacting with the Adafruit FeatherWing OLED

The Adafruit FeatherWing OLED

Where to buy it

Technical requirements

Detecting button presses with GPIO pins

Getting ready

How to do it...

How it works...

There's more...

See also

Connecting to the SSD1306 display

Getting ready

How to do it...

How it works...

There's more...

See also

Filling and clearing the display

Getting ready

How to do it...

How it works...

There's more...

See also

Setting pixels on the display

Getting ready

How to do it...

How it works...

There's more...

See also

Drawing lines and rectangles on the display

Getting ready

How to do it...

How it works...

There's more...

See also

Writing text on the display

Getting ready

How to do it...

How it works...

There's more...

See also

Inverting colors on the display

Getting ready

How to do it...

How it works...

There's more...

See also

Building an Internet of Things (IoT) Weather Machine

Technical requirements

Retrieving weather data from the internet

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a function to get a city's weather

Getting ready

How to do it...

How it works...

There's more...

See also

Randomly selecting cities

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a Screen object for text handling

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a function to show a city's weather

Getting ready

How to do it...

How it works...

There's more...

See also

Providing visual feedback when fetching data

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a function to display the weather for a random city

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an IoT button to show the weather around the world

Getting ready

How to do it...

How it works...

There's more...

See also

Coding on the Adafruit HalloWing Microcontroller

The Adafruit HalloWing M0 Express

Where to buy

Technical requirements

Discovering I2C devices

Getting ready

How to do it...

How it works...

There's more...

See also

Reading data from the accelerometer using I2C

Getting ready

How to do it...

How it works...

There's more...

See also

Detecting board-flipping with the accelerometer

Getting ready

How to do it...

How it works...

There's more...

See also

Controlling screen brightness

Getting ready

How to do it...

How it works...

There's more...

See also

Displaying a bitmap image

Getting ready

How to do it...

How it works...

There's more...

See also

Listing all image files

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a joke-telling machine

Getting ready

How to do it...

How it works...

There's more...

See also

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

MicroPython is a lean implementation of the Python 3 programming language that is capable of running on a wide range of microcontrollers. It provides the majority of features in the Python programming language, such as functions, classes, lists, dictionaries, strings, reading and writing files, list comprehensions, and exception handling to these microcontrollers.

Microcontrollers are tiny computers that usually include a CPU, memory, and input/output peripherals. Even though they will have more limited resources compared to a PC, they can be made to a much smaller dimension, with less power consumption and at a lower cost. These strengths make it possible to use them in a wide range of new applications that weren’t possible before.

This book will cover a number of different features in the MicroPython language, as well as a number of different microcontroller boards. The initial chapters will provide simple and easy to understand recipes to get these boards to interact with people and their environment. Topicsrangingfrom reading temperature, light, and motion data from sensors to interacting with push buttons, slide switches, and touchpads will also be covered. Producing output on these boards with audio playback and LED animations will also be covered in the early chapters. Once this foundation is in place, we will build more involved projects, such as interactive two-player games, electronic musical instruments, and an Internet of Things (IoT) weather machine. You will be able to take the skills you learn from these recipes and directly apply them to your own embedded projects.

Who this book is for

This book aims to help people apply the power and ease of use of the Python language to the versatility of microcontrollers. Prior knowledge of Python is expected in order to understand this book.

What this book covers

Chapter 1, Getting Started with MicroPython, introduces the Adafruit Circuit Playground Express microcontroller and teaches the core skills for using MicroPython on this hardware.

Chapter 2, Controlling LEDs, covers methods of controlling NeoPixel LEDs, the color of the lights, and how to create animated light shows by controlling the timing of light changes on the board.

Chapter 3, Creating Sound and Music, discusses methods of how to make sounds and playmusic on the Adafruit Circuit Playground Express. Topics such as making the board beep at a certain sound frequency and playing music files using the WAV file format and the board's built-in speakers will be covered.

Chapter 4, Interacting with Buttons, shows methods of interacting with the buttons and touch pads that come on board with the Adafruit Circuit Playground Express. The basics of detecting when a button is pressed or not, as well as advanced topics, such as fine tuning the touch threshold of the capacitive touch pads, will be discussed.

Chapter 5, Reading Sensor Data, introduces methods of reading sensor data from a number of different types of sensors, such as temperature, light, and motion sensors.

Chapter 6, Button Bash Game, guides us to create a two-player game called Button Bash that you can play directly on the Circuit Playground Express using the push buttons, NeoPixels, and built-in speakers.

Chapter 7, Fruity Tunes, explains how to create a musical instrument with the Adafruit Circuit Playground Express and some bananas. Touchpads will be used to interact with the bananas and play different musical sounds each time you touch a different banana.

Chapter 8, Let's Move It, Move It, introduces the Adafruit CRICKIT hardware add-on that will help control motors and servos through our Python scripts; in particular, their speed, rotational direction, and angle will be controlled through these scripts.

Chapter 9, Coding on the micro:bit, covers methods of interacting with the micro:bit platform. How to control its LED grid display and interact with the buttons that come on board will be discussed.

Chapter 10, Controlling the ESP8266, introduces the Adafruit Feather HUZZAH ESP8266 microcontroller, and discusses its features and strengths compared to other microcontrollers. Topics such as connecting to Wi-Fi networks, using the WebREPL, and transferring files over Wi-Fi will be covered.

Chapter 11, Interacting with the Filesystem, discusses a number of topics related to the operating system (OS), such as listing files, removing files, creating directories, and calculating disk usage.

Chapter 12, Networking, discusses how to perform a number of different network operations, such as DNS lookups, implementing an HTTP client, and HTTP servers.

Chapter 13, Interacting with the Adafruit FeatherWing OLED, introduces the Adafruit FeatherWing OLED hardware add-on, which can be attached to the ESP8266 to add a display to an internet-connected microcontroller, to display display text graphics and interact with the user using the included three hardware push buttons.

Chapter 14, Building an IoT Weather Machine, explains how to create an IoT device that will retrieve weather data and show it to the user at the press of a button from the IoT device itself.

Chapter 15, Coding on the Adafruit HalloWing, introduces the Adafruit HalloWing microcontroller, which comes with a 128x128 full-color Thin-Film Transistor (TFT) display built into it, providing the ability to display rich graphical images on the microcontroller.

To get the most out of this book

Readers are expected to have a basic knowledge of the Python programming language. It would be beneficial for readers to have a basic understanding of importing packages and working with the REPL to get the most out of this book.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.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.packtpub.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 at https://github.com/PacktPublishing/MicroPython-Cookbook. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781838649951_ColorImages.pdf.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it...

This section contains the steps required to follow the recipe.

How it works...

This section usually consists of a detailed explanation of what happened in the previous section.

There's more...

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.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.

Reviews

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 packtpub.com.

Getting started with MicroPython

It's an exciting time to work with technologies such as MicroPython. They make tiny and inexpensive hardware devices more accessible, as you can use a high-level language such as Python to code on them. Tasks such as retrieving data from web services can easily be done in a few lines of code, compared to other microcontroller languages that would require many more steps, because they operate at such a low level compared to Python. This is very empowering, as you will get results faster and be able to iterate through different designs and prototypes in a shorter amount of time.

In this chapter, we will provide you with the essential skills to get started and be productive with the software and hardware needed to run MicroPython. You'll learn how to update the firmware and libraries on the device. Recipes to load your first program on the board and use advanced features, such as auto-reloading your code, will also be covered. Finally, a number of recipes will cover the usage of the REPL that is a powerful way to quickly interact and experiment with the available components on MicroPython devices.

In this chapter, we will be covering the following recipes:

Flashing the microcontroller firmware

Executing your first program

Using screen to access the REPL

Using Mu to access the REPL

Executing commands in the REPL

Using the auto-reload feature

Updating the CircuitPython Library

What is MicroPython?

MicroPython is the creation of the Australian programmer and physicist Damien George, who launched a Kickstarter campaign in 2013 to support the development of the language and the initial microcontroller hardware that it would run on. After the success of the project, more and more devices (which have a variety of chipsets from different manufactures) have become supported by MicroPython, creating a wide range of devices from which to choose when you make a project using MicroPython.

MicroPython is a lean implementation of the Python 3 programming language that is capable of running on hardware with very limited resources, such as microcontrollers. MicroPython has implemented the majority of features in the Python programming language, such as functions, classes, lists, dictionaries, strings, reading and writing files, list comprehensions, and exception handling.

The REPL is also implemented and can be interacted with using a serial connection. A selection of the core Python libraries is provided, which allows a range of applications to be implemented. The JSON and socket libraries allow web client and server implementations, making Python-based Internet of Things (IoT) projects on microcontrollers a reality.

By bringing one of the most popular and easy to use programming languages to the exciting world of embedded computing, MicroPython opens up new doors for makers and entrepreneurs to bring their creations to life. This book will explore the different ways to leverage the MicroPython language with a variety of unique microcontroller devices that each bring a different set of capabilities to the table.

One of the unique and fascinating aspects of running MicroPython on microcontrollers is that it does not run on an operating system (OS), but instead runs directly on bare metal. These unique characteristics manifest themselves in many ways, such as the ability to run your Python code at the instant the hardware is powered on, as there is no OS that needs to boot up.

The other aspect of this is that the Python code has direct access to control and interact with the hardware, creating hardware possibilities that would not be possible with a typical Python application running on an OS.

As we know now that MicroPython runs on a microcontroller, let's see what microcontrollers are all about.

What is a microcontroller?

Microcontrollers are small computers on a single chip. They usually include a CPU, memory, and input/output peripherals. They will have more limited computing resources than what might be found on a modern PC.

Compared to a PC, however, they can be made to a much smaller dimension, allowing them to be embedded in all sorts of electronic and mechanical devices. Their power consumption is often far less in orders of magnitude, thus providing battery life for days. They have a much lower cost per unit, which opens up possibilities of having hundreds of such devices to collect sensor data across a broad geographical area and still be financially feasible.

Traditionally, it was a difficult process to create applications on microcontrollers because you would have to write very low-level code that took time and was difficult to debug. MicroPython brings the ease of use of Python to microcontroller. It's able to provide this easier interaction with the hardware, and yet still work in such a resource constrained environment and provide a wide range of functionality with a strong level of responsiveness.

What is CircuitPython?

CircuitPython is a branch of MicroPython created by Adafruit Industries that makes working with microcontrollers simpler. It has excellent support for many of the sensors and components that come with Adafruit devices through its Python libraries. It also allows code to be easily loaded and run without having to install any additional software applications by exposing the microcontroller's storage as a disk drive.

Generally, the differences between MicroPython and CircuitPython are minor, and, in many instances, code will run the same on both implementations.

What is the Circuit Playground Express?

The Adafruit Circuit Playground Express is an inexpensive, yet versatile microcontroller with a rich set of input and output devices that comes built-in with the device. The following are some of the main hardware features present in this device:

10 mini NeoPixels, each with the ability to display a full range of colors

As motion sensor (triple-axis accelerometer with tap detection and free-fall detection)

A temperature sensor

A light sensor

A sound sensor

A mini speaker

Two push buttons, which are labeled A and B

A slide switch

An infrared receiver and transmitter

Eight alligator-clip friendly input/output pins

Supports I2C and PWM output

Seven capacitive touch inputs

A red LED

A reset button

An ATSAMD21 ARM Cortex M0 processor, running at 3.3 V and 48 MHz

2 MB of flash storage

A micro USB port for connecting to a PC

These will be the only required devices for eight chapters. Later chapters will introduce a different set of devices.

Please refer to https://learn.adafruit.com/welcome-to-circuitpython?view=allfor more information.

Where to buy

The Adafruit Circuit Playground Express can be purchased directly from Adafruit (https://www.adafruit.com/product/3333). It can also be purchased from online retailers, such as Amazon and Pimoroni.

For the purpose of this book, we recommend buying the Circuit Playground Express – Base Kit (https://www.adafruit.com/product/3517) and also includes a USB cable and battery pack so that projects can easily be made portable.

References

Here are a few references:

The MicroPython web page at

http://micropython.org

The MicroPython project on Kickstarter at

https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers

An article in microcontrollers on PC Mag at

https://www.pcmag.com/encyclopedia/term/46924/microcontroller

The Adafruit learning guide on CircuitPython at

https://learn.adafruit.com/welcome-to-circuitpython/what-is-circuitpython

The CircuitPython official documentation at

https://circuitpython.readthedocs.io

Flashing the microcontroller firmware

In this recipe, we will show how to flash the firmware on the Circuit Playground Express with the latest CircuitPython firmware. There are two reasons to this before you start working with this device. First, the device also supports the Microsoft MakeCode programming environment and flashing the device with the CircuitPython firmware prepares it for use with the Python language.

Second, the CircuitPython language is under constant development, with a release every few months, so it is a good idea to update the firmware from time to time to load the latest release of the language onto the board.

Getting ready

This chapter's introduction gives us directions on how to buy the Circuit Playground Express,which will be required for all the recipes in this chapter.A USB micro B cable and a computer running macOS, Windows, or Linuxwillalsobe required.

How to do it...

Let's look at the following steps:

Download the latest CircuitPython Circuit Playground Express UF2 file (

https://github.com/adafruit/circuitpython/releases/latest

). The name of the UF2 file for version 3.1.2 of CircuitPython is

adafruit-circuitpython-circuitplayground_express-3.1.2.uf2

. For each release of CircuitPython, there are many different

uf2

files for different supported microcontrollers. Make sure that you download the file for the Circuit Playground Express device.

We will use the latest stable version of CircuitPython in this recipe, which is currently 3.1.2.

Connect the USB cable to the Circuit Playground Express and the computer.

Double-click the reset button located at the center of the board. If all goes well, you will see all the LEDs turn green; otherwise, there is most likely an issue with the USB cable being used. In some instances, if a double-click doesn't work, try a single click of the reset button.

You will see a new disk appear called

CPLAYBOOT

:

Copy the UF2 file into this drive.

Once the UF2 file has been fully written to the device, the firmware will be updated and a new drive will appear, called

CIRCUITPY

:

Now, our Circuit Playground Express can be used.

How it works...

Traditionally, special software has had to be installed and used to handle the delicate process of flashing a microcontroller. Microsoft developed the UF2 method, which greatly simplifies the process by not requiring any special software or command-line execution to flash the microcontroller.

Once the board is placed into the bootloader mode, it will then expect a UF2 file to be saved to it. When the UF2 is copied to the drive, the microcontroller will detect that the file copy has been completed and then automatically proceed to flash the microcontroller and restart the device, at which point the device is reattached and ready to be used.

The UF2 file format can be found athttps://github.com/Microsoft/uf2.

There's more...

The UF2 approach to flashing microcontroller firmware makes the process easier and faster compared to previous approaches. Not all MicroPython boards support the UF2 method and so require the more involved approach of installing special software to do the firmware flashing. The exact process and software required varies between different boards and manufactures.

When you use this flashing software, it will frequently require that you know the exact name of the serial device that the device appears as on your computer. The naming of these devices varies between Windows, Linux, and macOS. This type of software is usually required to be run in the Terminal, so you'll have to have some command-line knowledge to inter with it. For all these reasons, the use of UF2 with supported devices such as the Circuit Playground Express is the preferred way of starting your experimentation with MicroPython.

See also

There are a number of resources, both on the Adafruit and Microsoft websites, relating to the process described in this recipe. Here are a few references:

Documentation of updating CircuitPython can be found at

https://learn.adafruit.com/adafruit-circuit-playground-express/circuitpython-quickstart

.

The UF2 process is explained in more detail at

https://makecode.com/blog/one-chip-to-flash-them-all

.

Executing your first program

In this recipe, we will show you how to load your first program on the Circuit Playground Express and how to modify the program and reload it. The program will then light one of the ten NeoPixels that come available on the board.

Getting ready

Once theCircuit Playground Expresshas had theCircuitPythonfirmware flashed, you may load Python scripts onto the board and run them.

How it works...

When the device is turned on it looks for certain files, such as code.py ormain.py, that, if found, will be executed as part of the startup process. In this way, you can specify the code you want run when the device is powered on. The script first imports the adafruit_circuitplayground.express library so that it can control theNeoPixels.The firstNeoPixelis set to the color red by giving ita set of appropriate RGBvalues.

Finally, the script will sleep for 60 seconds so that the LED remains lit for one minute before the script ends execution.

There's more...

Now that the board has been loaded with a Python script, it can be disconnected from the computer and have the battery pack attached to it.Once the battery pack is powered on by the script, it should run and light up the selectedNeoPixel.

This is a simple way to create portable and inexpensive projects that can have a code running directly from the board with noneed for aconnected PC and canbepoweredsimplybythree AAA batteries.

See also

There are a number of files that CircuitPython looks for when it boots up, which are described at https://learn.adafruit.com/welcome-to-circuitpython?view=all#naming-your-program-file-7-30.

Using screen to access the REPL

Linux and macOS have powerful Terminal emulators, such as screen, that can be used to directly connect to the device's Read-Eval-Print Loop (REPL) over a serial (USB) connection. This recipe will show how to connect to the REPL and start running a Python code interactively.

Getting ready

EithermacOSor aLinuxcomputer may be used for this recipeand may require the screen command tobe available.On macOS, theScreen applicationis built-in and so requires no installation. On Ubuntu, the Linux Screen can be installed with theapt install screencommand.

How to do it...

Let's have a look at how to connect the REPL and run the code:

Open the computer's Terminal application.

List device names before plugging in device by running

ls /dev/ttyACM*

on Linux or

ls /dev/tty.*

on macOS.

Connect the board to your computer with a USB cable.

List the device names again with the same command to discover the device name of the board.

If the device name is

/dev/ttyACM0

, then the

screen

command would be

screen /dev/ttyACM0 115200

.

Enter the command in the Terminal and start the Screen application.

I

f Screen is able to connect successfully, the Python REPL should appear on the Terminal with output similar to the following text:

Adafruit CircuitPython 3.1.2 on 2019-01-07; Adafruit CircuitPlayground Express with samd21g18

>>>

If the prompt doesn't appear, you can try pressing

Ctrl

+

C

and then press

Enter

, which will stop the currently running Python script and run the REPL with the following message:

Press any key to enter the REPL. Use CTRL-D to reload.

Once the REPL prompt appears, we will have to test if the prompt is working by evaluating the

1+1

expression.

It should produce the following output:

>>> 1+1

2

How it works...

The Circuit Playground Express exposes a serial deviceover the USB connection,which can be accessed by a number of different Terminal emulator programs.Besidesscreen, there are other programs, such as picocom and minicom, that may also be used.

The last parameter that was set as 115,200 in the command sets the baud rate of the connection, which should be set at that speed.Once the connection is successfully established, an interactive session is commenced that allows expressions to be directly evaluated on the device and the output is directly displayed on the Terminal.

There's more...

Many of the recipes in the book will introduce the different parts of a script using the REPL. This will give you a chance to get immediate feedback as you run each snippet of code. Once you've entered the different snippets in the REPL you can also use REPL features to assist in your experimentation with the code. You can use the up and down arrow keys to move through the history of commands that have been entered in the REPL. For example, if you had just executed a line of code in the REPL that turned on a specific pixel on the board, you could press the up key and change which pixel is lit up by editing the line and pressing Enter again.

See also

Here are a few references:

The use of the REPL on CircuitPython boards is discussed in detail at

https://learn.adafruit.com/welcome-to-circuitpython/the-repl

.

Details on using the REPL to access MicroPython can be found at

https://learn.adafruit.com/micropython-basics-how-to-load-micropython-on-a-board/serial-terminal

.

Using Mu to access the REPL