You are on page 1of 54

Programming Microcontrollers with

Python: Experience the Power of


Embedded Python 1st Edition
Armstrong Subero
Visit to download the full and correct content document:
https://textbookfull.com/product/programming-microcontrollers-with-python-experienc
e-the-power-of-embedded-python-1st-edition-armstrong-subero-2/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Programming Microcontrollers with Python: Experience


the Power of Embedded Python 1st Edition Armstrong
Subero

https://textbookfull.com/product/programming-microcontrollers-
with-python-experience-the-power-of-embedded-python-1st-edition-
armstrong-subero-2/

Programming PIC Microcontrollers with XC8 1st Edition


Armstrong Subero

https://textbookfull.com/product/programming-pic-
microcontrollers-with-xc8-1st-edition-armstrong-subero/

Programming with MicroPython Embedded Programming with


Microcontrollers and Python 1st Edition Nicholas H.
Tollervey

https://textbookfull.com/product/programming-with-micropython-
embedded-programming-with-microcontrollers-and-python-1st-
edition-nicholas-h-tollervey/

Programming with MicroPython embedded programming with


Microcontrollers and Python First Edition Nicholas H.
Tollervey

https://textbookfull.com/product/programming-with-micropython-
embedded-programming-with-microcontrollers-and-python-first-
edition-nicholas-h-tollervey/
MicroPython for the Internet of Things: A Beginner’s
Guide to Programming with Python on Microcontrollers
2nd Edition Bell

https://textbookfull.com/product/micropython-for-the-internet-of-
things-a-beginners-guide-to-programming-with-python-on-
microcontrollers-2nd-edition-bell/

Learning Scientific Programming with Python 1st Edition


Christian Hill

https://textbookfull.com/product/learning-scientific-programming-
with-python-1st-edition-christian-hill/

Introduction to Scientific Programming with Python


Joakim Sundnes

https://textbookfull.com/product/introduction-to-scientific-
programming-with-python-joakim-sundnes/

Programming with Python for Social Scientists 1st


Edition Phillip Brooker

https://textbookfull.com/product/programming-with-python-for-
social-scientists-1st-edition-phillip-brooker/

Learning Scientific Programming With Python 2nd Edition


Christian Hill

https://textbookfull.com/product/learning-scientific-programming-
with-python-2nd-edition-christian-hill/
Programming
Microcontrollers
with Python
Experience the Power of
Embedded Python

Armstrong Subero
Programming
Microcontrollers with
Python
Experience the Power
of Embedded Python

Armstrong Subero
Programming Microcontrollers with Python: Experience the Power of
Embedded Python
Armstrong Subero
Basse Terre, Moruga, Trinidad and Tobago

ISBN-13 (pbk): 978-1-4842-7057-8 ISBN-13 (electronic): 978-1-4842-7058-5


https://doi.org/10.1007/978-1-4842-7058-5

Copyright © 2021 by Armstrong Subero


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole
or part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical
way, and transmission or information storage and retrieval, electronic adaptation, computer
software, or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a
trademark symbol with every occurrence of a trademarked name, logo, or image we use the
names, logos, and images only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms,
even if they are not identified as such, is not to be taken as an expression of opinion as to
whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the
date of publication, neither the authors nor the editors nor the publisher can accept any
legal responsibility for any errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Susan McDermott
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1
NY Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance
Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for
reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our
Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub via the book’s product page, located at www.apress.com/
978-­1-­4842-­7057-­8. For more detailed information, please visit http://www.apress.com/
source-­code.
Printed on acid-free paper
To all those who tinker to keep the world running
Table of Contents
About the Author��������������������������������������������������������������������������������xv
About the Technical Reviewer����������������������������������������������������������xvii
Acknowledgments�����������������������������������������������������������������������������xix

Chapter 1: Getting Ready����������������������������������������������������������������������1


Introduction to Microcontrollers����������������������������������������������������������������������������1
Firmware, Memory, and Clock Speed��������������������������������������������������������������������3
8-Bit vs. 32-Bit������������������������������������������������������������������������������������������������������4
Microcontroller Programming Languages�������������������������������������������������������5
Assembly Language����������������������������������������������������������������������������������������������5
C����������������������������������������������������������������������������������������������������������������������������6
C++�����������������������������������������������������������������������������������������������������������������������6
BASIC��������������������������������������������������������������������������������������������������������������������7
Rust�����������������������������������������������������������������������������������������������������������������������7
Python�������������������������������������������������������������������������������������������������������������������8
Selecting a Development Board����������������������������������������������������������������������������9
Adafruit Metro M0 Express���������������������������������������������������������������������������������10
Adafruit Feather M0 Express������������������������������������������������������������������������������12
Adafruit Metro M4 Express���������������������������������������������������������������������������������13
Adafruit Grand Central M4 Express���������������������������������������������������������������������14
The Arduino Zero�������������������������������������������������������������������������������������������������15

v
Table of Contents

The STM32F746ZG Nucleo����������������������������������������������������������������������������������16


Device Comparison���������������������������������������������������������������������������������������������17
The Component List��������������������������������������������������������������������������������������������18
The Mu Editor������������������������������������������������������������������������������������������������������21
Other Serial Communication Tools����������������������������������������������������������������25
Setting Up Your Own Board���������������������������������������������������������������������������������29
Conclusion����������������������������������������������������������������������������������������������������������35

Chapter 2: Electronics Primer������������������������������������������������������������37


Electrical Wires���������������������������������������������������������������������������������������������������40
The Breadboard��������������������������������������������������������������������������������������������������42
Electronic Schematics�����������������������������������������������������������������������������������44
Passive Components�������������������������������������������������������������������������������������������48
Resistors�������������������������������������������������������������������������������������������������������������48
Capacitors�����������������������������������������������������������������������������������������������������������51
Polarized Capacitors�������������������������������������������������������������������������������������������52
Non-polarized Capacitors�����������������������������������������������������������������������������������53
Capacitor Schematic Symbols�����������������������������������������������������������������������54
Inductors�������������������������������������������������������������������������������������������������������������55
Semiconductors��������������������������������������������������������������������������������������������������57
Diode�������������������������������������������������������������������������������������������������������������59
Light-Emitting Diode�������������������������������������������������������������������������������������������60
Transistor������������������������������������������������������������������������������������������������������������61
Metal-Oxide-Semiconductor Field-Effect Transistors�����������������������������������������64
Integrated Circuits�����������������������������������������������������������������������������������������66
Digital Logic���������������������������������������������������������������������������������������������������67
Logic Level Conversion���������������������������������������������������������������������������������������70

vi
Table of Contents

Flip-Flop��������������������������������������������������������������������������������������������������������������72
Registers and the Shift Register�������������������������������������������������������������������������73
Multiplexers and Demultiplexers������������������������������������������������������������������������75
Conclusion����������������������������������������������������������������������������������������������������������76

Chapter 3: Embedded Systems Overview�������������������������������������������77


An Overview of Embedded Systems�������������������������������������������������������������������77
Microcontroller vs. Application Processor����������������������������������������������������������78
Embedded Systems Structure����������������������������������������������������������������������������79
The Hardware System�����������������������������������������������������������������������������������������82
The Software System������������������������������������������������������������������������������������������83
The Toolchain������������������������������������������������������������������������������������������������������84
Software Testing�������������������������������������������������������������������������������������������������85
Embedded Software Architecture�����������������������������������������������������������������������86
The Driver Layer��������������������������������������������������������������������������������������������������87
Hardware Abstraction Layer (HAL)����������������������������������������������������������������������88
Board Support Package (BSP)�����������������������������������������������������������������������������88
Middleware���������������������������������������������������������������������������������������������������������89
Software Framework������������������������������������������������������������������������������������������90
Code Generator���������������������������������������������������������������������������������������������������92
Platform��������������������������������������������������������������������������������������������������������������92
Embedded Systems Constraints�������������������������������������������������������������������������93
Cost���������������������������������������������������������������������������������������������������������������������93
Performance�������������������������������������������������������������������������������������������������������94
Energy Budget�����������������������������������������������������������������������������������������������������95
Embedded Systems Classification����������������������������������������������������������������������96
Small-Scale Systems������������������������������������������������������������������������������������������96

vii
Table of Contents

