Copyright © 2018 by McGraw-Hill Education All rights reserved Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a data base or retrieval system, without the prior written permission of the publisher ISBN: 978-1-26-011759-2 MHID: 1-26-011759-6 The material in this eBook also appears in the print version of this title: ISBN: 978-1-26-011758-5, MHID: 1-26-011758-8 eBook conversion by codeMantra Version 1.0 All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps McGraw-Hill Education eBooks are available at special quantity discounts to use as premiums and sales promotions or for use in corporate training programs To contact a representative, please visit the Contact Us page at www.mhprofessional.com Information has been obtained by McGraw-Hill Education from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill Education, or others, McGraw-Hill Education does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information TERMS OF USE This is a copyrighted work and McGraw-Hill Education and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill Education’s prior consent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms THE WORK IS PROVIDED “AS IS.” McGRAW-HILL EDUCATION AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill Education and its licensors not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill Education nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill Education has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill Education and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise To my mother Anne Kemp, whose kindness and positive attitude to life are an example for all who know her About the Author Simon Monk (Preston, UK) has a bachelor’s degree in cybernetics and computer science and a Ph.D in software engineering He has been an active electronics hobbyist since his early teens and since 2012 has divided his work life between writing books and designing products for the business he started with his wife (http://monkmakes.com), which manufactures hobby electronics kits and boards You can find out more about Simon’s books at http://simonmonk.org You can also follow him on Twitter, where he is @simonmonk2 CONTENTS Acknowledgments Introduction Plug Me In! History What Can It Do? micro:bit versus Raspberry Pi and Arduino So What Is Programming? Why MicroPython? Summary Getting Started MicroPython Editors Online Editor Installing micro:bit Programs Using Windows Installing micro:bit Programs Using a Mac Installing micro:bit Programs Using Linux Saving and Loading Programs The Mu Editor Installing Mu on Windows Installing Mu on a Mac Installing Mu on Linux Using Mu The REPL Downloading This Book’s Programs Summary MicroPython Basics Numbers Variables Strings Converting Numbers to Strings Programs Looping Forever for Loops ifs and elses More on while Timer Example Summary Functions What Are Functions? Parameters Global Variables Return Values Advanced Parameters Summary Lists and Dictionaries Lists Message Board Example The Lowdown on Lists Accessing Elements of a List Adding to a List Deleting from a List Joining Lists Together Strings as a List of Characters Dictionaries An Example Dictionaries in Detail Accessing Elements of a Dictionary Adding Items to a Dictionary Summary Writing Your Own Programs Writing Software Keep It Simple Spikes and the REPL Versioning Comments Refactoring State Machine Design Revisiting the Timer Example A State Machine Framework Switching Between States Adding Code to the SET State Adding Code for the RUN State Adding Code for the ALARM State Debugging More Python Formatting Exception Handling File System Summary Modules and Classes Built-in Modules Importing Modules Classes and Instances Inheritance Making Simple Modules Making a Module That Uses a Class Module and Class Definition Methods Using the Module Modules from the Community Summary The LED Display Controlling Individual LEDs Scrolling Text Showing Text Showing an Image Animation Racing Game Summary micro:bit Sensors Buttons Revisited Gestures Raw Accelerometer Data Magnetometer Processor Temperature Touch Summary 10 Connecting Electronics Battery Power USB Power Pack V Battery Pack Battery Life micro:bit Operating Voltage GPIO Pins 0, 1, and Alligator Clip Leads Digital Outputs Analog Outputs Digital Inputs Analog Inputs Power Out Sound Output Alligator Clip to Audio Socket Amplifier Modules Updating the Alarm Project Music Speech Neopixels The Edge Connector Pinout Breakout Boards and Kits Disabling Hardware Summary 11 Radio and Communications Basic micro:bit-to-micro:bit Communication Messaging Different Users Advanced Radio Settings Computer-to-micro:bit Communication Remote Control of Your micro:bit Using Python Python on Your Computer Getting Bitio Installing the Resident Program Using Bitio from the Console Summary 12 JavaScript Blocks Editor The Editor Getting Started Events Variables and Loops Magnetometer Example Summary A MicroPython Reference Language Contructs Comparisons Numbers Strings Lists Dictionaries Type Conversions B Hardware micro:bit Edge Connector Pinout Suppliers and Manufacturers Components Hardware Kits Basic Components Modules and Expansion Boards Index B Hardware micro:bit Edge Connector Pinout Figure B-1 shows the pinout for the micro:bit’s edge connector See Chapter 10 for more information on using the edge connector Figure B-1 The micro:bit edge connector pinout Suppliers and Manufacturers The micro:bit is available from many suppliers worldwide, so for a micro:bit itself, your best starting point is probably an Internet search There are also manufacturers and retailers that supply micro:bits and also various add-ons and kits for the boards Some of the most popular companies are listed in Table B-1 Table B-1 Manufacturers and Suppliers of micro:bit-Related Products Components This section contains lists of the various parts and modules used in this book along with some ideas on where to get them Hardware It’s a little unfair of me to single out certain products, especially because new products for the micro:bit are being released all the time What I list in Table B-2 are items that I see as particularly useful I suggest a thorough Internet search to see the full range of options before you buy anything Table B-2 Hardware for the micro:bit Kits Buying a starter kit is a good way to get started with the basic hardware that you need with electronics on a micro:bit Table B-3 lists some of the kits I am aware of, although I am sure that other kits also will be available by now Table B-3 micro:bit Electronics Kits Basic Components Getting hold of basic components such as LEDs and resistors can be surprisingly difficult if you visit a large component supplier such as Farnell, Mouser, or Digi-Key Minimum order values and the sheer range of choices can be confusing If you are new to buying electronic components, then it is easier to either buy a kit that includes a basic set of components or use a component supplier such as Adafruit or SparkFun that specialize in the hobby market eBay is also a great source of low-cost components Table B-4 lists the few basic components used in this book Table B-4 Basic Electronic Components Modules and Expansion Boards The micro:bit has a lively “ecosystem” with many interesting add-on boards available Table B-5 lists those used in this book, as well as other interesting boards Table B-5 Modules and Expansion Boards for the micro:bit Index Please note that index links point to page beginnings from the print edition Locations are approximate in e-readers, and you may need to page down one or more times after clicking a link to get to the indexed material Page numbers in italics refer to figures abs function, 99 absolute value, 99 accelerometer module, getting raw data, 96–99 Adventures in Minecraft (Whale), 136 alarm project, 121–123 alligator clips, 109–110, 120–121 amplifier modules, 121, 122 analog inputs, 109, 115–119 analog outputs, 109, 113–115 animation, 89–90 racing game, 91–92 See also images Arduino Uno, vs micro:bit, 5–6 ARMmbed, 19 attributes, 76 audio, 120 alarm project, 121–123 alligator clip to audio socket, 120–121 amplifier modules, 121, 122 music, 123–124 speech, 124 batteries, 45–46 battery life, 107–108 battery tester, 115–117 V battery pack, 107 BBC See British Broadcasting Corporation (BBC) bitio, 136 installing, 137, 138 using from the console, 137–139 Bitio Project, 136 blocking, 87 Bluetooth, 131 breakout boards and kits, 128–129 British Broadcasting Corporation (BBC), 3–4 built-in modules, 73–75 classes, 75–76 defining, 81 inheritance, 76–78 making a module that uses a class, 80–83 coding, self-documenting code, 57 See also programming comments, 57 comparison operators, 150 compass, calibrating, 99–100 See also magnetometer module compiling, components, suppliers and manufacturers, 158–160 concatenation, 29 See also strings conditions, 34–35 connecting to a computer, 1–3 constants, 27 crocodile clips, 109–110 debugging, 66–67 Dictionaries, 45, 51 accessing elements of a Dictionary, 53–54 adding items to a Dictionary, 54 functions, 154 gesture-detector project, 51–53 digital inputs, 109, 115, 116 digital outputs, 108, 110–113 downloading example programs, 23–24 DRY, 58–59 edge connector breakout boards and kits, 128–129 disabling hardware, 129 overview, 126–127 pinout, 127–128, 157 See also touch pins else, 34–35 embedded software, 55 escape characters, 151 exception handling, 68–69 expansion boards, suppliers and manufacturers, 160 file system, 69–71 finite state machines (FSMs), 59 See also state machine design flashing, 8, 32 floats, 25 for loops, 33–34 freefall, 96 functions, 29 body, 41 calling, 40, 41 definition, 40, 41 Dictionary, 154 List, 153 number, 151 overview, 39 parameters, 40–42, 44 returning a value, 43–44 string, 152 George, Damien, gesture-detector project, 51–53 gestures, 96 get_presses( ), 95 Github repository, 23–24 global variables, 42–43, 47, 101 Google Chrome, installing micro:bit programs, 13–14 GPIO pins, 108–119 hardware disabling, 129 micro:bit edge connector pinout, 157 suppliers and manufacturers, 158–159 Hello message, in JavaScript Blocks, 142–143 hex (hexadecimal), I2C, 128 if, 34–35 images animation, 89–90 racing game, 91–92 showing, 88–89 inheritance, 76–78 inputs, instance variables, 82 instances, 75–76 integers, 25 integrated circuits (ICs), 112 inverse square law, 101–102 is_pressed( ), 95 JavaScript Blocks, 8, 141 displaying “Hello World!” message, 142–143 editor, 141–142 events, 144 magnetometer program, 147 variables and loops, 144–146 kits, suppliers and manufacturers, 159 LED display, animation, 89–90 controlling individual LEDs, 85–86 neopixels, 124–126 racing game, 91–92 scrolling text, 87 showing an image, 88–89 showing text, 88 LEDs, suppliers and manufacturers, 159–160 libraries, 83 Linux installing micro:bit programs, 14–16 installing Mu, 19 Lists, 45 accessing elements of a List, 48–49 adding to a List, 49 deleting from a List, 49–50 functions, 153 joining Lists together, 50 message board example, 45–48 strings as a list of characters, 50–51 local variables, 41 loops, 31–32 Mac installing micro:bit programs, 11–13 installing Mu, 19 magnetometer module, 99–102 JavaScript Blocks program, 147 See also compass manufacturers basic components, 159–160 hardware, 158–159 kits, 159 modules and expansion boards, 160 message board example, 45–48 methods, 32, 76, 81–83 micro:bit, connecting to a computer, 1–3 features, 4–5 front and back views, history of, 3–4 vs Raspberry Pi and Arduino Uno, 5–6 Microbit Educational Foundation, 4, MicroPython, comments, 57 comparison operators, 150 converting numbers to strings, 29 Dictionary functions, 154 else, 34–35 escape characters, 151 file system, 69–71 for loops, 33–34 if, 34–35 images, 88–89 language constructs, 149–150 List functions, 153 loops, 31–34 Mu, number functions, 151 numbers, 25–26 online editor, 9, 10–17 overview, programs, 30–31 string functions, 151–152 strings, 28–29 type conversions, 155 variables, 27–28 while loops, 31–32, 35–36 See also Python MicroPython online editor, installing micro:bit programs using a Mac, 13–14 installing micro:bit programs using Linux, 14–16 installing micro:bit programs using Windows, 11–13 overview, 10 saving and loading programs, 17 Microsoft Edge, installing micro:bit programs, 11–13 Minecraft, remote controlling with the micro:bit, 136 modules built-in, 73–74 importing, 74–75 libraries, 83 making a module that uses a class, 80–83 making simple modules, 78–80 suppliers and manufacturers, 160 MonkMakes Basic Components Kit, 160 MonkMakes relay board, 112, 113, 115 MonkMakes sensor board, 118 MonkMakes Speaker, 121, 122 motor driver boards, suppliers and manufacturers, 160 Mu editor, changing code, 31 downloading example programs to use in, 24 installing on a Mac, 19 installing on Linux, 19 installing on Windows, 18–19 overview, 17 using Mu, 19–21 music, 123–124 “neo” neodymium magnet, 100 See also magnetometer module neopixels, 124–126 number functions, 151 numbers converting to strings, 29 working with, 25–26 operating voltage, 108 outputs, parameters, 33, 40–42 optional parameters with default values, 44 See also functions photoresistors, suppliers and manufacturers, 159–160 pins, 109 See also GPIO pins pluralize function, 78–80 powering a micro:bit battery life, 107–108 battery pack, 45–46 operating voltage, 108 V battery pack, 107 USB power lead, 45–46 USB power pack, 105–106 powering out, 119 private methods, 82 programming, 7–8 programs, 30–31 writing your own, 55–59 Proto-PIC amp:bit, 121, 122 public methods, 82 pulse width modulation (PWM), 114–115 push buttons A and B, 4, 95 Python comments, 57 Dictionaries, 45 exception handling, 68–69 file system, 69–71 floats, 25 formatting, 67 integers, 25 Lists, 45–48 running on your computer, 137 See also bitio; MicroPython racing game, 91–92 radio communications, 131 adjusting length of message, 135 basic micro:bit-to-micro:bit communication, 131–132 computer-to-micro:bit communication, 135 increasing the range, 134 sending messages to specific micro:bits, 132–134 radio module, range errors, 47 Raspberry Pi installing micro:bit programs, 14–16 installing Mu, 19 vs micro:bit, 5–6 Read Eval Print Loop See REPL refactoring, 57–59 relay boards, suppliers and manufacturers, 160 remote controlling the micro:bit, 136–139 REPL, 17, 21–23 accessing elements of a Dictionary, 53–54 accessing elements of a List, 48–49 computer-to-micro:bit communication, 135 controlling individual LEDs, 85–86 debugging, 66–67 for loops, 33 getting raw accelerometer data, 96–99 running programs, 30–31 scrolling text, 87 showing text, 88 spike solutions, 56 working with numbers, 25–26 working with strings, 28–29 working with variables, 27–28 Reset button, resistors, suppliers and manufacturers, 159–160 return values, 43–44 scroll method, 39 scrolling text, 87 self-documenting code, 57 sensors accelerometer, 4, 96–99 light-sensing circuits, 119 magnetometer, 99–102, 147 MonkMakes sensor board, 118 suppliers and manufacturers, 160 temperature, 102 touch, 102–104 serial programming interface (SPI), 127 shake, 96 shock, 96 showing an image, 88–89 showing text, 88 sleeping, 32 solderless breadboards, 128–129 solid-state relays, 112 sound output, 120 alarm project, 121–123 alligator clip to audio socket, 120–121 amplifier modules, 121, 122 music, 123–124 speech, 124 speakers, suppliers and manufacturers, 160 speech, 124 spike solutions, 56 state machine design, 59–61 adding code for the ALARM state, 65 adding code to the RUN state, 63–65 adding code to the SET state, 63 state machine framework for timer project, 61–62 switching between states, 62 string functions, 151–152 strings, 28–29 converting numbers to, 29 format strings, 67 as a list of characters, 50–51 substrings, 51 suppliers basic components, 159–160 hardware, 158–159 kits, 159 modules and expansion boards, 160 temperature sensor, 102 text scrolling, 87 showing, 88 timer project, 36–37 adding alarm, 121–123 state machine design, 59–65 touch pins, 4, 102–104 See also edge connector type conversions, 155 underscore, 39 uploading, 8, 32 USB power lead, 45–46 USB power pack, 105–106 USB to micro-USB connector, 1–3 variables, 27–28, 47 global variables, 42–43, 101 in JavaScript Blocks, 144–146 local variables, 41 versioning, 56 was_pressed( ), 95 Whale, David, 136 while loops, 31–32, 35–36 Windows installing micro:bit programs, 11–13 installing Mu, 18–19 wireless communications See radio communications writing software, 55–59 ... the Reset button (see Figure 1-1B) just to the right of the the USB connector History The micro:bit is more correctly called the BBC micro:bit The BBC (British Broadcasting Corporation) is the. .. the UK public school system Since then, the running of the micro:bit project has passed from the BBC to the Microbit Educational Foundation This not-for-profit organization is now spreading the. .. code onto the device MicroPython Editors When it comes to programming the micro:bit using MicroPython, there are two main options for the editor with which to type your programs The first is browser