Book Image

BBC Micro:bit in Practice

By : Ashwin Pajankar, Abhishek Sharma, Sandeep Saini
Book Image

BBC Micro:bit in Practice

By: Ashwin Pajankar, Abhishek Sharma, Sandeep Saini

Overview of this book

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.
Table of Contents (22 chapters)
1
Part 1: Getting Started with the BBC Micro:bit
6
Part 2: Programming Hardware with MicroPython
10
Part 3: Filesystems and Programming Analog I/O
13
Part 4: Advanced Hardware Interfacing and Applications

Appending a file

The standard Python implementation (CPython) has the provision for appending a file. If we open a file again in write mode and add some information, earlier information is erased, and new information is overwritten. However, MicroPython does not have this functionality. We can, however, append a file with a clever trick. We first open the file to be appended in read mode and save the contents to the variable. Then, we add another string to that variable and write the variable to the file to be appended. This will append the file. The following program demonstrates that:

with open('HenryV.txt') as file_handle:
    file_data = file_handle.read()
file_data = file_data + '\nHenry V, William Shakespeare'
with open('HenryV.txt', 'w') as file_handle:
    file_handle.write(file_data)
with open('HenryV.txt') as file_handle:
    print(file_handle.read())