Medium-Scale Systems��������������������������������������������������������������������������������������97
High-Performance Systems��������������������������������������������������������������������������������98
Distributed Embedded Systems��������������������������������������������������������������������������99
Seven Steps to Developing an Embedded Product�������������������������������������������100
Step 1: Idea Creation�����������������������������������������������������������������������������������100
Step 2: Requirements Specifications�����������������������������������������������������������100
Step 3: Functional Design����������������������������������������������������������������������������101
Step 4: Rapid Prototyping����������������������������������������������������������������������������101
Step 5: Testing���������������������������������������������������������������������������������������������102
Step 6: Securing Your System���������������������������������������������������������������������103
Step 7: Bringing to Market���������������������������������������������������������������������������104
Conclusion��������������������������������������������������������������������������������������������������������105

Chapter 4: Python Programming������������������������������������������������������107


Writing Python Programs����������������������������������������������������������������������������������107
Whitespace�������������������������������������������������������������������������������������������������������110
Comments���������������������������������������������������������������������������������������������������������110
Variables and Constants�����������������������������������������������������������������������������������111
Data Types���������������������������������������������������������������������������������������������������������114
Operators����������������������������������������������������������������������������������������������������������115
Lists������������������������������������������������������������������������������������������������������������������116
Tuples����������������������������������������������������������������������������������������������������������������116
If Statement������������������������������������������������������������������������������������������������������117
else Statement��������������������������������������������������������������������������������������������������117
elif Statement���������������������������������������������������������������������������������������������������118
short if���������������������������������������������������������������������������������������������������������������118
for Loop�������������������������������������������������������������������������������������������������������������119
while Loop���������������������������������������������������������������������������������������������������������119

viii
Table of Contents

Functions����������������������������������������������������������������������������������������������������������120
Lambda Functions���������������������������������������������������������������������������������������������120
Exception Handling�������������������������������������������������������������������������������������������121
Object-Oriented Programming��������������������������������������������������������������������������121
Random and Time���������������������������������������������������������������������������������������������123
Python vs. CircuitPython�����������������������������������������������������������������������������������124
How Does My Python Program Run?����������������������������������������������������������������124
Conclusion��������������������������������������������������������������������������������������������������������125

Chapter 5: Digital Control�����������������������������������������������������������������127


I/O Pins��������������������������������������������������������������������������������������������������������������127
Output and Input on Microcontroller Hardware������������������������������������������������128
Going Deeper into Microcontroller I/O���������������������������������������������������������������132
Using Output: Lighting an LED��������������������������������������������������������������������������135
LED Control��������������������������������������������������������������������������������������������������136
Building the Circuit��������������������������������������������������������������������������������������136
Lighting an LED with CircuitPython�������������������������������������������������������������139
Blinking an LED�������������������������������������������������������������������������������������������������141
Using Input: Adding a Pushbutton���������������������������������������������������������������������143
Pull-Up vs. Pull-Down Resistors������������������������������������������������������������������143
Switch Debouncing��������������������������������������������������������������������������������������146
Input with MCU Schematic (Pull-Up)�����������������������������������������������������������147
Pushbutton Pull-Up Circuit Connection Tips������������������������������������������������������148
Pushbutton Pull-Up with CircuitPython Program�����������������������������������������150
Input with MCU Schematic (Pull-Down)������������������������������������������������������152
Pushbutton Pull-Down Circuit Connection Tips�������������������������������������������153
Pushbutton Pull-Down with CircuitPython Program������������������������������������155
Conclusion��������������������������������������������������������������������������������������������������������157

ix
Table of Contents

Chapter 6: Data Conversion��������������������������������������������������������������159


Analog to Digital Conversion�����������������������������������������������������������������������������159
ADC Hardware���������������������������������������������������������������������������������������������������161
Going Deeper into ADC��������������������������������������������������������������������������������������163
The Potentiometer���������������������������������������������������������������������������������������������164
Analog to Digital Conversion in CircuitPython���������������������������������������������������169
ADC with MCU Schematic���������������������������������������������������������������������������������169
ADC Circuit Connection Tips������������������������������������������������������������������������������170
CircuitPython with Potentiometer Program�������������������������������������������������������171
Photoresistor�����������������������������������������������������������������������������������������������������173
Photoresistor with MCU Schematic������������������������������������������������������������������174
Photoresistor Circuit Connection Tips���������������������������������������������������������������175
Photoresistor with CircuitPython Program��������������������������������������������������������176
Temperature Sensor������������������������������������������������������������������������������������������178
Temperature Sensor with MCU Schematic�������������������������������������������������������180
Temperature Sensor Circuit Connection Tips����������������������������������������������������181
Temperature Sensor with CircuitPython Program���������������������������������������������182
Conclusion��������������������������������������������������������������������������������������������������������184

Chapter 7: Communication Protocols�����������������������������������������������185


Microcontroller Communications����������������������������������������������������������������������185
USART Communications�����������������������������������������������������������������������������������186
Deeper into UART����������������������������������������������������������������������������������������������189
UART in CircuitPython���������������������������������������������������������������������������������������190
USB-UART with MCU Schematic�����������������������������������������������������������������������190
MCU with USB-UART Circuit Connection Tips���������������������������������������������������191
UART with CircuitPython Program���������������������������������������������������������������������193

x
Table of Contents

SPI Communications�����������������������������������������������������������������������������������������194
Deeper into SPI�������������������������������������������������������������������������������������������������196
SPI Circuit Connection���������������������������������������������������������������������������������������197
SPI with CircuitPython Program������������������������������������������������������������������������197
I2C Communications�����������������������������������������������������������������������������������������199
Deeper into I2C�������������������������������������������������������������������������������������������������200
I2C Support in CircuitPython�����������������������������������������������������������������������������201
The MPU6050����������������������������������������������������������������������������������������������������201
I2C with MCU Schematic�����������������������������������������������������������������������������������202
I2C Circuit Connection Tips�������������������������������������������������������������������������������203
I2C with CircuitPython Program������������������������������������������������������������������������204
Adding Libraries������������������������������������������������������������������������������������������������206
MPU6050 with CircuitPython Program��������������������������������������������������������������206
Conclusion��������������������������������������������������������������������������������������������������������208

Chapter 8: Display Interfacing����������������������������������������������������������209


The Liquid Crystal Display���������������������������������������������������������������������������������209
Using a GLCD����������������������������������������������������������������������������������������������������211
Monochrome GLCD Schematic��������������������������������������������������������������������������213
PCD8544 with CircuitPython�����������������������������������������������������������������������������215
Troubleshooting������������������������������������������������������������������������������������������������218
The Framebuffer�����������������������������������������������������������������������������������������������220
OLED�����������������������������������������������������������������������������������������������������������������222
Using an OLED���������������������������������������������������������������������������������������������������224
MCU with OLED Schematic�������������������������������������������������������������������������������225
CircuitPython with OLED Program���������������������������������������������������������������������227
Conclusion��������������������������������������������������������������������������������������������������������230

xi
Table of Contents

Chapter 9: Controlling DC Actuators�������������������������������������������������231


DC Motors���������������������������������������������������������������������������������������������������������231
Driving DC Motors���������������������������������������������������������������������������������������������232
Pulse Width Modulation������������������������������������������������������������������������������������235
PWM in CircuitPython����������������������������������������������������������������������������������������237
PWM with CircuitPython Program���������������������������������������������������������������������237
Controlling Motor Speed�����������������������������������������������������������������������������������238
The H-Bridge�����������������������������������������������������������������������������������������������������239
H-Bridge with MCU Schematic�������������������������������������������������������������������������242
H-Bridge with CircuitPython Program���������������������������������������������������������������245
Servo Motors�����������������������������������������������������������������������������������������������������247
Servo Motors in CircuitPython��������������������������������������������������������������������������249
Servo Motor with MCU Schematic��������������������������������������������������������������������249
Servo Motor with CircuitPython Program����������������������������������������������������������251
Stepper Motors�������������������������������������������������������������������������������������������������252
Stepper Motors in CircuitPython�����������������������������������������������������������������������256
Stepper Motor with MCU Schematic�����������������������������������������������������������������256
Stepper Motor with CircuitPython Program������������������������������������������������������258
Conclusion��������������������������������������������������������������������������������������������������������261

Chapter 10: Python MCU Interfacing������������������������������������������������263


