Page
1
Nicholas H. Tollervey Programming with MicroPython EMBEDDED PROGRAMMING WITH MICROCONTROLLERS & PYTHON
Page
2
(This page has no text content)
Page
3
Nicholas H. Tollervey Programming with MicroPython Embedded Programming with Microcontrollers and Python Boston Farnham Sebastopol TokyoBeijing
Page
4
978-1-491-97273-1 [LSI] Programming with MicroPython by Nicholas H. Tollervey Copyright © 2018 Nicholas H. Tollervey. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐ tutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Susan Conant and Jeff Bleiel Production Editor: Colleen Cole Copyeditor: Amanda Kersey Proofreader: Marta Justak Indexer: WordCo Indexing Services Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest October 2017: First Edition Revision History for the First Edition 2017-09-25: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491972731 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming with MicroPython, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Page
5
Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. What Is MicroPython?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Why Micro? 2 Why Python? 4 MicroPython Genesis 9 Dive In! 12 2. PyBoard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 The Hardware 17 Developer Setup 18 3. BBC micro:bit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 The Hardware 25 Developer Setup 27 4. Adafruit Circuit Playground Express. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 The Hardware 34 Developer Setup 36 5. ESP8266 / ESP32. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 The Hardware 41 Developer Setup 42 ESP8266 42 ESP32 45 iii
Page
6
6. Thinking Embedded. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Human Drives 53 Abilities of Enchantment 56 Steps on the Ladder of Enchantment 60 7. Visual Feedback. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Blinkenlights 63 NeoPixels (Blinkenlights on Steroids) 67 Text, Images, and Animation 70 PyBoard Colour LCD Display 75 8. Input and Sensing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Buttons and Capacitative Touch 81 Accelerometers, Gestures, and Compasses 89 Sound, Light, and Temperature 91 Sensing with Peripherals 95 9. GPIO. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Pins 99 UART 103 SPI 105 I2C 108 Miscellaneous GPIO Techniques and Protocols 110 10. Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Circuit Playground Express Infrared 115 The micro:bit Radio 120 ESP8266/32 WiFi 128 MQTT 136 11. Sound and Music. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Bleeps and Bloops 141 Music 151 Speech 154 12. Robots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Trundle Bot 163 Racer Bot 169 13. Idiomatic MicroPython. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 The Zen of MicroPython 177 Memory 177 iv | Table of Contents
Page
7
Performance 182 14. Next Steps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 The Community 185 Going Deeper 186 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Table of Contents | v
Page
8
(This page has no text content)
Page
9
Foreword In late 2012, I had an idea to build a tiny, low-powered computing machine that could run scripts directly on the “bare metal” of the underlying hardware. The aim was to make it extraordinarily easy for anyone—no matter his or her background nor technical skill level—to be able to make a digital device that uses 1’s and 0’s to control the real world. In my particular case, I wanted an easier way to program the little robots that I was building at the time. At first I didn’t have any particular scripting language in mind for this device, but after investigating what would be a good choice for the language, and what people would like writing in and would find easy to learn, I chose Python. I was also interested in running a Kickstarter campaign, to see if people liked the idea and to perhaps begin to build a community around the project. The first Kickstarter campaign that ran at the end of 2013 really did kick start MicroPython: it raised funds to build 3,000 pyboards upon which MicroPython would run; it brought nearly 2,000 people into the initial community; and it attracted some very talented program‐ mers who volunteered their time and expertise to contribute to and improve Micro‐ Python. My background is theoretical physics, so I approach the design and development of MicroPython from a much more academic and research-oriented point of view, com‐ pared to simply engineering a solution to a problem. I believe this has been part of the reason for the success of MicroPython. From the outset it was not obvious that MicroPython would even work, that Python could at all be shrunk down to such a small size and run on tiny microcontrollers with very little memory. I treated the cre‐ ation of MicroPython like a research project and I used analysis combined with many coding tricks, ignoring a lot of software development principles, in order to just get it working. My general philosophy with MicroPython is to remain minimal yet usable. And the name embodies this: “micro” makes reference to microcontrollers and embedded sys‐ tems, but also gives the feeling of minimalism. “Python” is the language and is a very vii
Page
10
pragmatic and usable language, designed so humans can enjoy programming. On the one extreme, making everything too minimal hurts (the ultimate minimalism is nothing!), but on the other extreme, adding masses of usability features leads to over burden and excessive resource usage. These ideas about balancing minimalism with pragmatism apply not just to the design and development philosophy of Micro‐ Python but also to the wider computing industry and even beyond. Since the first Kickstarter MicroPython has seen fantastic growth, and I, along with many others in the community, have put an immense amount of work into Micro‐ Python, on both the hardware and software fronts. Today MicroPython stays true to its original goal of making it easy for anyone to digitally control the real world, and is widening its scope and seeing use by hobbyists and professionals, in education and research, as well as commercial products. MicroPython has actually formed its own little industry (soon to be much bigger!), and it’s very humbling to see one’s creation grow and attract interest from so many diverse people around the world, and for so many diverse applications. MicroPython is constantly improving, the community of users is growing every day, and the future looks very bright indeed. I hope that MicroPython continues to inspire people, continues to help people learn, and continues to be used to build and control systems, from coffee makers to space satellites. Digital computing devices need to be programmed and MicroPython provides an efficient and enjoyable way to do just that. Nicholas has been a great proponent of MicroPython since the early days and has contributed immensely to its development, most notably from the community and education side, and was key to the development and success of the micro:bit plat‐ form. He knows MicroPython very well, particularly from the point of view of an end user, and is well qualified to teach you about it. So dive into it, read and enjoy this fantastic initiation into the world of MicroPython, and go out and build some amazing digital devices! — Damien P. George Creator of MicroPython July 2017 viii | Foreword
Page
11
1 For example, you’re comfortable with Python’s syntax, understand how to define and call a function, and know how to control program flow in your code. Preface This is a book about MicroPython. MicroPython is a reimplementation of Python 3 for microcontrollers and embedded systems. It’s also a staggering feat of engineering to have a reimplemention of Python that works under such constrained circumstances. Why is this important? Micro‐ Python empowers people: it brings one of the most beautiful, easy-to-learn, and expressive programming languages to the world of embedded development. This book is intended for anyone who wants to learn how MicroPython is used for embedded development. I expect you to already know Python,1 but I don’t expect you to be an expert. For example, much of the material found in this book works well in an educational context; so rather than being a professional programmer, you might be a teacher or autodidact. I aim to give you the understanding, pointers, and ideas you need so you feel confi‐ dent when working on your own projects. Most importantly, I want this book to be both fun and inspiring. After reading it, I hope you have enough enthusiasm that you dive in, feet first, to making your own MicroPython-based doohickey, thingamabob, or enchanted object. This book will provide an overview of the sorts of devices that run MicroPython, prompt you into thinking about how best to develop and execute embedded projects, examine how MicroPython uses and interacts with hardware in order to fulfil various common outcomes and behaviours, and explore idiomatic MicroPython develop‐ ment. It will close with suggestions for next steps. As with any book, it contains compromises. Some may find it too technical, others not technical enough. Alternatively, some may feel I spend too much time on certain ix
Page
12
subjects and gloss over others. No matter the compromises I’ve had to make, my intention has been to write something that is easy to read and accessible while provid‐ ing enough context and signposts to resources for further study. My ultimate aim is simple: to help bring more people to the remarkable technology that is MicroPython. It’s important to note that MicroPython is a relatively young project. It’s an exciting time to get involved as a community evolves, tools and infrastructure are created, fea‐ tures are added, and bugs are fixed. Given the sharp uptake in conference talks, work‐ shops, and community meetings, there is a lot of enthusiasm in various communities for MicroPython and its nascent potential. Python programmers are learning how to create projects with embedded devices, embedded developers are discovering how much fun it is to use Python, and educators all over the world see MicroPython as a compelling platform for teaching children how to code. Furthermore, since MicroPython is a reimplementation of “regular” Python, it retains Python’s state as a mature language with an international community of engaged and active programmers. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. x | Preface
Page
13
This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/ntoll/programming-with-micropython. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming with MicroPython by Nicholas H. Tollervey (O’Reilly). Copyright 2018 Nicholas H.Tollervey, 978-1-491-97273-1”. If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Safari Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals. Members have access to thousands of books, training videos, Learning Paths, interac‐ tive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐ sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, Preface | xi
Page
14
John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others. For more information, please visit http://oreilly.com/safari. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/programming-with-micropython. To comment or ask technical questions about this book, send email to bookques‐ tions@oreilly.com. For more information about our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments I want to thank my reviewers who spotted many mistakes, suggested helpful ideas, and tactfully pointed out ways in which I could improve the text. It’s a privilege to work with such a talented, smart, and sympathetic group of people. Thank you, Dam‐ ien George, Radomir Dopieralski, Tim Golden, Kushal Das, Peter Inglesby, Michael Foord, Carlos Pereira Atencio, Roger Tollervey, Naomi Ceder, and Carol Willing. I also want to thank Scott Shawcroft, Tony DiCola, Limor Fried, and Phillip Torrone, all of Adafruit Industries. They have demonstrated infinite patience and provided invaluable help, advice, and support for those aspects of the book relating to Circuit‐ Python and Adafruit’s line of boards capable of running Python. The open and col‐ laborative nature of your amazing work is an inspiration to us all. xii | Preface
Page
15
Jo Claessens, Howard Baker, and Michael Sparks also deserve thanks as the origina‐ tors of the BBC micro:bit project. All of the MicroPython resources created for the micro:bit project are the work of an international community of volunteers. Special mention should be made of Dr. Mark Shannon, who has proven to be an outstanding contributor to this community (you can blame him for the speech synthesiser, among other things). Thanks are due to all of you, no matter how small or insignificant you may believe your contribution to be. My editor at O’Reilly, Jeff Bleiel, deserves special thanks for his encouragement, advice, and suggestions. I imagine editing a book written by someone halfway around the other side of the world is akin to cat herding via weekly video calls. Jeff, you do it with great aplomb! Without Damien George, the creator of MicroPython, none of this would be possible. In an industry where everyone has a brain the size of a planet, Damien is the Jupiter of our solar system. His extraordinary feat of miniaturization is, quite simply, an unprecedented achievement. Damien is backed by a growing online community of volunteers who support, fix, and contribute to MicroPython. Thanks to all of you who contribute and help with MicroPython. Most importantly of all, Damien is sup‐ ported by Viktoriya and Nate. I want to take this opportunity (and take the liberty of speaking on behalf of the global MicroPython community) to express our collective and sincere gratitude for all that you have done and continue to do. Bonzer effort Damo, Vik, and Nate! Last (but not least), I want to thank my wife, Mary, and our three children, Penelope, Sam, and William, for their continued love, support, and leg-pulling. Believe it or not, they are my muses, and I wouldn’t get anything done without them. Preface | xiii
Page
16
(This page has no text content)
Page
17
1 MicroPython works on many different devices. The four used in this book were chosen because they repre‐ sent the diversity of choice while being exemplars of the different sorts of device that are available. If you have a different sort of embedded device running MicroPython, the general principles outlined in this book remain the same, and it should be relatively simple to adapt the code examples. CHAPTER 1 What Is MicroPython? MicroPython is a reimplementation of the Python programming language that tar‐ gets microcontrollers and embedded systems. Microcontrollers are computers shrunk onto a single, very small chip. Embedded sys‐ tems are computers that function within a larger mechanical or electrical system. Embedded systems often use microcontrollers. This book introduces, explores, and explains MicroPython through four typical yet different devices,1 all of which have a microcontroller at their core. Such devices are very different to other sorts of computer. Most computers contain lots of parts: memory, storage, and processing are physically separate components containing various specialist chips. They may also contain additional parts for sound, graphics, and networking capabilities. Such computers are significantly more power‐ ful than the resource-constrained, microcontroller-based devices used in this book. This raises two important questions: • Why use such small, underpowered microcontroller-based devices? • Why use Python? Answering these questions illustrates why there is so much excitement surrounding MicroPython. 1
Page
18
2 Such text-based worlds are called MOOs (multiuser object orientation), and many are still available online. See https://en.wikipedia.org/wiki/MOO. Why Micro? Computers are amazing and seemingly magical things. For example, it is commonplace to make video calls to the other side of the world. Yet, just 20 years ago, this was the realm of science fiction. Any sufficiently advanced technology is indistinguishable from magic. —Arthur C. Clarke, Hazards of Prophecy: The Failure of Imagination The quote from science-fiction author Arthur C. Clarke suggests advanced technol‐ ogy appears as awe-inspiring magic. He forgot to mention that any sufficiently advanced technology is boring if it’s everywhere. Familiarity and ubiquity banish any sense of wonder for all but the most inquisitive. What do I mean? I am just old enough to remember a world without computers everywhere. First encounters with computers felt like magic. For instance, when I was at university in the 1990s, I spent hours connected to multiuser, text-based virtual worlds2 collaborat‐ ing with people connected to the server from all over the globe. It felt amazing to work, in real-time, with such a diverse and far-flung group of friends. I was especially pleased to discover I could chat with my fellow users, albeit in a textual sense. Being British I always enquired about the weather and found it strangely satisfying to instantly know conditions in San Francisco, Tel Aviv, or Singapore (usually, better than the weather in London). Knowing this information and, more importantly, knowing how to get such information felt like magic. Depending on your age, you probably experience one of two reactions to my example: 1. A tingle of nostalgia for those wonderful, exciting, and amazing early days of the internet. 2. Spare us reminiscences of the good old days; haven’t you heard of social media? Today, my own children are unsurprised when they video-call their grandparents from mobile phones. There is no longer a sense of amazement or wonder at such feats of engineering. Rather, like generations of children before them, they’re more impressed, intrigued, and entertained by the magic found in stories, legends, and fairy tales. Why? 2 | Chapter 1: What Is MicroPython?
Page
19
3 We’ll look at what it means for an object to be “enchanted” in greater detail later in the book, especially with reference to a framework of ideas suggested by Professor David Rose of the Massachusetts Institute of Tech‐ nology (MIT). It captures their imagination, whereas the use of everyday objects is humdrum and unremarkable. Take the world of J.K. Rowling’s Harry Potter books—a world populated by enchanted objects, magical forces, and incantations that bestow upon the user the ability to transform the world around them. Readers are drawn into the world because they imagine, “Wouldn’t it be amazing if I owned an invisibility cloak, flying broom, or could cast a spell that allowed me to breathe under water?” There is a sense of wonder in the magic found in Rowling’s world. The same could be said of Tolkien’s Middle Earth, ancient Greek legends, any number of super heroes and Force-wielding Jedi in the Star Wars movies. It’s fun to be immersed in such magical realms—they entertain by encouraging a sense of wonder while giving imagination the freedom to wander. It’s an opportunity to ask yourself, “What would I do if I were the magic wielding hero?” What has this to do with microcontrollers? Such computing devices allow programmers to ask a similar question. Imaginations are set free to roam but, just as in literature and life, there is always a tension between right and wrong, good and evil, yes or no. How? Everyday objects containing small, embedded microcontrollers become programma‐ ble. If they are programmable, they have agency (the state of being in action) and autonomy (the capability of choosing how to act given certain situations). Rather than being static, dead objects, they become independent and demonstrate behav‐ iours that bring them to life. Microcontroller-based devices are small enough to be stuck, sewn, soldered, and screwed in and on to other objects, turning everyday things into programmable “enchanted” objects.3 Most importantly, anyone with the right knowledge can “cast a spell” in code to modify the activities and behaviour of such objects. Just as in literary worlds, embedded systems appear magical in ways that engage and inspire. Consequently, our world becomes programmable in a way that is similar to how make-believe spells control a fictional, magical world. Imagination and a sense of wonder for computing is, in a sense, restored. We regain the opportunity to ask ourselves, “What would I do if I could program these devices?” As Seymour Papert tells us, someone who learns to write code “both acquires a sense of mastery over a piece of the most modern and powerful technology and establishes an intense contact with some of the deepest ideas from science, from mathematics, and from the art of Why Micro? | 3
Page
20
4 IEEE Spectrum, “The 2016 Top Programming Languages”, posted 26 Jul 2016. intellectual model building”. There are many examples of people inspired to build exciting hardware projects programmed with MicroPython. These encompass a diverse range of applications: robotics, sensing and reporting on the environment, satellite control, new musical instruments, art installations, counting South Atlantic krill, and quite a number of games, to name but a few. Objects containing embedded and potentially networked microcontrollers are “enchanted” in the same way objects are in fictional, magical worlds—you simply give them instructions. Just like in magical stories, it is important to understand how such incantations in code make enchanted embedded objects work for you. That’s where Python comes into the picture. Why Python? Python is an easy-to-learn, widely used, and expressive programming language (see Figure 1-1). It’s easy to write what you mean in Python with concise and simple code. Additionally, Python flourishes because it has a well-organised, proactive, diverse, and welcoming global community. Figure 1-1. In 2016 Python was ranked the third most popular programming language in the world by the IEEE. Guido van Rossum (the inventor of Python) correctly points out the omission of the “Embedded” flag thanks to MicroPython.4 4 | Chapter 1: What Is MicroPython?