29,99 €
This book is a one-stop guide for learning BBC Micro:bit with MicroPython, exploring many hardware components and programming techniques to provide detailed insights into developing practical applications with the Micro:bit. It will also show you how hardware components can be manipulated using a combination of Micro:bit and MicroPython for developing practical projects. BBC Micro:bit in Practice will help you gain a holistic understanding of the BBC Micro:bit platform and MicroPython programming, guiding you through mini projects aimed at developing practical knowledge of circuit design and writing programs. You’ll learn how to write programs for working with built-in LEDs and buttons, interfacing external LEDs, buttons, motors, buzzers, and much more. You’ll also work with built-in radio, speakers, accelerometer, and a compass. You’ll dive into concepts related to the Micro:bit filesystem, interfacing external displays, and working with libraries in detail before exploring sewable circuits and wearable technology.
After reading this Micro:bit book, you’ll understand how to apply principles in electronics and MicroPython to create interesting real-life projects from scratch.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 242
Veröffentlichungsjahr: 2022
A hands-on guide to building creative real-life projects with MicroPython and the BBC Micro:bit
Ashwin Pajankar
Abhishek Sharma
Sandeep Saini
BIRMINGHAM—MUMBAI
Copyright © 2022 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(s), 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.
Group Product Manager: Rahul Nair
Publishing Product Manager: Surbhi Suman
Senior Editor: Runcil Rebello
Technical Editor: Arjun Varma
Copy Editor: Safis Editing
Project Coordinator: Ashwin Kharwa
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Nilesh Mohite
Marketing Coordinator: Gaurav Christian
Senior Marketing Coordinator: Nimisha Dua
First published: December 2022
Production reference: 1171122
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80461-012-1
www.packt.com
To Pandit Jawaharlal Nehru and Sardar Vallabhbhai Patel, the architects of modern India, whose names will always be remembered and cherished.
– Ashwin Pajankar
Ashwin Pajankar is an author, a YouTuber, and an instructor. He graduated from the International Institute of Information Technology, Hyderabad, with an MTech in computer science and engineering. He has been writing programs for over two and a half decades. He is proficient in Linux, Unix shell scripting, C, C++, Java, JavaScript, Python, PowerShell, Golang, HTML, and assembly language. He has worked on single-board computers such as Raspberry Pi and Banana Pro. He is also proficient with microcontroller boards such as Arduino and the BBC Micro:bit. He is currently self-employed and teaches on Udemy and YouTube. He also organizes programming boot camps for working professionals and software companies.
I want to thank my friend Anuradha who encouraged me to write this book. I thank the other two authors of the book, Abhishek and Sandeep. Finally, I would like to express my heartfelt gratitude toward the Packt team members – Neil, Runcil, Preet, Sayali, Surbhi, and Yogesh – for their valuable guidance and assistance.
Abhishek Sharma completed his BE in electronics engineering from Jiwaji University, Gwalior, India, and his PhD in engineering from the University of Genoa, Italy. He is presently working as an assistant professor in the Department of Electronics and Communication Engineering at the LNM Institute of Information and Technology, Jaipur, India. He is the coordinator of the ARM University Partner Program, Texas Instruments Lab, and Intel Intelligent Lab at the LNM Institute of Information and Technology and the center lead of LNMIIT-Center of Smart Technology (L-CST). His research interests are real-time systems and emerging technologies.
I would like to first and foremost thank my loving wife, Mano, and daughters, Madhu and Mihu, for their continued support, patience, and encouragement throughout the long process of writing this book. Thanks also to my parents for their support and faith.
Sandeep Saini works as an assistant professor in the Department of Electronics and Communication Engineering at the LNM Institute of Information and Technology, Jaipur, India. He has taught robotics and electronics subjects at the university level in India and abroad for over a decade. He has taught more than 8,000 students online and offline during this time. He received a BTech and MS in electronics and communication engineering from the International Institute of Information Technology, Hyderabad, India. He received his PhD from Malaviya National Institute of Technology (MNIT), Jaipur, India. He has written 6 books and published 35 peer-reviewed journals and conference papers.
I would like to first and foremost thank my parents, my wife, and my daughter for their continued support, patience, and encouragement throughout the long process of writing this book.
Emmanuel Efegodo is a software developer and an ed-tech practitioner with a degree in computer engineering. He enjoys programming generally but is mostly in love with JavaScript and the Jamstack architecture. He had his high school education in Gambia and his tertiary education in Nigeria. He strives to become an agent of change in Africa’s digital education ecosystem, particularly in software design. He heads the curriculum team of JuniorX Innovation Academy with Obi Brown, a Google-certified ed-tech innovator, where he also teaches physical computing with the BBC Micro:bit, Python programming, and game development to young Africans.
The BBC Micro:bit is a very popular microcontroller board. It comes packed with features such as a display and various sensors. This board comes with a computing unit and the possibility to connect with various other peripheral devices. It is used by beginners to learn about the fundamentals of computer programming, electronics, and physical computing. It can be programmed using many programming frameworks such as MicroPython and Scratch.
The book covers many aspects of programming the BBC Micro:bit with the MicroPython programming language. The book begins with the basics and setup. Then, it covers the fundamentals of the Python programming language. After that, it explores various aspects of physical computing with the BBC Micro:bit, such as the programming of LEDs, buttons, buzzers, stepper motors, analog input, Pulse Width Modulation (PWM), internal sensors, and radio communication. It also explores topics such as the filesystem and wearable computing with a BBC Micro:bit.
After following the concepts, circuits, and code examples in this book, you will be comfortable with building your own project using the BBC Micro:bit with MicroPython as the preferred programming language.
This book is for anyone who would like to use the combination of MicroPython and the BBC Micro:bit to build exciting real-life projects. Individuals working in domains such as embedded systems, electronics, software development, IoT, and robotics will find this book quite useful.
Chapter 1, Introduction to the BBC Micro:bit, covers the technical specifications of the BBC Micro:bit.
Chapter 2, Setting Up the Micro:bit and Using Code Editors, covers the installation of various integrated development environments for programming the Micro:bit with MicroPython.
Chapter 3, Python Programming Essentials, explores the basic concepts and syntax of Python programming.
Chapter 4, Advanced Python, dives deeper into the advanced concepts of Python.
Chapter 5, Built-in LED Matrix Display and Push Buttons, explores the programming of the built-in 5 x 5 matrix of LEDs and push buttons.
Chapter 6, Interfacing External LEDs, explores the interfacing and programming of external LEDs.
Chapter 7, Programming External Push Buttons, Buzzers, and Stepper Motors, teaches the programming of external output devices.
Chapter 8, Exploring the Filesystem, covers the built-in filesystem of the Micro:bit.
Chapter 9, Working with Analog Input and PWM, dives deeper into the interfacing of analog input devices. It also explores the PWM and interfacing of the output devices that employ PWM.
Chapter 10, Working with Acceleration and Direction, details working with internal sensors.
Chapter 11, Working with NeoPixels and a MAX7219 Display, teaches the interfacing of the external display.
Chapter 12, Producing Music and Speech, dives into producing music and speech with the Micro:bit.
Chapter 13, Networking and Radio, teaches you how to connect multiple Micro:bits together.
Chapter 14, Advanced Features of the Micro:bit, explores the advanced hardware features of the Micro:bit.
Chapter 15, Wearable Computing and More Programming Environments, covers simple projects in the area of sewable and wearable computing.
You will need a BBC Micro:bit v2 for running the code examples. You will also need Thonny or Mu Editor installed on your computer—the latest versions, if possible. All code examples have been tested using Thonny and Mu Editor on Windows 10 and Linux. The code examples should work with future versions of the BBC Micro:bit, Thonny, Mu Editor, Windows, and Linux releases too.
Prior experience with some programming language, but not necessarily MicroPython, as well as building basic electronic circuits will be helpful when using this book.
Software/hardware covered in the book
Operating system requirements
BBC Micro:bit V2, Thonny, and Mu Editor
Windows, macOS, or Linux
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You should be comfortable with electronics and computer programming. Prior exposure to Python or MicroPython is desired but not mandatory.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/BBC-Micro-bit-in-Practice. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/AYz3z
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “This is because the str1 and pi variables are not of the same data type.”
A block of code is set as follows:
>>> print("This is a test string) Traceback (most recent call last): File "<stdin>", line 1 SyntaxError: invalid syntaxAny command-line input or output is written as follows:
PS C:\Users\Ashwin> ufs ls mylib.py main.py test.txtBold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select System info from the Administration panel.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
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/support/errata and fill in the form.
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.
Once you’ve read BBC Micro:bit in Practice, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781804610121
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyThis part aims to introduce you to the hardware and software. The first chapter introduces the specifications of the BBC Micro:bit, which is controlled by user-written code. The second chapter helps you set up the environment for the code. The third and the fourth chapters explore the Python programming syntax in detail. These chapters will help you follow and practice the book's concepts.
This part has the following chapters:
Chapter 1, Introduction to the BBC Micro:bitChapter 2, Setting Up the Micro:bit and Using Code EditorsChapter 3, Python Programming EssentialsChapter 4, Advanced PythonI certainly hope that you have read the preface and the table of contents, which provide a fair idea about our journey into the amazing world of the BBC Micro:bit (also written as Micro:bit or Micro Bit). This introductory chapter will warm you up for the upcoming exciting journey into the vast world of the Micro:bit. The road ahead is full of interesting concepts and projects. It is always a good idea to prepare well for the journey ahead, and this chapter will accomplish that.
We will explore the following topics in this chapter:
The history of the Micro:bitThe specifications of Micro:bit V1 and Micro:bit V2Powering up the Micro:bitBreakout boardsFritzing to create circuit diagramsLet’s get started!
We will need the following hardware for this chapter:
BBC Micro:bit V1 or V2A computer with Windows, macOS, or LinuxA BBC Micro:bit edge connectorA Micro-USB to USB cableAn internet connectionA mobile power bankKitronik Mi:powerIt is important to know the history of the BBC Micro:bit. The British Broadcasting Corporation (BBC) is the United Kingdom’s public broadcaster. It is also the world’s oldest and biggest broadcaster. BBC has always been pioneering in creating programs for outreach in science and technology to improve the public understanding of science. Its programs include various documentaries and television series.
One such interesting television series was The Computer Programme. It was broadcast on BBC Two and used a home computer, the BBC Micro, conceptualized by the BBC and developed by Acorn Computers. The TV series was a part of the BBC Computer Literacy Project. The BBC Micro had six different models, which were all based on the famous MOS Technology 6502 8-bit microprocessor. It is a simplified and faster version of the Motorola 6800 microprocessor. The 6502 is a very popular microprocessor, and variants of it were used in popular video game consoles and computers such as Atari 2600, Apple II, Nintendo Entertainment System (popularly known as NES or Famicom), Commodore 64, and, of course, the BBC Micro. The BBC Micro was very successful, and it made a great impact in the computer education sector, leaving a great legacy behind.
In 2012, with the release of Raspberry Pi, a new era was ushered into the world of computing and education. Through the Computer Literacy Project, the BBC sought to build upon the legacy of the BBC Micro after the great success of Raspberry Pi. It onboarded many partners from industry, such as Microsoft, and academia, such as Lancaster University. The first version (now referred to as the Micro:bit V1) was launched in July 2015 and was available for general sale in March 2016. The BBC also gave hundreds of thousands of Micro:bits to school children in the UK as a part of science education outreach. After the Micro:bit successfully launched, the BBC formed a not-for-profit organization known as the Microbit Foundation.
Note
For more details, you can visit the home page of the Microbit Foundation at https://microbit.org/.
In October 2020, the Microbit Foundation released the second version of the Micro:bit. V2 has got better specifications than V1 at the same price. We will explore the specifications of V1 and V2 side by side in the following section.
The following table compares the features of the BBC Micro:bit V1 and V2 side by side (source: https://microbit.org/):
BBC Micro:bit
V1
V2
Processor
Nordic nRF51822
Nordic nRF52833
Flash memory
256 KB
512 KB
RAM
16 KB
128 KB
Speed
16 MHz
64 MHz
Bluetooth
Bluetooth 4.0
Bluetooth 5.1 with Bluetooth Low Energy (BLE)
Radio communication
2.4 GHz radio (80 channels)
2.4 GHz radio (80 channels)
Buttons
Two programmable (A and B) and one system (reset)
Two programmable (A and B) and one system (power/reset)
On/off switch
None
Press and hold the rear power button
Touchpad
None
Touch-sensitive logo
Microphone
None
Onboard Knowles SPU0410LR5H-QB-7 MEMS microphone (with LED indicator)
Display
5x5 programmable LED matrix (25 LEDs in total)
5x5 programmable LED matrix (25 LEDs in total)
Speaker
None
Onboard JIANGSU HUANENG MLT-8530 (up to 80 dB)
Motion sensor and compass
LSM303AGR
LSM303AGR
Temperature sensor
On-board temperature sensor
On-core NRF52
Edge connector
25 pins
25 pins
Table 1.1 – Comparison of the features of BBC Micro:bit V1 and V2
The processors used in both versions are a special type of processor known as a System on Chip (also abbreviated as SoC or SOC). An SoC is an Integrated Circuit (IC) that has all or most components of a complete working computer system. A typical SoC has a processor, flash memory, and RAM. Both versions employ Advanced RISC Machines (ARM) processors. The ARM uses Reduced Instruction Set Computer (RISC) instruction architecture. The V1 uses Nordic nRF51822 SoC (https://www.nordicsemi.com/Products/nRF51822), and the V2 uses Nordic nRF52833 (https://www.nordicsemi.com/products/nrf52833). The Random Access Memory (RAM) is used to execute the programs. The flash memory is used to store the programs, and it is reprogrammable.
The following diagram shows the front faces of V2 and V1 side by side:
Figure 1.1 – Hardware features on the fronts of V2 and V1 (courtesy: ©Micro:bit Educational Foundation/microbit.org)
The following diagram shows the rear of the V2 and V1 side by side:
Figure 1.2 – The hardware features on the rears of V2 and V1 (courtesy: ©Micro:bit Educational Foundation/microbit.org)
Another important aspect of the Micro:bit boards of both versions is that they come with edge connectors to interface with external hardware components. The following diagram explains the slight difference between the edge connectors of V2 and V1 side by side:
Figure 1.3 – The edge connectors of V2 and V1 (courtesy: https://tech.microbit.org/hardware/edgeconnector/)
You can read online about the edge connectors in detail at https://tech.microbit.org/hardware/edgeconnector/and https://microbit.pinout.xyz/.
I understand that you may feel a bit overwhelmed with all this technical information at this stage. Without enough context about the utility of this technical information, it is natural to feel that way. However, in the upcoming chapters, we will learn about and demonstrate all these features in detail.
Now that we have a fair understanding of the history and specifications of the Micro:bit, let’s learn various methods to power it up.
There are a few ways we can power up the Micro:bit. Let’s see them all one by one. The following diagram clearly shows the micro-USB port and the battery socket. We can power up the BBC Micro:bit using these:
Figure 1.4 – The battery socket and micro-USB port (courtesy: https://commons.wikimedia.org/wiki/File:BBC_micro_bit_%2826238853955%29.png)
We can use a micro-USB male to USB male cable to power the Micro:bit. The following is the micro-USB end of such a cable:
Figure 1.5 – A micro-USB male connector (courtesy: https://commons.wikimedia.org/wiki/File:MicroB_USB_Plug.jpg)
Insert this end into the Micro:bit, as shown in the following photo:
Figure 1.6 – A micro-USB male connector (courtesy: https://commons.wikimedia.org/wiki/File:Bbc-microbit-2021.jpg)
Insert the other end into a computer or a power bank. The following is an image of a mobile/portable power bank:
Figure 1.7 – A power bank with a micro USB cable attached (courtesy: https://commons.wikimedia.org/wiki/File:Portable_power_bank.jpg)
We can also use a pair of AAA batteries with a special connector, as shown in the following photo:
Figure 1.8 – A battery connector (courtesy: https://commons.wikimedia.org/wiki/File:Cavo_Microbit.jpg)
You can procure such a connector online at various marketplaces. One such page is https://www.sparkfun.com/products/15101. There are many other websites too that sell these connectors. You can also check your local makers’ electronic supply shops for this.
The following photo shows the Micro:bit powered up with this connector and a pair of AAA batteries:
Figure 1.9 – A battery connector connected to the Micro:bit
We can also power the Micro:bit with a CR2032-type power cell, as shown in thefollowing figure:
Figure 1.10 – CR2032 power cells (courtesy: https://commons.wikimedia.org/wiki/File:Cr2032-7mmgrid.jpg)
We can use various special connectors to connect it with the Micro:bit. One special connector board is MI – the power board by Kitronik (https://kitronik.co.uk/products/5610-mipower-board-for-the-bbc-microbit). Figure 1.11 shows a photo of the board, the nuts, and the CR2032 battery that comes with it:
Figure 1.11 – The MI:power board and contents of the package
Figure 1.12 is a photo of the rear of the Micro:bit attached to the MI:power board:
Figure 1.12 – The Micro:bit assembled with the MI:power board
We can see that there is a dedicated ON/OFF switch. Attaching the board to the Micro:bit is very easy, and we can check the instructions for assembly at https://kitronik.co.uk/products/5610-mipower-board-for-the-bbc-microbit.
Both versions of the Micro:bit come with booklets, as shown in the following image:
Figure 1.13 – Micro:bit instruction booklets
It is recommended to go through them for a better understanding.
When we unbox the Micro:bit and power it up for the very first time, it runs a factory default program known as the out-of-box experience. It is lots of fun to learn about the features of the Micro:bit using this program. Unbox and power your Micro:bit to run this program. Enjoy exploring the features of the Micro:bit.
Now that we have explored various ways to power the Micro:bit, we will explore special hardware components known as breakout boards.
The General Purpose Input Output (GPIO) pins of the Micro:bit are extremely narrowly printed on the edge connector. It is difficult to use them directly, and soldering can ruin the board. So, many organizations have developed special products that make the GPIO pins of the Micro:bit easily accessible. These products are known by various names, such as breakout boards, GPIO expanders, I/O extensions, and edge connectors. The following are the URLs of the web pages for such products:
https://www.sparkfun.com/products/16445https://kitronik.co.uk/collections/microbit-and-accessories/products/5601b-edge-connector-breakout-board-for-bbc-microbit-pre-builthttps://robu.in/product/microbit-gpio-expansion-board/https://www.dfrobot.com/product-1867.htmlhttps://wiki.dfrobot.com/IO_Extender_for_microbit_V2.0_SKU_MBT0008I urge you all to procure one of these or any other edge connector of your choice, as we will need these for the demonstrations in this book.
I, too, own a couple of them, as shown in the following photos:
Figure 1.14 – A couple of edge connectors I own
Here, we have Micro:bit V1 and V2 inserted into the edge connectors:
Figure 1.15 – Micro:bits with the edge connectors
In the following section, we will get acquainted with a software program, Fritzing, that will help us visualize circuits.
I am using software known as Fritzing (https://fritzing.org/) to create the circuits depicted in this book. It is not mandatory software for the demonstrations, as all the circuit diagrams are already printed in the book. However, if you wish to create your own circuit diagrams with Fritzing, you must procure them separately for 8 euros from https://fritzing.org/download/. I have included the Fritzing diagram files (with the .fzz extension) in the code bundle of the book. You can open them using the Fritzing software and modify them. It is very convenient software, and many hardware hackers (including us, the book’s authors) use it to design and visualize their projects.
Fritzing has a library of many routinely used electronic and electrical components that include various boards. Also, users can create their own custom components such as boards and add them to their Fritzing setup. Many of them make such components available to other users for free. These components are stored in files with the .fzpz extension. You can find the component files for the BBC Micro:bit and many edge connectors at the following URLs:
https://tech.microbit.org/docs/hardware/assets/Microbit.fzpz.ziphttps://forum.fritzing.org/t/improved-micro-bit-part/7288Download the part files. Open the Fritzing software. In the Parts panel (the top-right panel), right-click on an empty gray space to show a dropdown, as shown in Figure 1.16:
Figure 1.16 – Importing a part to Fritzing
The first option is Import…. Click on that, and it opens a standard file selection window of the OS. Select the downloaded component files for the Micro:bit and edge connectors (those with the .fzpz extension) and import them. We can import only one component at a time. Once imported, all the components will be visible in the tab labeled MINE (refer to Figure 1.16). The following figure is a screenshot of those components added to a circuit diagram under development:
Figure 1.17 – Using the BBC micro:bit and edge connector parts in circuit diagrams
This is how Fritzing can be used to visualize the circuits we will build for the demonstrations throughout this book. You will find similar and more detailed circuit diagrams in the upcoming chapters of the book.
In this chapter, we learned a few fundamentals about the BBC Micro:bit. We had a brief tour of the hardware features that we will explore in the coming chapters. We also learned about the ways to power the board and edge connectors.