RGB LED������������������������������������������������������������������������������������������������������������263
RGB LED with MCU Schematic��������������������������������������������������������������������������264
RGB LED Circuit Connection Tips����������������������������������������������������������������������265
Libraries We’ll Need������������������������������������������������������������������������������������������266
RGB LED with CircuitPython Program���������������������������������������������������������������266
HC-SR04������������������������������������������������������������������������������������������������������������268

xii
Table of Contents

HC-SR04 with MCU Schematic�������������������������������������������������������������������������270


HC-SR04 Circuit Connection Tips����������������������������������������������������������������������270
Libraries We’ll Need������������������������������������������������������������������������������������������271
HC-SR04 with CircuitPython Program���������������������������������������������������������������272
Piezo Speaker���������������������������������������������������������������������������������������������������274
Piezo with MCU Schematic�������������������������������������������������������������������������������274
Piezo Circuit Connection Tips����������������������������������������������������������������������������275
Libraries We’ll Need������������������������������������������������������������������������������������������276
Piezo with CircuitPython Program��������������������������������������������������������������������276
DHT11���������������������������������������������������������������������������������������������������������������277
DHT11 with MCU Schematic�����������������������������������������������������������������������������278
DHT11 Sensor Circuit Connection Tips��������������������������������������������������������������279
Libraries We’ll Need������������������������������������������������������������������������������������������280
DHT11 Sensor with CircuitPython Program������������������������������������������������������280
Conclusion��������������������������������������������������������������������������������������������������������283

Index�������������������������������������������������������������������������������������������������285

xiii
About the Author
Armstrong Subero started learning electronics at the age of 8. One of
the happiest memories in his childhood was when he finally figured out
how to make a light bulb. It took off from there as he taught himself more
advanced topics in electronics, before delving into computer architecture,
and eventually discovering the joys of microcontrollers and FPGAs.
He currently works for the Ministry of National Security in his country;
writes software; designs circuits, courses, and robots; writes books; and
blogs about technology on www.trinirobotics.com in his free time.
He is also a contributing author to Free Code Camp and has degrees in
Computer Science and Liberal Arts and Sciences from Thomas Edison
State University. He is the author of Programming PIC Microcontrollers
with XC8 and Codeless Data Structures and Algorithms both published by
Apress Media LLC.

xv
About the Technical Reviewer
Sai Yamanoor is an embedded systems engineer working for an industrial
gases company in Buffalo, NY. His interests, deeply rooted in DIY and
open source hardware, include developing gadgets that aid behavior
modification. He has published two books with his brother, and in his
spare time, he likes to contribute to build things that improve quality of
life. You can find his project portfolio at http://saiyamanoor.com.

xvii
Acknowledgments
I want to thank my family.
I want to thank everyone who ever said anything positive to me or
taught me something. I heard it all, and it meant something.
I want to thank God most of all, because without God I wouldn’t be
able to do any of this.

xix
CHAPTER 1

Getting Ready
You have decided to learn about microcontrollers using Python. While it
would be nice to jump straight into developing cool stuff, there are a few
steps you must take to get ready first. If you have experience with software
development, you may be accustomed to just opening an editor and typing
code right away. However, microcontroller development is a little more
involved than that. After all, you will be writing programs for a separate
computer, so there is a lot more to set up. A microcontroller development
environment consists of not only software but an entire hardware
ecosystem that must be understood to unlock all the magic these devices
have to offer.
In this chapter, we will look at setting up an environment for
development. By the end of the chapter, you will be ready to select a
microcontroller board, and you’ll have the software tools and hardware
devices needed to begin your development with CircuitPython. Let’s get
started!

I ntroduction to Microcontrollers
In our modern world, computers are ubiquitous. They have become
smaller, easier to use, and more integrated into our daily lives. A few years
ago, to connect to the Internet and check your email, you would have
had to sit down at a large desktop device. Today, you can do the same
thing with a computer that fits in the palm of your hand and places all the
information in the world at your fingertips.
© Armstrong Subero 2021 1
A. Subero, Programming Microcontrollers with Python,
https://doi.org/10.1007/978-1-4842-7058-5_1
Chapter 1 Getting Ready

The advancements in technology that brought us smartphones and


tablets have given billions of people access to computers. However, these
handheld devices aren’t the only computers that exist. What if I told you
that the billions of smartphones in use pale when compared to another
kind of computing device that silently surrounds us? In fact, there are
probably a half dozen or more of these devices in the room with you right
now. These miniature computers are called microcontrollers, or MCUs, and
they can be found all around us.
Microcontrollers are small, intelligent, programmable computers that
we use to perform tasks that are repetitive or that require some level of
intelligent control without the need for human interaction. Microcontroller
devices have a fraction of the computing power of a device like your
smartphone or tablet, but they have many, many uses. Any device around
you that reacts to a button press, displays information, or makes sounds
when something is wrong is most likely controlled by a microcontroller.
From calculators to TVs to microwaves and dishwashers, almost every
household device you can think of contains a microcontroller.
If you are familiar with computers, you are sure to have heard of a
central processing unit (CPU) or a microprocessor: the brain behind your
computer. A microprocessor lets a computer perform many functions. One
day you might use your computer to type a document, the next to stream
your favorite movie, and so on. The microprocessor has a lot of supporting
circuitry, including memory and input and output chips, that allows it to
carry out all these tasks. These are usually part of the motherboard that
houses the microprocessor.
A microcontroller takes all the supporting chips that are required to
make a microprocessor work and places them on a single chip. This is
why a microcontroller is called a single-chip computer. A microcontroller
still operates like the microprocessor, but it is designed to only do
a single task and to do it as efficiently as possible. For this reason, a
microcontroller chip contains the minimum amount of processing power
required to do its task.

2
Chapter 1 Getting Ready

Firmware, Memory, and Clock Speed


Like general-purpose computers, microcontrollers work by running
programs. Because microcontrollers perform limited functions, the
programs written for them are not expected to change frequently. For that
reason, programs written for microcontrollers are called firmware. This
firmware is usually stored as a binary file (with a .bin file extension) or a
hex file which is a text-represented binary file (having a .hex file extension);
this file contains the memory content that is written on flash, and thus
it is ready to be run on the microcontroller. A special device called a
programmer loads this binary file into the microcontroller’s memory.
The memory consists of two parts: the main memory (sometimes
called program memory) and the random-access memory (RAM,
sometimes called data memory). The main memory is nonvolatile,
whereas RAM is volatile. This means that when the microcontroller is not
powered, the information contained in RAM will disappear, whereas the
information in the main memory will be retained. For this reason, the
main memory is also called read-only memory (ROM). Its contents are
designed to be mainly read, whereas RAM is designed to have its contents
changed by the user during runtime.
In a general-purpose computer system, usually a program is loaded
into RAM before it is executed. Microcontroller systems are a bit different.
In a microcontroller, the firmware is executed directly from ROM, and
RAM is used to do things such as to store temporary information that
aids in running the firmware (these are usually runtime variables and can
contain a stack or a heap, special memory structures).
Some microcontroller devices can have their ROM contents
programmed into them from the factory and cannot be changed by
the end user once they are put into a device. These are called one-­
time programmable (OTP) devices, and they are cheaper and easier to
manufacture. Usually though, the ROM is made of flash memory, meaning
that it can be programmed and changed after manufacturing.

3
Chapter 1 Getting Ready

Flash memory lets you program a device thousands of times, making


it useful for learning and product prototyping. If errors show up in
your firmware program, flash also allows you to fix errors by means of
an update, a process called patching. Updates usually take the form of
over-the-air (OTA) updates, which change the contents of the ROM via a
wireless connection. OTA updates are common for Internet of Things (IoT)
devices. Alternately, you can connect the device to a computer with a cable
to update the firmware.
A microcontroller executes the instructions in its firmware program
according to the speed of a clock that runs the device. The speed is
measured in hertz, or cycles per second. The faster the clock speed, the
faster the device will execute instructions. Microcontroller clock speeds
typically range from about 1 MHz (though for extremely low-cost, low-­
power applications, the clock speed can run as low as 32.768 kHz to about
and for fast systems up to 1 GHz.)

8-Bit vs. 32-Bit


The devices we will use in this book are quite powerful. They consist of a
32-bit microprocessor core which means that the number of bits of data
that can be processed by the microcontroller is comprised of 32 registers (a
register is a small storage location for data within the microcontroller; we’ll
talk about this more in the next chapter). For a long time, however, 8-bit
devices ruled the microcontroller market.
Historically, 32-bit devices were expensive and hard to program. Due
to advances in technology, the cost of 32-bit devices has been declining
to the point of where they can rival 8-bit devices for all but extremely
cost-sensitive applications. Meanwhile, thanks to the myriad of tools now
available to use with them, 32-bit devices have become amazingly easy
to program and control. While 8-bit microcontrollers are still alive and
relevant, a lot of their market share is being replaced by 32-bit devices.

4
Chapter 1 Getting Ready

For beginners, 32-bit devices are an especially useful learning tool


because they contain more memory and have greater memory addressing
capabilities. This allows for a higher level of abstraction, meaning
it is typically easier to program a 32-bit device without a thorough
understanding of its inner workings. By contrast, since 8-bit devices
have less processing power and memory, you need to have a deeper
understanding of the internals of the device to better manage memory
resources and write effective programs.

Microcontroller Programming Languages


In this section, we will look at some of the languages available for
programming microcontrollers. While there are several options to choose
from, microcontrollers have been mostly resistant to the overcrowded
zoo of programming languages that make up the modern software
development landscape. Historically, the microcontroller world has
been dominated by the C programming language. This is because
microcontrollers have traditionally only had a few bytes of memory and
run at a few tens of megahertz of clock speed, and C is particularly well
suited to working on memory-constrained systems. Nowadays, though,
you can find microcontroller devices that have multiple cores that run up a
gigahertz and possess several megabytes of memory, opening up space for
other languages to be used.

Assembly Language
At one point in time, microcontrollers were programmed exclusively in
assembly language. Today, assembly language is reserved for devices
with limited memory and for situations where the programmer needs to
squeeze every drop of performance out of the microcontroller. Assembly
language is useful in these situations because a lot of assembly instructions

5
Chapter 1 Getting Ready

translate directly into machine instructions on the microcontroller. This


means that there is less overhead in the execution of the instructions,
making code segments written in assembly language faster. While
assembly language is fast, it takes a lot of instructions to perform a simple
task on the device. Another limiting factor of assembly language is that for
each device you are programming, you must learn the assembly language
for that device. Given these limitations, the language has declined in
popularity for all but niche situations.

C
C has long been the language of choice in the embedded world. It was
made to run on memory-constrained devices such as microcontrollers. C
gives us the ability to control the underlying hardware efficiently – one C
instruction translates into several assembly language instructions – and
it can match the speed of assembly language for most applications. Since
C has been used for so long, a lot of the code that is written has been
battle tested and proven to work for the applications they are intended. C
users have access to a large code base with helpful information and code
snippets. However, the language requires a good understanding of the
hardware and is difficult for beginners to break into.

C++
As time progressed and embedded devices became more powerful, some
microcontroller manufacturers and software vendors began adding C++
support to their devices. C++ is slowly gaining traction in the professional
embedded space. In the hobbyist realm, however, C++ finds widespread
use on the Arduino platform. C++ is a large and difficult language to learn,
however. Many of the features that make C++ more effective to use than
C in general-purpose computing applications, sometimes cannot be

6
Chapter 1 Getting Ready

implemented on the resource-constrained microcontroller devices. This is


because while C++ can match the performance of C for most applications,
C++ tends to use more memory, a precious resource that is usually not
bountiful on microcontroller devices. For that reason, C++ is reserved for
the higher-end devices.

BASIC
In the early 2000s, if a beginner was getting started with microcontrollers
and did not fancy assembly, BASIC was the programming language to use.
BASIC stands for Beginners’ All-Purpose Symbolic Instruction Code and
is an easy programming language to use. There would usually be a BASIC
interpreter on the microcontroller chip to run the instructions.
BASIC eventually fell in popularity because the boards that ran it
cost a lot of money relative to what they were capable of. Additionally,
running the BASIC interpreter slowed the chips down and took up too
many resources on the already constrained 8-bit devices. Also, the tools
and software for the most popular BASIC devices were all closed source,
so people could not make their own BASIC devices. When open source
alternatives like the Arduino came around, devices like the BASIC Stamp
thus fell out of favor.

Rust
The Rust programming language is new compared to C (which is almost
half a century old) and is designed to upset the C and C++ hold on systems
programming, including embedded programming. As microcontrollers
become more powerful and factors like concurrency (the ability to carry
out multiple processes at once) start to matter, Rust’s advantages over C
begin to show. Rust is better suited to concurrency because it can handle
a data race, which is when two devices try to access the same location in
memory at the same time.

7
Chapter 1 Getting Ready

While Rust could replace C, there is no reason for the industry to


adopt it anytime soon. Embedded software is called firmware for a reason:
it doesn’t change all that often, and much of the code that has already
been written has no reason to change to a new language. C works and has
a lot of established toolchains and devices, and there are many skilled
developers comfortable with the language. However, there are already
tools available that allow Rust to be used on microcontrollers, and as time
progresses, Rust may gain some share in the embedded market.

Python
Python is a relative newcomer to the embedded space, and it could
become a major player in the field. Python is a lot simpler than C to learn
and is one of the most popular programming languages today. While
BASIC was also easier than C for beginners, Python has several advantages
over BASIC that make it better suited for use as an embedded language.
Notably, while the popular BASIC microcontrollers were closed source,
Python is open source, allowing you to run Python on your custom device
if you desire. Python files can also be compiled to make them smaller,
allowing you to create tight, memory-efficient programs.
Many people say that interpreted languages like Python are not
suited to the limitations of microcontrollers. This may have once been
true, but with today’s more powerful devices, it is entirely possible for
microcontrollers to run interpreted languages without hiccups like the
speed limitations experienced by older BASIC devices. For extremely
time-efficient computing, also called real-time computing, interpreted
languages are still not suitable. However, Python should have no problem
meeting the speed requirements of the majority of microcontroller
projects.

8
Chapter 1 Getting Ready

While Python is not as fast or efficient as C when running on


microcontrollers, its ease of use makes it worthwhile, especially if you are
now getting started with microcontrollers. Additionally, you can extend
Python code with C, which means you can leverage existing C code bases
that have been battle tested and refined over the decades.
The Python interpreter as it exists on general-purpose computers
cannot be directly implemented on a microcontroller with the same
available features. This is because the standard Python interpreter is a
large program that relies on features that would be given by the operating
system, particularly memory and hardware interfacing features, a luxury
nonexistent on microcontroller devices. Two modified forms of the
language interpreter, MicroPython and CircuitPython, bridge the gap
between the standard Python interpreter and the embedded space. Of the
two, MicroPython is targeted more toward professional developers and
precedes CircuitPython. CircuitPython, developed by Adafruit, is simpler
to use, making it an excellent learning tool for beginners as well as a
platform for professionals. The major feature of CircuitPython that makes
it user-friendly is that you do not need to compile a program before it can
run on the microcontroller. As soon as you save a program, it is run and
executed.
CircuitPython promises to be available for more resource-constrained
devices and is expected to remain well supported into the foreseeable
future. For these reasons, we will use it throughout this book.

Selecting a Development Board


To work on the projects in this book, you will need a development board
with a microcontroller that can run CircuitPython. A development board
contains a microcontroller as well as the connections required to power

9
Chapter 1 Getting Ready

the board and get it up and running. A development board allows you to
use, program, and prototype with the microcontroller without worrying
about the hardware setup.
At the time of writing, CircuitPython supports over 140 boards, and the
list keeps growing. You can view the list here on the CircuitPython website:
https://circuitpython.org/downloads. Any one of these compatible
boards will work with this book. You can also choose to create your
own custom device that supports CircuitPython, a process I will discuss
at the end of this chapter. For beginners, however, using a premade,
CircuitPython-­compatible board will always be a better choice. It will
ensure that the hardware is working and allow you to get started more
quickly with writing software for your device.
In this section, we will look at some preconfigured devices that can run
CircuitPython. Though many companies supply microcontroller boards
that are capable of running CircuitPython, Adafruit devices have the best
support since they originated the language and have an entire ecosystem
built around CircuitPython with their development environment.
We’ll look at some of the boards that they have available, along with
some popular boards from other manufacturers that can be used with
CircuitPython. This list is not exhaustive, but the boards presented here
will be compatible with the examples discussed in this book.

Adafruit Metro M0 Express


The first board we will look at is the Adafruit Metro M0 Express, pictured
in Figure 1-1. This board is an ideal choice to be used with the examples
in this book, as it is powered by a SAMD21G18A microcontroller. This
board also has the Arduino form factor; this means that it can be used
with existing Arduino shields. Thus, the powerful Arduino ecosystem
can be used to easily prototype with Arduino shields in Python. The
SAMD21G18A represents the “ideal minimum” that is required to run

10
Chapter 1 Getting Ready

CircuitPython. Its features allow it to run the interpreter without any


hiccups. The SAMD21G18A has a 48 MHz clock, 256KB of flash memory,
and 32KB of RAM. (For comparison, boards powered by the ATmega328
microcontroller, like the Arduino Uno, offered 8 times less flash and 16
times less RAM.) The Metro M0 Express also has 2MB of flash storage that
can be used to store programs and other files. You may be able to run the
CircuitPython interpreter with less memory or less processing power than
the SAMD21G18A offers, but the experience may not be seamless.
The SAMD21G18A microcontroller was one of the first devices to
support CircuitPython, and boards built around this device are usually
among the first to receive the newest versions of the interpreter. In
particular, the Metro M0 Express was the first Adafruit Metro board
designed to use CircuitPython. It is considered the standard board for
running CircuitPython, and it will be able to run the programs in this book
decently.

Figure 1-1. Adafruit Metro M0 Express [Credit: Adafruit,


adafruit.com]

11
Chapter 1 Getting Ready

Adafruit Feather M0 Express


If you want a more minimalist approach to development, you can grab
the Feather M0 Express from Adafruit, shown in Figure 1-2. Because it
is also built around the SAMD21G18A processor, this board has all the
capabilities of the Metro M0 Express: the same 48 MHz clock, 256KB of
flash, and 32KB of RAM. It also has the same onboard 2MB of flash storage.
However, it is more compact than the Metro, and it has 5 fewer I/O pins –
20 rather than 25.
A cool feature of this board that the Metro M0 Express lacks is the little
prototyping area in the front. When you have become acquainted with the
Metro M0 Express and you want a board to embed into your own projects,
then you can use this smaller, cheaper board. There is also the QT Py board
from Adafruit which is even more compact than the M0 Express should
you need an even smaller board for your projects.

Figure 1-2. Adafruit Feather M0 Express [Credit: Adafruit,


adafruit.com]

12
Chapter 1 Getting Ready

Adafruit Metro M4 Express


If you need a little more oomph than the Metro M0 Express offers, then you
can grab the Metro M4 Express, shown in Figure 1-3. The board is powered
by the SAMD51J19 microcontroller, which offers better performance than
the SAMD21G18A-based devices discussed earlier. At 120 MHz, it runs at
more than double the clock speed of the SAMD21G18A-based boards, and
it features 512KB of flash memory, 192KB of RAM, and an additional 2MB
of onboard flash storage.
These enhanced features provide better support for digital signal
processing (DSP) and floating-point processing applications. If you want to
use your board for applications like audio processing, or if you’re looking
for better security capability or general performance improvement, then
this is a good board to use. However, the heightened performance comes
with a trade-off. The Metro M4 Express’s processor will consume more
power than the boards discussed earlier. Depending on your application,
this may not be much of a factor, though, as the board is still power
efficient.

Figure 1-3. Adafruit M4 Metro Express [Credit: Adafruit,


adafruit.com]

13
Another random document with
no related content on Scribd:
officers assembled to await our return, to whom we had to narrate
the whole of the incidents of the night’s adventure. Our surgeon
announced that Mr. Osborne was in his cot, and was suffering much
from his sprained ankle; so Mr. Thompson mercifully left him alone,
vowing he would have his revenge at a more suitable opportunity.
The next morning the American captain, his wife, and the rest of
the party came off and breakfasted with Captain Graves by the
latter’s express invitation; and from the peals of laughter that issued
from within, it was evident that host and guests were in the highest
good-humour. Afterwards the Americans briefly inspected the ship,
and then rowed back to the Snapping Turtle; while we made every
preparation for departing in search of the Flying-fish and her piratical
crew.
After the ship’s company had had their dinner, the boatswain piped
“Up anchor!” and half an hour later we were standing out to sea
under a full head of steam.
CHAPTER II.
WE STORM THE FORT.

A FTER a long and patient search, our vigilance was rewarded by


the discovery of the Flying-fish, securely moored in an almost
land-locked creek on the southern coast of Cuba. It was impossible
for the Rattler to enter, on account of her draught; nor could she
bring her guns to bear on the merchantman, for that craft was
protected by an outlying spit of land, over which her spars alone
were visible.
Under these circumstances there was no alternative but to send in
some of the boats to cut her out; and the pinnace, the first and
second cutters, and the jolly-boat were quickly got in readiness for
the service. As far as we could see with our glasses, there was a
battery on the heights above the creek; but as it was probably
garrisoned by Spanish regulars, Captain Graves refrained from
opening fire. We soon, however, saw the true nature of this work; for,
as soon as the crew of the Flying-fish saw that we were going to
push in with our boats, they abandoned their ship, and putting off to
the shore, leisurely retreated into the fort, where we saw them get
into readiness to open fire as soon as our flotilla should get within
range. It was pretty evident that they were being encouraged in their
resistance by bodies of insurgents, who had apparently seized the
battery and killed or dispersed the Spanish garrison.
Mr. Thompson commanded the flotilla of boats, and took his
station in the pinnace, which carried a nine-pounder Armstrong gun
in the bows. He had previously sent for Charlie Balfour and myself,
who were to go in the first and second cutters, and had given us an
outline of the proposed operations.
“There is little doubt of our success, Mr. Darcy,” he had said
laughingly; “but I must warn you and your brother-midshipman not to
allow your men to waste their ammunition, and mind you attend
strictly to any orders I may issue from the pinnace.”
“Jolly spree this will be, Jack; won’t it?” Charlie had sung out to me
just as we were getting into our respective boats.
“The best lark we’ve had all the commission, I expect,” I had
answered with boyish thoughtlessness.
We had reason to change our minds when we reached the shore
and grappled with our determined foes.
At the last moment the captain sent a sub-lieutenant and the
gunner to assist us in the cutters, and the boatswain and one of the
middies shared the honours of the jolly-boat.
With a cheer we shoved off from the ship, fully expecting to see
jets of flame dart from the embrasures of the fort, and hissing shot
and shell come hurtling through the air in our direction. At first,
however, all was silent in the battery. Not even a cheer or a shout
was audible, and no defiant bunting flew from the flagstaff which
occupied a prominent position on the sea-front.
Mr. Thompson immediately took the offensive, and with his nine-
pounder opened a brisk and well-directed fire upon the mutineers
and their allies. This had the effect of creating some confusion within
the fort, as we were able to observe with our glasses; and this was
still further increased when we began peppering them with rockets
from the cutters. After a time, however, they steadied down and
returned our fire with very indifferent aim from six guns, which
appeared to be the armament of the work. The Rattler now brought
some of her guns to bear, and her heavy shell told with great effect,
making a breach in the sea-front and dismounting two of the guns
even before we had reached the landing-place.
Under cover of this iron hailstorm we got our gallant fellows safely
on shore, formed them up, and charged forward up the hill at the
double. As yet not a man had fallen, though there had been some
narrow escapes which seemed to me almost miraculous. As we
swept up the slope to the assault, the enemy depressed the muzzles
of their remaining guns, and met us with a galling salute of grape-
shot. This discharge, at almost point-blank range, cut up our ranks a
little. Undaunted, we gave a loud cheer and pressed on without a
moment’s hesitation—Mr. Thompson waving his sword well in
advance, and shouting words of encouragement.
The frigate was now obliged to suspend her fire, as was also the
pinnace, which latter, in charge of the gunner, had taken up a
position in the creek so as to cover our advance.
In the onward rush, Charlie and I found ourselves advancing side
by side, though we could scarcely identify each other through the
cloud of dun war-smoke that enveloped us as we approached the
battery. Now and again the ruddy jets of flame darted angrily through
the vapour, as the mutineers and insurgents plied their guns; and the
hoarse roar of the artillery and the sharper rattle of the musketry
made a terrible din in our ears as we pressed onwards.
As yet we had not fired a shot in return, as Mr. Thompson’s plan
was to rush the fort and, if possible, carry it at the point of the
bayonet in true British style.
“Well, Jack,” shouted Charlie, “what do you think of this for a nice
little shindy?”
“It’s rather awful,” I replied; “not that I funk it in the least, but I can’t
bear to see our brave fellows knocked over. Lobb, the captain of the
mizzen-top, was killed by a round-shot just now, and you know he
was rather a pal of mine.”
“I’m awfully sorry, I can tell you, old man,” said Charlie in
sympathetic tones; “I didn’t know the poor fellow had lost the number
of his mess. Lobb was such a general favourite that everybody on
board the Rattler will miss him.”
“We’re close to the fort now,” I said, drawing my loaded revolver
from my belt. “Let’s stick to each other, Charlie, and try to be first
over the rampart!”
“We’ll make a dash for it at any rate!” shouted my friend excitedly.
“Come along, Jack; try to think you’re winning a hurdle-race!”
Like an inrushing tide, determined to drive everything before it, our
little naval brigade swept up to the attack, and with a ringing cheer
threw itself, sword and revolver in hand, into the breach which the
frigate had made with her shell.
A more diabolical set of men than those who clustered on the
rampart to meet us I had never before seen. They were not in the
least cowed by our determined attack, and met us with shouts of
defiance and rage, some discharging pistols in our faces, and others
pouring in volleys of musketry, which for a moment checked our
advance.
But only for a moment!
Charlie and I did not succeed, much to our disappointment, in
being the first to cross swords with the enemy. However, there was
no time to think about such things at the moment, for our work was
cut out for us, and a foe worthy of our steel, desperate and
determined, was lining the earthworks to dispute our advance inch
by inch and foot by foot. All our energies, and all our dogged British
courage and persistence, were called into play at that supreme crisis
in our fortunes; and well and valorously did our noble blue-jackets
respond to our call.
As Charlie and I scrambled upwards, still mercifully unscathed, we
caught sight of Mr. Thompson’s and the boatswain’s forms erect
upon the rampart, looming huge through the smoke, and in a few
seconds we had scrambled up beside them through a storm of
bullets. Then was heard the sharp ringing clash of steel as we
crossed swords with the desperadoes. As we had suspected, they
had leagued themselves with a ferocious band of Creole insurgents,
who no doubt anticipated sharing in the plunder of the Flying-fish.
Very soon after the mêlée commenced, I saw Charlie—who had
got a little separated from me—seized by two of the mutineers, and,
in spite of his violent struggles, thrown violently over the wall into the
ditch. Much to the astonishment of an antagonist with whom I was
crossing swords at the time, I disengaged myself from him and
darted to the rear in search of my chum, much fearing that I should
find him badly hurt. No doubt the piratical fellow I had been fighting
with thought that I was fleeing from him in dismay; but fortunately he
did not attempt to follow me. Nor did I meet with any obstruction by
the way; for every moment our brave fellows were pressing forward
and slowly but surely driving the enemy back, though the latter, to do
them full justice, fought most tenaciously, and seemed little inclined
to surrender.
It took me only a few seconds to rush down the embankment, and
I at once caught sight of Charlie’s prostrate form extended
motionless in the ditch. Close beside him lay the dead body of a
seaman who had been shot through the head with a rifle-bullet just
as we were about to rush the fort. In a moment I was at my friend’s
side, half dreading that he might be dead too; for he lay motionless,
with his white face upturned to the sky.
In vivid contrast to all the sounds of battle was the deathlike
stillness of that gloomy ditch, where the two human forms lay inert
and apparently lifeless.
In an agony of apprehension I knelt down at Charlie’s side, and
called him loudly by his name, at the same time placing my hand
upon his heart to feel whether it still throbbed with life. I fancied there
was a faint pulsation, and this gave me hope; but I was alarmed to
find that my friend’s head had been cut and was bleeding rather
profusely. This I quickly bandaged with my pocket-handkerchief; and
then, as there appeared to be no signs of returning consciousness, I
looked about me to see if I could discover any water near. By great
good-fortune, I found a little stream trickling down the hillside not fifty
yards away. Overjoyed at this discovery, I ran quickly across the
intervening space, took up some of the water in my cap, hurried back
to Charlie’s side, and commenced bathing his temples with the
refreshing liquid.
To my joy the effect was almost immediate, for after a few
moments I noticed a little colour coming back into his cheeks, and a
quivering of the eyelids. I wetted his lips, and chafed his cold hands
with my warm ones.
“He’s coming round all right,” I muttered. “I must persevere for a
few minutes.”
Presently my friend moved uneasily, and then opened his eyes,
which rested upon me with a frightened expression.
“You’re all right, old chap,” I said reassuringly. “You fell over the
embankment, and were stunned for a few minutes.”
“I recollect something about it now,” he replied faintly, making a
futile attempt to raise his right hand to his head. “A fellow pitched me
over—yes—an awfully strong chap—I’d like—”
“Don’t talk till you’re feeling a bit stronger,” I interrupted. “Try to
take a drink of this water.”
My friend managed to swallow a mouthful or two, and the effect
was almost instantaneous, for he presently sat up and looked about
him.
“Damaged about the head,” he observed, his hand straying to the
bandage; “but I don’t believe it’s anything very bad.”
“It’s just cut a little by a stone,” I said; “but I don’t believe you’ve
got any bones broken, Charlie, or you wouldn’t be able to sit up like
that.”
At this moment one of our surgeons who had accompanied the
force came running up at full speed, carrying a case of instruments
in one hand.
“I’ve only just caught sight of you fellows,” he exclaimed, as he
arrived breathless on the scene. “What did you stow yourselves
away in this ditch for, I should like to know?”
I hurriedly explained the position of affairs.
“Well, I must just overhaul you, Balfour,” said the surgeon, laying
his case of instruments upon the ground, and turning to examine
him. “I trust, however, that it’s only a case of cuts and bruises, which
boys are pretty well accustomed to.”
“Have a look at that poor fellow first,” said Charlie, pointing to the
body of the poor seaman which lay near him; “I’m afraid he’s much
worse off than I am.”
The surgeon bent down and felt the pulse and heart of the poor
fellow, more as a matter of form than anything else. The bullet-
wound in his forehead told its own tale only too legibly, and that tale
was: “Died for Queen and country.”
The surgeon now again turned his attention to Charlie, and soon
announced, much to my joy, that there was no serious damage
done.
“We’ll have you carried on board as soon as possible,” he said,
“and you’ll be as right as a trivet in a few days, if you keep perfectly
quiet in a cot.”
“Do you know if the scrimmage is over?” I asked the doctor.
“Our fellows were driving all before them when I last had a glimpse
of them,” the medico replied.—“Hallo! who are these rascally-looking
villains bearing down upon us?”
Turning in astonishment, I beheld four armed desperadoes swiftly
approaching us from the rear.
CHAPTER III.
A FIGHT FOR LIFE.

I T was a ticklish moment, but the surgeon was coolness itself.


“Stand steady, Darcy!” he cried to me in resolute tones, as he
drew his sword from its sheath. “Empty your revolver amongst them,
my boy, and be careful to take steady aim.”
I must confess that I felt a little flurried at this moment, though I
tried hard to pull myself together, knowing how much depended upon
my coolness and resolution. This attack by a detachment of the
enemy was so sudden, and was made in such a determined manner,
that it is small wonder that my presence of mind deserted me for a
few moments.
Charlie tried in vain to rise, and then sank back in an exhausted
state.
“Give me a weapon to defend myself with,” he said hoarsely; “I
won’t be killed without a struggle, weak as I am.”
My friend’s faltering voice and pathetic request helped to recall my
wits, and braced up my nerves like a powerful tonic. I darted to the
dead blue-jacket’s side, and gained possession of his rifle and
cutlass. The latter I handed to Charlie with the remark, “We’ll defend
you, old chap, but you may as well have this bit of steel in your fist.”
Then I glanced hurriedly at our approaching foes. They were only
twenty yards distant. Every moment was precious indeed. There had
been no time for me to obtain cartridges from the dead man’s pouch,
but I now hastily opened the breech of the rifle and discovered, to my
delight, that it was loaded. Without a moment’s hesitation I dropped
on one knee, levelled the piece, and took careful aim at one of the
leading desperadoes.
A jet of flame issued from the muzzle of the rifle as I pressed the
trigger, and then a little puff of sulphurous smoke. At almost the
same moment the man at whom I had aimed sprang several feet
from the ground in a sort of convulsive bound, and then fell heavily to
the earth a lifeless corpse.
Unfortunately the surgeon had no pistols with him.
“Well done, my boy!” he cried, as he saw the effect of my shot;
“that’s reduced the odds against us, at any rate.”
“Do give us a hand, Jack,” cried Charlie, making a fresh but
equally futile attempt to struggle to his feet. “I’m sure I can do
something to help.”
“Just you shut up, Charlie!” I said angrily; “you’re only balking me
at the moment when—”
I broke off short, for a bullet from a pistol whizzed so close to my
head that it almost grazed my temple.
Two of our antagonists, who possessed pistols, had opened fire
upon us at almost point-blank range. It was fortunate for us that they
were so poorly supplied with firearms. Had it been otherwise, our
chances of success would have been slender indeed.
The surgeon stood unscathed, his bright sword-blade flashing in
the sunlight. He was a Scotsman, tall, lithe, muscular, and a very
good fencer. I felt sure that he would make very short work of an
indifferent swordsman, however powerful an individual the latter
might be. For all we knew, however, the unprepossessing men who
were bearing down upon us might be adepts at wielding the
cutlasses which they were waving defiantly in the air as they
bounded along.
“Blaze away with your revolver, my lad!” shouted the doctor. “Don’t
let them all come to close quarters.”
I had already taken aim with my Colt, trusting to make another gap
in the little detachment before it rushed in upon us. Sharply the
report rang out, the surgeon gave an exultant shout, and as two
villanous-looking fellows charged in upon us with glaring eyeballs
and features distorted with rage, I caught a hasty glance of the man I
had covered with my pistol writhing on the ground and uttering
horrible imprecations. I afterwards discovered that I had shot him in
the right shoulder, and had thus effectually debarred him from taking
part in the conflict.
The odds were thus made even, but I felt that even man for man
we had our work cut out for us, for both our antagonists, though
rather below middle size, were square-built, powerful-looking fellows.
Their brawny, sunburnt throats and chests were bare, and the rolled-
up sleeves of their loose jackets displayed muscles and sinews of
which any athlete might have been proud.
I had again levelled my revolver, hoping to get in another shot; but
before I could take proper aim or press the trigger, my invaluable
little weapon was struck from my hand by a blow from the cutlass of
the man who had singled me out for attack. Most fortunately my
hand escaped injury, for I was quite sure that my opponent had fully
intended to sever it from my arm at the wrist. Stepping back a pace, I
hurriedly shifted my sword from my left hand to my right, and brought
it to the first guard, keeping my eyes warily fixed upon the dark, cruel
orbs of my savage-looking antagonist. It flashed like lightning
through my brain that, by great good luck, I was not pitted against an
expert swordsman, for I saw him again raise his cutlass in order to
deliver a swashing blow instead of making a straight and direct lunge
at my heart.
“I’ll have him now!” I muttered, feeling all the self-confidence of a
youngster who had not reached his seventeenth year; and with great
promptitude I shortened my sword and drove the sharp point straight
at his breast, just as he had unwarily left it exposed by raising his
brawny arm to cut me down. I ought to have got that point home. By
all the laws of fence my antagonist’s life was at my disposal, and he
should have been stretched upon the sward at my feet; but as ill luck
would have it—we always attribute our misfortunes to ill luck, don’t
we?—I slipped on a patch of wet grass, and fell prostrate at the very
feet of my foe, my nose coming into violent contact with a hard
mound of earth.
Although this contretemps was most unexpected, and the shock
considerable, I had presence of mind enough to keep a firm grip of
my sword. One does not lightly part with a firm and trusty friend.
But oh, how well I remember, even at this distance of time, the
awful thought passing swiftly through my brain, “I’m helplessly in the
power of my antagonist, and he’ll assuredly kill me.”
A boy, however, does not give in while there’s a chance left, slight
and remote as it may be, and even as the thought recorded above
flashed through my mind I struggled to rise. As I turned my head I
saw, to my horror, that my foe, with a cruel and exultant smile on his
lips, was on the point of running me through with a downward
stabbing blow. It was impossible to avoid this thrust in my helpless
position, and I felt an icy feeling of despair at my heart. Then the
sharp crack of a revolver—to my intense astonishment—cleft the air,
and the next moment the fellow who had been so intent upon
finishing me off fell across me with a terrific thud, and I lost
consciousness from the violence of the shock.
CHAPTER IV.
WE RETURN ON BOARD.

IT was not long before I recovered my senses. When I did so, I


found that I was stretched upon the ground, and that the surgeon
was bending over me bathing my temples with water.
“That’s right, youngster!” he cried encouragingly; “I knew you
wouldn’t take long to come round, though Balfour declared you were
shamming just to excite our sympathy.”
Memory returned in a flash.
I sat up without assistance, and gazed about me with great
curiosity.
Close to me, and reclining against a convenient hillock, was my
friend Charlie. He still looked ghastly pale, and his bandaged head
seemed to add to the impression; but he was evidently better, and
there was life in his handsome dark eyes. At his feet lay my revolver
and the cutlass I had given him. Stretched on the ground at the
distance of some yards were the bodies of our late enemies, now
powerless for evil.
“That chap must have taken your wind jolly well, Jack,” said my
friend, pointing to one of the corpses; “but you may thank your stars
that he didn’t take your life. By Jove, he went for you like a wild
beast!”
“How did it happen?” I asked in a rather bewildered manner. “Who
shot him, and where did the pistol come from?”
“Balfour will never tell you,” remarked the surgeon, whose name
was Grant; “he’s much too modest a fellow. The truly brave and the
truly great are not given to blowing their own trumpets. I’m afraid I’m
just the opposite, and blow a tremendous blast on mine whenever an
opportunity offers. Not having been born with a silver spoon in my
mouth, I have to—”
“Blow upon a silver trumpet,” interrupted Charlie rather rudely.
“Ah, I see you’re recovering rapidly,” said Dr. Grant good-
naturedly, giving me at the same time a sly wink.
“But do you mean to say that Charlie shot him!” I exclaimed
excitedly; “he had no firearms.”
“Ah, that’s where the story comes in,” said the surgeon with a
laugh. “Balfour saw that you were about to be spitted upon yonder
fellow’s sword, and also saw that I was engaged in a desperate
hand-to-hand conflict with the other villain, and was powerless to
render you any assistance; so what does he do but crawl out and
gain possession of the revolver which had been dashed from your
hand at the first shock of conflict—as Sir Walter Scott would have
said. To his delight he found that there was still one cylinder loaded;
but there was not a second to lose, for your end was at hand. The
deadly shot was fired, and so truly sped the bullet to its billet that the
fellow for whom it was destined fell dead without so much as a cry or
a groan. It was a masterpiece. I’ve no hesitation in saying so, upon
my word.”
“Charlie,” I cried emphatically, “you’re the best chum I ever had,
and I owe my life to you!”
“What nonsense!” exclaimed Charlie. “Do you suppose I was
going to sit still and see you stuck like a pig? Not if I know it, old
chap.”
“And he was almost too weak to crawl,” I said, turning to Dr. Grant.
“It was splendid of him!” and my eyes filled with tears.
“We may all thank God for our narrow escape,” said the surgeon;
“at one time I thought I had myself caught a Tartar.”
At this moment the air was rent with loud halloos and triumphant
shouts, and we saw the officers and men of our little naval brigade
pouring down over the embankment of the fort.
In five minutes they were around us, listening to our story and
detailing their own.
“The beggars have fled in all directions into the interior,” said Mr.
Thompson in conclusion. “We’ve spiked their guns, and taken a
number of prisoners, arms, and ammunition.”
“That’s very creditable and satisfactory as far as it goes,” said Dr.
Grant, rather dryly; “but the principal question to my mind is, what
has become of the valuable cargo which is known to have been on
board the Flying-fish when the mutineers seized her?”
“Why, what a croaker you are!” exclaimed the lieutenant
laughingly. “I should say that the so-called valuable cargo is at the
present moment safely in the hold of the Flying-fish.”
“I very much doubt it,” said the surgeon laconically; “but we won’t
argue the point now, as I am anxious to get the wounded on board
the Rattler with as little delay as possible, and I daresay you won’t be
sorry to get rid of your prisoners.”
The lieutenant looked thoughtful as he marched off with his men,
and it occurred to me that he was wondering whether the
merchantman had been entirely abandoned by her crew, and
whether or not Captain Graves had sent a boat to ascertain the fact
during our absence on shore.
Charlie was put on a stretcher and carried carefully down to the
place of embarkation, but I was now sufficiently recovered to walk
with the occasional assistance of the surgeon’s arm. In half an hour
we were all safely on board the Rattler again, and Mr. Thompson at
once went to make his official report to the captain. I accompanied
my friend below, and saw him snugly ensconced in a cot in the sick-
bay.
The operations ashore had taken place rather late in the
afternoon, and the sun had already begun to sink in the west when
we returned on board the frigate. I had now quite recovered from the
effects of my adventure, and was ravenously hungry and thirsty; so
after administering some beef-tea to Charlie, I repaired to the
gunroom to get some tea, during which meal I had to relate over and
over again to those of my messmates who had been debarred from
joining the expedition the story of our hairbreadth escape.
“We had a mild kind of excitement while the landing-party was
ashore,” observed one of my brother-middies, as he looked
disconsolately into a nearly empty pot of marmalade.
“What was that?” I asked, hacking away viciously at a huge loaf. “I
suppose you had a rat hunt in the bread-room with the commander’s
dog and the ship’s cat.”
“It would have been a case of ‘the dog that worried the cat that
killed the rat,’ I should say, if we had gone in for that sort of sport,”
answered my messmate laughingly.—“Steward, bring me a pot of
strawberry jam.”
“Well, don’t keep me in suspense any longer,” I said impatiently,
“or you’ll take all my appetite away; honour bright.”
“Darcy’s off his feed, you fellows!” shouted my teasing brother-
middy, whose name was Fitzgerald; “and I can positively count his
ribs through his waistcoat.—Steward, bring a soup-tureen of oatmeal
porridge in this direction and a few gallons of buttermilk, for there’s a
young gentleman here at the last gasp for want of nourishment.”
The steward at this moment entered the mess with the pot of
strawberry jam which had been ordered; but before he could deposit
it upon the table in front of Fitzgerald, I had snatched it from the tray
and placed it by the side of my own plate. Then seizing a large table-
spoon, and without even looking at the rightful owner of the
preserve, I made a pretence of digging out an enormous spoonful of
it for my own special gratification.
“O you greedy beggar!” shouted Fitzgerald, starting up and trying
to snatch his property from me. “Even if you were more like a
skeleton than you are, you’ve no business to grub away at another
fellow’s jam like that.”
But I put one firm hand upon the jam-pot, and waved him away
with the other which held the spoon.
“Spin your yarn and eat your jam, or hold your tongue and see it
go into my capacious maw,” I said, grinning at him. “You pay your
money and take your choice, old man.”
Fitzgerald laughed. “I’d like awfully to punch your head, Darcy, but
unluckily fighting isn’t allowed in the mess. The yarn is short, I’m
thankful to say, and so you won’t have much time to stow away my
jam in that horrid ‘capacious maw’ of yours. Well, as the story is
wrung out of me, I must tell you that whilst you were on shore
pretending to scrimmage with the mutineers and their allies, we
manned the remaining boats, and under the commander’s orders
boarded the Flying-fish. I was in the gig, and was on the tiptoe of
expectation, wondering whether we should meet with resistance, or
find the ship entirely deserted. The commander told us that he hoped
at any rate to gain possession of the valuable cargo which was
supposed to have fallen into the hands of the mutineers, and which
was reported to be worth many thousands of pounds. Imagine our
disgust, then, when we clambered up the side and found that the
ship was nothing more nor less than an empty and deserted hulk.
Every bit of the cargo that was of any value had been removed
ashore, and the only living beings we found on board were the
second mate and the boatswain, and they had been securely put in
irons long before the Flying-fish had entered the creek. Of course,
we immediately released the poor fellows, and found them half dead
from exhaustion and semi-starvation. It was they, of course, who told
us about the cargo having been taken out of the ship, and they
added that they were positive that in some way the mutineers had
heard that a British cruiser was on the look-out for them, most
probably through their insurgent friends ashore.”
“No doubt that was it,” I said, “and they took the precaution of
hiding their ill-gotten gains away in some inaccessible place up
country well-known to the rebels.”
“My pot of strawberry jam, please,” said Fitzgerald austerely, and
holding out his hand in what I considered rather a peremptory
manner.
“I’ve a good mind to levy blackmail,” I cried, flourishing my big
spoon; “but on second thoughts I’ll be magnanimous, and hand it
over intact. It’s awfully good-natured of me!”
Fitzgerald was still more “awfully good-natured,” for after helping
himself in what I considered a very lavish manner, he handed me
over the crock with a lordly air and the very unnecessary remark,
“Help yourself, old chap, but leave us a scraping at the bottom.”
It was my first watch that night, and I was pacing the deck in a
somewhat dreamy state, and longing for midnight to arrive that I
might be enabled to turn in, when I saw the gunner, Mr. Triggs,
ascend the main hatchway, walk to the starboard entry-port, and
gaze out upon the moonlit waters of the roadstead.
“Well, Mr. Triggs, how are you this evening?” I said, accosting him.
“None the worse for the shindy on shore, I hope?”
“Not a bit, thank you, Mr. Darcy. Didn’t get a scratch, I’m thankful
to say; and now I’m only hoping that I may have the good luck to see
a bit more service ashore.”
“I’m afraid we won’t get the chance again in a hurry,” I answered.
“It isn’t every day that crews mutiny on the high seas.”
“Ah, you haven’t heard the news then,” said the gunner with a
chuckle. “It isn’t often I score off you like that.”
“What news?” I asked excitedly. “Do tell me, Mr. Triggs.”
“Well, I don’t know, I’m sure, if I oughtn’t to keep it to myself,”
answered the gunner, trying to look very solemn. “Maybe ’twould be
strong meat for babes, so to speak.”
“You’re positively insulting, Mr. Triggs! The midshipmen of the
Rattler will hold a drumhead court-martial on you to-morrow if I’m not
mistaken, and you may depend upon it the sentence will be a severe
one.”
“I’m beginning to shake in my shoes at the very prospect of such a
thing,” said the gunner, with a laugh; “and as I’m a married man with
a family, I think I ought to be excused if I cave in.”
“Confide in me, and the matter shall go no further,” I exclaimed,
with a patronizing air.
“I think I must have a couple of whiffs before I turn in,” said the
gunner, proceeding to light his pipe. “’Tis against orders, I’m aware,
but I rely on you, Mr. Darcy, not to split upon me to the officer of the
watch.”
“You may smoke till you’re black in the face,” I rejoined
irreverently, “so long as you heave ahead and tell me what I want to
know.”
“You midshipmen are a terribly impatient lot of mortals—”
“That’s better than being prosy and tedious,” I interrupted. “Steam
ahead full speed, Mr. Triggs, and keep a look-out for shoals.”
“So impatient that you’d try the temper of the quietest cow that
ever chewed the cud,” continued the gunner emphatically; “and as to
repartee, I’m jiggered if I think an Irish car-driver wouldn’t be out of
the running with the dullest of you. Well, I’ll relieve your curiosity, Mr.
Darcy, and the yarn is just this. Mr. Osborne, the surgeon of the
Flying-fish, told our assistant-surgeon, who had been a-doctoring of
his foot, that the captain had been questioning him about the value
of the cargo that the mutineers had seized, and had mentioned that it
was his intention to endeavour to track the rascals down and recover
the booty. On the top of that I had a message late in the evening
from the gunnery lieutenant that an armed expedition up country was
in contemplation, and requesting me to keep a weather eye lifting on
stores and ammunition and such like.”
“What perfectly splendid news!” I cried excitedly; “but I wonder if
I’ve the remotest chance of being appointed to the force.”
“You were knocked about a bit in the scrimmage ashore, weren’t
you?” asked the gunner.
“Yes; but I’m not incapacitated for duty,” I said, “or I shouldn’t be
keeping watch now. It was my chum Charlie Balfour who was
seriously hurt, poor fellow.”
“I believe it’s considered a bit feverish up country, Mr. Darcy, and
that may put a stopper on any midshipmen going; but I’m sure I
heartily wish you good-luck, and your chum a speedy recovery.” And
so saying, Mr. Triggs knocked the ashes out of his pipe, and went
below to turn in.
What exciting dreams I had that night!

You might also like