100% found this document useful (5 votes)
83 views

IoT Development for ESP32 and ESP8266 with JavaScript: A Practical Guide to XS and the Moddable SDK Peter Hoddie pdf download

The document is a guide for IoT development using the ESP32 and ESP8266 microcontrollers with JavaScript, specifically through the XS and Moddable SDK. It includes detailed instructions on setting up hardware and software environments, as well as programming concepts and networking techniques. Additionally, it provides links to related resources and books for further learning in the IoT space.

Uploaded by

tsengseyman86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
83 views

IoT Development for ESP32 and ESP8266 with JavaScript: A Practical Guide to XS and the Moddable SDK Peter Hoddie pdf download

The document is a guide for IoT development using the ESP32 and ESP8266 microcontrollers with JavaScript, specifically through the XS and Moddable SDK. It includes detailed instructions on setting up hardware and software environments, as well as programming concepts and networking techniques. Additionally, it provides links to related resources and books for further learning in the IoT space.

Uploaded by

tsengseyman86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

IoT Development for ESP32 and ESP8266 with

JavaScript: A Practical Guide to XS and the


Moddable SDK Peter Hoddie download

https://textbookfull.com/product/iot-development-for-esp32-and-
esp8266-with-javascript-a-practical-guide-to-xs-and-the-moddable-
sdk-peter-hoddie/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

MicroPython Programming with ESP32 and ESP8266 Rui


Santos

https://textbookfull.com/product/micropython-programming-with-
esp32-and-esp8266-rui-santos/

Developing IoT Projects with ESP32: Discover the IoT


development ecosystem with ESP32 to create production-
grade smart devices 2nd Edition Vedat Ozan Oner

https://textbookfull.com/product/developing-iot-projects-with-
esp32-discover-the-iot-development-ecosystem-with-esp32-to-
create-production-grade-smart-devices-2nd-edition-vedat-ozan-
oner/

Hands-on ESP32 with Arduino IDE: Unleash the power of


IoT with ESP32 and build exciting projects with this
practical guide 1st Edition Zulfiqar

https://textbookfull.com/product/hands-on-esp32-with-arduino-ide-
unleash-the-power-of-iot-with-esp32-and-build-exciting-projects-
with-this-practical-guide-1st-edition-zulfiqar/

Practical Internet of Things with JavaScript Build


standalone exciting IoT projects with Raspberry Pi 3
and JavaScript 1st Edition Arvind Ravulavaru

https://textbookfull.com/product/practical-internet-of-things-
with-javascript-build-standalone-exciting-iot-projects-with-
raspberry-pi-3-and-javascript-1st-edition-arvind-ravulavaru/
Applied Machine Learning for Health and Fitness: A
Practical Guide to Machine Learning with Deep Vision,
Sensors and IoT Kevin Ashley

https://textbookfull.com/product/applied-machine-learning-for-
health-and-fitness-a-practical-guide-to-machine-learning-with-
deep-vision-sensors-and-iot-kevin-ashley/

THE COMPLETE GUIDE TO ESP32 AND ARDUINO FOR IOT Unleash


the Power of the Internet of Things Build Connected
Devices and Automate Your Worl 1st Edition Hatake

https://textbookfull.com/product/the-complete-guide-to-esp32-and-
arduino-for-iot-unleash-the-power-of-the-internet-of-things-
build-connected-devices-and-automate-your-worl-1st-edition-
hatake/

A Practical Guide to Biomedical Research for the


Aspiring Scientist 1st Edition Peter Agger

https://textbookfull.com/product/a-practical-guide-to-biomedical-
research-for-the-aspiring-scientist-1st-edition-peter-agger/

iOS 10 SDK Development Creating iPhone and iPad Apps


with Swift Chris Adamson

https://textbookfull.com/product/ios-10-sdk-development-creating-
iphone-and-ipad-apps-with-swift-chris-adamson/

Internet of Things from Scratch: Build IoT solutions


for Industry 4.0 with ESP32, Raspberry Pi, and AWS 1st
Edition Renaldi Gondosubroto

https://textbookfull.com/product/internet-of-things-from-scratch-
build-iot-solutions-for-industry-4-0-with-esp32-raspberry-pi-and-
aws-1st-edition-renaldi-gondosubroto/
IoT Development
for ESP32 and
ESP8266 with
JavaScript
A Practical Guide to XS and the
Moddable SDK

Peter Hoddie
Lizzie Prader
IoT Development for
ESP32 and ESP8266
with JavaScript
A Practical Guide to XS
and the Moddable SDK

Peter Hoddie
Lizzie Prader
IoT Development for ESP32 and ESP8266 with JavaScript: A Practical
Guide to XS and the Moddable SDK
Peter Hoddie Lizzie Prader
Menlo Park, CA, USA Menlo Park, CA, USA

ISBN-13 (pbk): 978-1-4842-5069-3 ISBN-13 (electronic): 978-1-4842-5070-9


https://doi.org/10.1007/978-1-4842-5070-9

Copyright © 2020 by Peter Hoddie and Lizzie Prader


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: Natalie Pao
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail [email protected], 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 [email protected], or visit http://www.apress.
com/rights-permissions.
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-5069-3.
For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Authors�����������������������������������������������������������������������������xvii

About the Technical Reviewers���������������������������������������������������������xix

About the Editor���������������������������������������������������������������������������������xxi

Acknowledgments���������������������������������������������������������������������������xxiii

Foreword������������������������������������������������������������������������������������������ xxv

Introduction������������������������������������������������������������������������������������ xxvii

Chapter 1: Getting Started��������������������������������������������������������������������1


Hardware Requirements���������������������������������������������������������������������������������������1
Software Requirements����������������������������������������������������������������������������������������6
Downloading the Example Code���������������������������������������������������������������������������6
Setting Up Your Build Environment�����������������������������������������������������������������������7
Using xsbug����������������������������������������������������������������������������������������������������������7
Important Features for Examples in This Book������������������������������������������������9
Running Examples����������������������������������������������������������������������������������������������10
Installing the Host�����������������������������������������������������������������������������������������������10
mcconfig������������������������������������������������������������������������������������������������������11
Confirming the Host Was Installed����������������������������������������������������������������11
Installing helloworld���������������������������������������������������������������������������������������12
mcrun������������������������������������������������������������������������������������������������������������13
Finishing Up���������������������������������������������������������������������������������������������������13

iii
Table of Contents

Troubleshooting��������������������������������������������������������������������������������������������������14
Device Not Connected/Recognized���������������������������������������������������������������14
Incompatible Baud Rate��������������������������������������������������������������������������������16
Device Not in Bootloader Mode���������������������������������������������������������������������17
Adding a Display�������������������������������������������������������������������������������������������������18
Connecting a Display to the ESP32���������������������������������������������������������������19
Connecting a Display to the ESP8266�����������������������������������������������������������20
Installing helloworld-gui�������������������������������������������������������������������������������22
Conclusion����������������������������������������������������������������������������������������������������������24

Chapter 2: JavaScript for Embedded C and C++ Programmers���������25


Fundamental Syntax�������������������������������������������������������������������������������������������26
“Hello, world”������������������������������������������������������������������������������������������������26
Semicolons����������������������������������������������������������������������������������������������������27
Declaring Variables and Constants����������������������������������������������������������������27
The if Statement������������������������������������������������������������������������������������������29
The switch Statement����������������������������������������������������������������������������������30
Loops�������������������������������������������������������������������������������������������������������������32
Types�������������������������������������������������������������������������������������������������������������������33
undefined����������������������������������������������������������������������������������������������������34
Boolean Values����������������������������������������������������������������������������������������������35
Numbers��������������������������������������������������������������������������������������������������������35
Strings�����������������������������������������������������������������������������������������������������������39
Functions�������������������������������������������������������������������������������������������������������47
Objects����������������������������������������������������������������������������������������������������������58
null��������������������������������������������������������������������������������������������������������������68
Comparisons�������������������������������������������������������������������������������������������������������68
Comparing Objects����������������������������������������������������������������������������������������70
Errors and Exceptions�����������������������������������������������������������������������������������������71

iv
Table of Contents

Classes����������������������������������������������������������������������������������������������������������������75
Class Constructor and Methods��������������������������������������������������������������������75
Static Methods����������������������������������������������������������������������������������������������77
Subclasses����������������������������������������������������������������������������������������������������78
Private Fields�������������������������������������������������������������������������������������������������84
Private Methods���������������������������������������������������������������������������������������������86
Using Callback Functions in Classes�������������������������������������������������������������87
Modules��������������������������������������������������������������������������������������������������������������90
Importing from Modules��������������������������������������������������������������������������������90
Exporting from Modules��������������������������������������������������������������������������������93
ECMAScript Modules vs. CommonJS Modules����������������������������������������������94
Globals����������������������������������������������������������������������������������������������������������������94
Arrays������������������������������������������������������������������������������������������������������������������96
Array Shorthand��������������������������������������������������������������������������������������������97
Accessing Elements of an Array��������������������������������������������������������������������97
Iterating over Arrays��������������������������������������������������������������������������������������99
Adding and Removing Elements of an Array�����������������������������������������������101
Searching Arrays�����������������������������������������������������������������������������������������103
Sorting Arrays����������������������������������������������������������������������������������������������104
Binary Data�������������������������������������������������������������������������������������������������������106
ArrayBuffer���������������������������������������������������������������������������������������������106
Typed Arrays������������������������������������������������������������������������������������������������107
Data Views���������������������������������������������������������������������������������������������������114
Memory Management���������������������������������������������������������������������������������������118
The Date Class�������������������������������������������������������������������������������������������������121
Event-Driven Programming�������������������������������������������������������������������������������125
Conclusion��������������������������������������������������������������������������������������������������������126

v
Table of Contents

Chapter 3: Networking����������������������������������������������������������������������127
About Networking���������������������������������������������������������������������������������������������128
Connecting to Wi-Fi�������������������������������������������������������������������������������������������129
Connecting from the Command Line�����������������������������������������������������������130
Connecting with Code���������������������������������������������������������������������������������131
Connecting to Any Open Access Point���������������������������������������������������������134
Installing the Network Host�������������������������������������������������������������������������������137
Installing Examples�������������������������������������������������������������������������������������������137
Getting Network Information�����������������������������������������������������������������������������137
Making HTTP Requests�������������������������������������������������������������������������������������138
Fundamentals����������������������������������������������������������������������������������������������138
GET��������������������������������������������������������������������������������������������������������������140
Streaming GET���������������������������������������������������������������������������������������������141
GET JSON����������������������������������������������������������������������������������������������������143
Subclassing an HTTP Request���������������������������������������������������������������������145
Setting Request Headers�����������������������������������������������������������������������������147
Getting Response Headers��������������������������������������������������������������������������148
POST������������������������������������������������������������������������������������������������������������149
Handling Errors��������������������������������������������������������������������������������������������150
Securing Connections with TLS������������������������������������������������������������������������151
Using TLS with the SecureSocket Class���������������������������������������������������152
Public Certificates���������������������������������������������������������������������������������������152
Private Certificates��������������������������������������������������������������������������������������154
Creating an HTTP Server�����������������������������������������������������������������������������������155
Fundamentals����������������������������������������������������������������������������������������������155
Responding to a Request�����������������������������������������������������������������������������157
Responding to JSON PUT�����������������������������������������������������������������������������158

vi
Table of Contents

Receiving a Streaming Request������������������������������������������������������������������160


Sending a Streaming Response������������������������������������������������������������������161
mDNS����������������������������������������������������������������������������������������������������������������163
Claiming a Name�����������������������������������������������������������������������������������������164
Finding a Service�����������������������������������������������������������������������������������������165
Advertising a Service�����������������������������������������������������������������������������������167
WebSocket��������������������������������������������������������������������������������������������������������168
Connecting to a WebSocket Server�������������������������������������������������������������169
Creating a WebSocket Server����������������������������������������������������������������������171
MQTT�����������������������������������������������������������������������������������������������������������������173
Connecting to an MQTT Server��������������������������������������������������������������������173
Subscribing to a Topic���������������������������������������������������������������������������������175
Publishing to a Topic������������������������������������������������������������������������������������176
SNTP�����������������������������������������������������������������������������������������������������������������177
Advanced Topics�����������������������������������������������������������������������������������������������178
Creating a Wi-Fi Access Point����������������������������������������������������������������������178
Promises and Asynchronous Functions�������������������������������������������������������181
Conclusion��������������������������������������������������������������������������������������������������������183

Chapter 4: Bluetooth Low Energy (BLE)��������������������������������������������185


BLE Basics��������������������������������������������������������������������������������������������������������186
GAP Centrals and Peripherals����������������������������������������������������������������������186
GATT Clients and Servers����������������������������������������������������������������������������187
GAP vs. GATT�����������������������������������������������������������������������������������������������187
Profiles, Services, and Characteristics��������������������������������������������������������188
The BLE API of the Moddable SDK��������������������������������������������������������������������189
The BLEClient Class���������������������������������������������������������������������������������190
The BLEServer Class���������������������������������������������������������������������������������191

vii
Table of Contents

Installing the BLE Host��������������������������������������������������������������������������������������191


Creating a BLE Scanner������������������������������������������������������������������������������������192
Creating Two-Way Communication�������������������������������������������������������������������193
Connecting to the Peripheral�����������������������������������������������������������������������195
Receiving Notifications��������������������������������������������������������������������������������198
Creating a Heart Rate Monitor��������������������������������������������������������������������������200
Defining and Deploying Services�����������������������������������������������������������������200
Advertising��������������������������������������������������������������������������������������������������203
Establishing a Connection���������������������������������������������������������������������������204
Sending Notifications����������������������������������������������������������������������������������206
Responding to Read Requests���������������������������������������������������������������������211
Establishing Secure Communication����������������������������������������������������������������215
Secure Heart Rate Monitor��������������������������������������������������������������������������215
Conclusion��������������������������������������������������������������������������������������������������������220

Chapter 5: Files and Data�����������������������������������������������������������������221


Installing the Files and Data Host���������������������������������������������������������������������222
Files������������������������������������������������������������������������������������������������������������������222
File Classes�������������������������������������������������������������������������������������������������223
File Paths�����������������������������������������������������������������������������������������������������223
File Operations��������������������������������������������������������������������������������������������224
Writing to a File�������������������������������������������������������������������������������������������226
Reading from a File�������������������������������������������������������������������������������������229
Directories���������������������������������������������������������������������������������������������������231
Getting File System Information������������������������������������������������������������������233
Preferences�������������������������������������������������������������������������������������������������������234
The Preference Class�������������������������������������������������������������������������������234
Preference Names���������������������������������������������������������������������������������������235

viii
Table of Contents

Preference Data�������������������������������������������������������������������������������������������235
Reading and Writing Preferences����������������������������������������������������������������236
Deleting Preferences�����������������������������������������������������������������������������������237
Don’t Use JSON�������������������������������������������������������������������������������������������237
Security�������������������������������������������������������������������������������������������������������239
Resources���������������������������������������������������������������������������������������������������������239
Adding Resources to a Project��������������������������������������������������������������������240
Accessing Resources����������������������������������������������������������������������������������241
Using Resources������������������������������������������������������������������������������������������241
Accessing Flash Memory Directly���������������������������������������������������������������������243
Flash Hardware Fundamentals��������������������������������������������������������������������244
Accessing Flash Partitions��������������������������������������������������������������������������246
Example: Frequently Updated Integer���������������������������������������������������������251
Conclusion��������������������������������������������������������������������������������������������������������254

Chapter 6: Hardware�������������������������������������������������������������������������255
Installing the Hardware Host�����������������������������������������������������������������������������256
Notes on Wiring�������������������������������������������������������������������������������������������������256
Following the Wiring Instructions����������������������������������������������������������������256
Troubleshooting Wiring Issues���������������������������������������������������������������������257
Blinking an LED�������������������������������������������������������������������������������������������������258
Reading a Button����������������������������������������������������������������������������������������������260
Other Digital Input Modes����������������������������������������������������������������������������262
Monitoring for Changes�������������������������������������������������������������������������������266
Controlling a Tri-color LED��������������������������������������������������������������������������������267
LED Setup����������������������������������������������������������������������������������������������������268
ESP32 Wiring Instructions���������������������������������������������������������������������������268
ESP8266 Wiring Instructions�����������������������������������������������������������������������269

ix
Table of Contents

Using Digital with a Tri-color LED������������������������������������������������������������270


Using PWM with a Tri-color LED��������������������������������������������������������������������271
Rotating a Servo�����������������������������������������������������������������������������������������������274
ESP32 Wiring Instructions���������������������������������������������������������������������������275
ESP8266 Wiring Instructions�����������������������������������������������������������������������275
Understanding the servo Code�������������������������������������������������������������������276
Getting the Temperature�����������������������������������������������������������������������������������277
TMP36���������������������������������������������������������������������������������������������������������278
TMP102�������������������������������������������������������������������������������������������������������282
Conclusion��������������������������������������������������������������������������������������������������������294

Chapter 7: Audio�������������������������������������������������������������������������������295
Speaker Options������������������������������������������������������������������������������������������������295
Adding the Analog Speaker�������������������������������������������������������������������������������297
ESP32 Wiring Instructions���������������������������������������������������������������������������298
ESP8266 Wiring Instructions�����������������������������������������������������������������������299
Adding an I2S Chip and Digital Speaker������������������������������������������������������������300
ESP32 Wiring Instructions���������������������������������������������������������������������������300
ESP8266 Wiring Instructions�����������������������������������������������������������������������302
Installing the Audio Host�����������������������������������������������������������������������������������303
The AudioOut Class�����������������������������������������������������������������������������������������304
AudioOut Configuration�����������������������������������������������������������������������������������304
Audio Hardware Protocols���������������������������������������������������������������������������304
Audio Data Formats�������������������������������������������������������������������������������������308
Audio Compression��������������������������������������������������������������������������������������310
Setting the Audio Queue Length������������������������������������������������������������������310
Playing Audio with AudioOut���������������������������������������������������������������������������311
Instantiating AudioOut�������������������������������������������������������������������������������311

x
Table of Contents

Playing a Single Sound��������������������������������������������������������������������������������312


Repeating a Sound��������������������������������������������������������������������������������������313
Using Callbacks to Synchronize Audio���������������������������������������������������������313
Using Commands to Change Volume�����������������������������������������������������������314
Playing a Sequence of Sounds��������������������������������������������������������������������314
Playing Sounds Simultaneously������������������������������������������������������������������315
Playing Part of a Sound�������������������������������������������������������������������������������316
Flushing the Audio Queue����������������������������������������������������������������������������317
Conclusion��������������������������������������������������������������������������������������������������������317

Chapter 8: Graphics Fundamentals��������������������������������������������������319


Why Add a Display?�������������������������������������������������������������������������������������������320
Overcoming Hardware Limitations��������������������������������������������������������������������322
Pixel Rate Impacts Frame Rate�������������������������������������������������������������������323
Drawing Frames������������������������������������������������������������������������������������������324
Scanline Rendering�������������������������������������������������������������������������������������326
Restricting the Drawing Area�����������������������������������������������������������������������327
Pixels����������������������������������������������������������������������������������������������������������������331
Pixel Formats�����������������������������������������������������������������������������������������������332
Configuring a Host for a Pixel Format����������������������������������������������������������333
Freedom to Choose a Display����������������������������������������������������������������������335
Graphics Assets������������������������������������������������������������������������������������������������335
Masks����������������������������������������������������������������������������������������������������������336
Fonts������������������������������������������������������������������������������������������������������������341
Color Images������������������������������������������������������������������������������������������������345
Display Rotation������������������������������������������������������������������������������������������������349
Rotating in Software������������������������������������������������������������������������������������350
Rotating in Hardware�����������������������������������������������������������������������������������351

xi
Table of Contents

Poco or Piu?������������������������������������������������������������������������������������������������������352
Conclusion��������������������������������������������������������������������������������������������������������355

Chapter 9: Drawing Graphics with Poco�������������������������������������������357


Installing the Poco Host������������������������������������������������������������������������������������357
Preparing to Draw���������������������������������������������������������������������������������������������358
Drawing Rectangles������������������������������������������������������������������������������������������361
Filling the Screen�����������������������������������������������������������������������������������������361
Updating Part of the Screen������������������������������������������������������������������������363
Drawing Random Rectangles����������������������������������������������������������������������364
Drawing Blended Rectangles����������������������������������������������������������������������366
Drawing Bitmaps����������������������������������������������������������������������������������������������370
Drawing Masks��������������������������������������������������������������������������������������������370
Drawing Color Images���������������������������������������������������������������������������������377
Drawing JPEG Images���������������������������������������������������������������������������������378
Filling with Color Images�����������������������������������������������������������������������������381
Drawing Masked Color Images��������������������������������������������������������������������383
Drawing Text�����������������������������������������������������������������������������������������������������387
Drawing a Text Shadow�������������������������������������������������������������������������������388
Measuring Text��������������������������������������������������������������������������������������������389
Truncating Text��������������������������������������������������������������������������������������������390
Wrapping Text����������������������������������������������������������������������������������������������391
Additional Drawing Techniques�������������������������������������������������������������������������393
Restricting Text to a Box������������������������������������������������������������������������������393
Easily Reusing Drawing Code����������������������������������������������������������������������396
Efficiently Rendering Gradients�������������������������������������������������������������������398
Touch Input�������������������������������������������������������������������������������������������������������402
Accessing the Touch Driver�������������������������������������������������������������������������402
Reading Touch Input������������������������������������������������������������������������������������402

xii
Table of Contents

Using Multi-touch����������������������������������������������������������������������������������������404
Applying Rotation����������������������������������������������������������������������������������������404
Conclusion��������������������������������������������������������������������������������������������������������405

Chapter 10: Building User Interfaces with Piu���������������������������������407


Key Concepts����������������������������������������������������������������������������������������������������408
Everything Is an Object��������������������������������������������������������������������������������408
Every User Interface Element Is a Content Object���������������������������������������410
Not All Piu Objects Are Content Objects�������������������������������������������������������411
Installing the Piu Host���������������������������������������������������������������������������������������413
“Hello, World” with Piu��������������������������������������������������������������������������������������414
Fonts������������������������������������������������������������������������������������������������������������416
Adding Color������������������������������������������������������������������������������������������������423
Responding to Events with Behaviors���������������������������������������������������������428
Adding Images��������������������������������������������������������������������������������������������������435
Drawing Part of an Image����������������������������������������������������������������������������436
Drawing Multiple Icons from One Image�����������������������������������������������������438
Using Masks������������������������������������������������������������������������������������������������440
Tiling Images�����������������������������������������������������������������������������������������������442
Building Compound User Interface Elements���������������������������������������������������448
Creating a Header����������������������������������������������������������������������������������������449
Building Responsive Layouts����������������������������������������������������������������������������454
Row and Column Layouts����������������������������������������������������������������������������456
Scrolling Content�����������������������������������������������������������������������������������������460
Templates for Content Objects��������������������������������������������������������������������������463
Creating a Button Template Class����������������������������������������������������������������463
Content Constructor Arguments������������������������������������������������������������������466

xiii
Table of Contents

Accessing Content Objects in a Container��������������������������������������������������������471


Using first, last, next, and previous��������������������������������������������������471
Accessing Children by Index and Name������������������������������������������������������472
Accessing Content with Anchors�����������������������������������������������������������������472
Defining and Triggering Your Own Events���������������������������������������������������������476
Triggering Events on a Content Object��������������������������������������������������������477
Distributing Events Inside a Container��������������������������������������������������������480
Bubbling Events Up the Containment Hierarchy������������������������������������������484
Animation����������������������������������������������������������������������������������������������������������488
Easing Equations�����������������������������������������������������������������������������������������488
Animating Content Objects��������������������������������������������������������������������������489
Animating Transitions����������������������������������������������������������������������������������494
Drawing a Graph in Real Time���������������������������������������������������������������������������497
Adding an Onscreen Keyboard��������������������������������������������������������������������������500
Organizing User Interface Code Using Modules������������������������������������������������506
The Modules������������������������������������������������������������������������������������������������507
The Application Logic����������������������������������������������������������������������������������508
The Splash Screen���������������������������������������������������������������������������������������511
The Home Screen����������������������������������������������������������������������������������������513
Adding More Screens����������������������������������������������������������������������������������517
Conclusion��������������������������������������������������������������������������������������������������������518

Chapter 11: Adding Native Code�������������������������������������������������������519


Installing the Host���������������������������������������������������������������������������������������������520
Generating Random Integers����������������������������������������������������������������������������521
Creating a Native Function��������������������������������������������������������������������������521
Implementing a Native Function������������������������������������������������������������������522
Using the Hardware Random Number Generator����������������������������������������523

xiv
Table of Contents

Restricting Random Numbers to a Range���������������������������������������������������526


Comparing Random Number Approaches���������������������������������������������������528
The BitArray Class�����������������������������������������������������������������������������������������529
Using Memory Allocated by ArrayBuffer�������������������������������������������������530
Using Memory Allocated by calloc�����������������������������������������������������������533
Wi-Fi Signal Notifications����������������������������������������������������������������������������������542
The Test Code����������������������������������������������������������������������������������������������542
The WiFiRSSINotify Class�����������������������������������������������������������������������544
The Native RSSINotifyRecord Structure�������������������������������������������������544
The Constructor�������������������������������������������������������������������������������������������545
The Destructor���������������������������������������������������������������������������������������������550
The close Function������������������������������������������������������������������������������������550
The Callback������������������������������������������������������������������������������������������������551
Additional Techniques���������������������������������������������������������������������������������������554
Debugging Native Code�������������������������������������������������������������������������������554
Accessing Global Variables��������������������������������������������������������������������������555
Getting a Function’s Return Value���������������������������������������������������������������556
Getting Values����������������������������������������������������������������������������������������������556
Setting Values����������������������������������������������������������������������������������������������557
Determining a Value’s Type�������������������������������������������������������������������������559
Working with Strings�����������������������������������������������������������������������������������560
Ensuring Your Buffer Pointers Are Valid�������������������������������������������������������561
Integrating with C++�����������������������������������������������������������������������������������562
Using Threads����������������������������������������������������������������������������������������������562
Conclusion��������������������������������������������������������������������������������������������������������563

Glossary��������������������������������������������������������������������������������������������565

Index�������������������������������������������������������������������������������������������������583

xv
About the Authors
Peter Hoddie is an engineer and entrepreneur focused on client software.
He is recognized for crafting compact and efficient code that pushes the
boundaries of user experience on consumer hardware. The software he and
his teams have built has powered mass-market consumer products from
companies including Apple, Palm, Sling, HP, Sony, and Whirlpool. Peter
recognizes that the first users of any product are the developers creating
it, and that those developers cannot build compelling consumer products
on a foundation that’s unstable, complex, or confusing. He therefore
champions investments in great tools and a simple runtime architecture.
Peter has founded several companies, including Kinoma, which merged
into Marvell Semiconductor. He led QuickTime development at Apple
during the 1990s as a Distinguished Engineer. He contributed to the
development of the QuickTime file format and its adoption by ISO into the
MPEG-4 standard. He is currently a member of the JavaScript language
standards committee (ECMA TC39) and chair of ECMA TC53 for “Smart
wearable systems and sensor-based devices.” Peter is particularly proud
of his work putting both the KinomaJS framework and Darwin Streaming
Server into open source. He continues to come to terms with the ten
patents that bear his name.

Lizzie Prader is a software engineer at Moddable in the San Francisco


Bay Area. She is an IoT skeptic working in the IoT space, hoping to make
consumer IoT products and other embedded systems more open and
customizable for the end user. She specializes in developing touch screen
user interfaces for embedded systems and creating developer resources.

xvii
About the Authors

Before Moddable, Lizzie worked as a developer relations engineer for the


Kinoma team at Marvell Semiconductor, helping customers get the most
out of Kinoma’s JavaScript-powered prototyping products. She earned
her bachelor’s degree in Computer Science from UC Berkeley. When
not sitting behind a computer, she enjoys being outdoors (in particular
running, hiking, and swimming), reading, and playing the piano.

xviii
About the Technical Reviewers
Mark Wharton was born in England, was raised in Papua New Guinea
and Australia, and worked as a software engineer for startups and large
corporations in Australia, Japan, and the United States. He currently
works at Amazon on the Alexa Automotive initiative. Since his early days
programming the 6502 assembly language on Apple IIe and Commodore
64 computers, Mark excels at making the most of limited resources in
constrained environments. Now in his spare time, Mark enjoys applying
those skills to a new generation of low-cost, low-power devices using the
Moddable SDK.

Masahiro Shioji is a product creator who likes to bring technologies into


easy-to-use products and release them to the world. He started in product
development in the digital camera industry, at Sanyo Electric in Japan,
and produced a QuickTime/MPEG-4 direct encoding video camera in
collaboration with Peter Hoddie when Peter worked at Apple. Masahiro
went on to spread the joy of creating something to university students,
including operating a lab toward that end while continuing his own work
in product development and new business development.

xix
About the Editor
Caroline Rose is a freelance technical writer and editor based in
Palo Alto, California. With a career that has included 7 years working
as a programmer, her focus has been on producing highly technical
documentation, most notably as lead writer and editor of the original
Inside Macintosh. Caroline was also Manager of Publications at NeXT and
the editor of Apple’s quarterly technical journal, develop. Her subsequent
freelance work began with coauthoring updated versions of Adobe’s
PostScript and PDF reference manuals and went on to include clients such
as AMD, Apple, Apress, Kinoma, Logitech, Nokia, and Sony. In her free
time, Caroline enjoys playing guitar, singing, swimming, hiking, traveling,
and working on her memoir.

xxi
Acknowledgments
This book is better because of the generous assistance of many talented
individuals we’re fortunate to call friends.

• Caroline Rose, editor – Caroline brought her


legendary precision and clarity to this book. Everything
about this book is better thanks to her patient work.

• Mark Wharton, technical reviewer – Mark carefully


reviewed the entire text, and then ran and reviewed
every single example.

• Masahiro Shioji, technical reviewer, Chapter 2 –


Shioji-san brought the perspective of an embedded
C developer to his thoughtful review.

• Brian Friedkin, BLE advisor – Creator of the BLE


implementation in the Moddable SDK, Brian made
sure the explanations and examples in Chapter 4 are
just right.

• Patrick Soquet, advisor – As the inventor of the XS


JavaScript engine, Patrick is the starting point for
everything we know about embedded JavaScript.

• Chris Krueger, illustrator – Chris turned our rough


ideas and rougher sketches into the simple, clear
images you see throughout the book.

• Team Moddable – Our colleagues at Moddable have


been incredibly supportive and patient over the many
months it took to create this book.

xxiii
Foreword
Those of you who have read Wikipedia cover to cover will remember the
definition of hybrid vigor. For the rest of you:

Heterosis, hybrid vigor, or outbreeding enhancement is the


improved or increased function of any biological quality in a hybrid
offspring. An offspring is heterotic if its traits are enhanced as a
result of mixing the genetic contributions of its parents.

— Wikipedia, page 69105

The practical upshot of this is that if you take separate, inbred strains
of, say, corn and breed them together, you get a great big vigorous plant,
hence the name hybrid vigor.
The Moddable SDK, as described in this book, represents the hybrid
vigor between embedded and JavaScript development. Using Moddable is
a short path to very large amounts of corn.
If you’re an embedded developer, you delight in the ability to get
close to the metal, to program on tiny, inexpensive devices without the
affordances offered by development on large systems. Writing in C/C++
and/or assembly language gives you a great deal of control, but you often
struggle with shoehorning functionality into these small devices, wrestle
brittle development and debugging environments, and build ad hoc
device-specific ways of updating code and managing resources. If the
embedded device has a display or is capable of wireless communications,
you need to track down the right tools to build, simulate, and test a wide
variety of functionality in the absence of a rich underlying OS. A great deal
of your energy goes into managing the constraints of these small systems
rather than into the applications themselves.

xxv
Foreword

If you’re a JavaScript developer, you delight in its productivity,


versatility, and ubiquity. The language is forgiving to a novice yet extremely
powerful in the hands of a master. It’s versatile enough to be used in front-­
end development as well as back-end infrastructure. Its huge community
continually enriches the language and libraries and makes it arguably the
most popular language ever. All this versatility and power comes with a
price; until now a robust version of JavaScript has not scaled down to the
point where it will fit on a small embedded device.
Moddable takes the best of these two strains and blends them together
on an emerging class of powerful new microcontrollers. Embedded
developers no longer have to regard JavaScript with envious eyes. They
now have access to a versatile high-level language that still allows them to
stay close to the metal and maintain tight control. JavaScript developers
can reach ridiculously inexpensive devices with none of the friction of
traditional embedded development, yet still work with affordances present
on much larger systems.
It’s embarrassingly easy to be productive in the Moddable
environment, with its rich SDK for managing secure web connectivity,
Wi-Fi, Bluetooth, sound, graphics, user interfaces, and more; its elegant,
full-featured debugging; and a wide variety of target hardware that ranges
from inexpensive to nearly free.
My day job is investing in technology startups, and as such it pains me
to see companies attempting embedded development with blunt tools.
Moddable can save developers time and money and produce beautifully
polished embedded applications. As an investor, I love tools that reduce
risk and make companies more capital-efficient. As an avid maker, I love
tools that make making even more fun.
If you develop embedded products, or if you’re a hobbyist or even just
someone who loves writing code, Moddable’s hybrid vigor changes the
game. Go grow some corn.

— Peter Barrett

xxvi
Introduction
This book is a hands-on guide to writing the software for IoT products.
Each chapter is filled with compact, focused examples for you to learn
from, study, run, and modify. When you finish this book, you’ll know the
fundamentals of building sophisticated IoT products on low-cost hardware
using modern JavaScript.
IoT products differ from traditional products in two ways: they have
the ability to run software and they have the ability to communicate. Their
communication is often over the internet, but it may be more local—for
example, between products on your home Wi-Fi network or with your
phone over a Bluetooth connection.
IoT products are often created by adding a microcontroller with Wi-Fi
or Bluetooth capabilities to a traditional product. The cost of adding a
microcontroller with communication capabilities is about one dollar today
and continues to fall. At that price, nearly every product is going to be an
IoT product—not just televisions and thermostats but also light bulbs,
light switches, electric wall plugs, door locks, window shades, garage door
openers, ceiling fans, rice cookers, refrigerators, and more.
The code in this book runs on the ESP32 and ESP8266 microcontrollers
from Espressif, which offer remarkable power at an unprecedented cost.
Unsurprisingly, they’re widely deployed in IoT products and extremely
popular with makers and hobbyists. What you’ll learn in this book isn’t
limited to these microcontrollers, however; it can be applied to a growing
number of microcontrollers from manufacturers including Nordic,
Qualcomm, and Silicon Labs.
Adding IoT hardware to a traditional product is the easy part; the hard
part is the software. Software defines the product’s features and behavior.

xxvii
Introduction

It determines whether the product is reliable and easy to use and whether
it’s secure from external attacks and respects the privacy of users. Software
decides what other products the product can communicate with, its energy
use, the ease of adding new features over time, and much more.
Software is fundamental to IoT products, yet most of the industry
continues to write the software for them using the same tools and
techniques embedded software developers have used for decades. While
the hardware has advanced by orders of magnitude, the software has not.
That’s a problem, because much more is expected of the software in an IoT
product today than the software in a digital thermostat from 1999.

JavaScript: A New Tool


This book introduces a new way of building the software for IoT
products—a way that doesn’t try to reinvent the wheel by starting over. It
adds one new tool to the many that embedded software developers have
used for years: the JavaScript programming language. It may sound like a
stretch to suggest that a programming language can transform the software
of an IoT product, but it can. A modern high-level language is the perfect
antidote to decades-old, low-level development methods.
JavaScript may seem an unlikely starting point for future generations
of IoT products. After all, JavaScript began as a simple programming
language to add a little interactivity to web pages at the dawn of the web.
But as the web has evolved, JavaScript has evolved with it; it’s now a
formally defined programming language standardized by an international
committee with representatives from major companies, including Apple,
Facebook, Google, Microsoft, Mozilla, and PayPal. The language has been
made secure by two decades of attacks in the web browser. It’s been made
powerful by the demands of increasingly sophisticated web pages. And it’s
been made reliable and easy to use to meet the needs of millions of web
developers around the world.

xxviii
Introduction

Developers working in JavaScript are incredibly productive and


nimble. Within hours of a natural disaster, new websites appear with
impressive features implemented in JavaScript. Major websites like
Facebook and LinkedIn aren’t just built in JavaScript but deploy new
features daily using JavaScript. Server-side JavaScript with Node.js now
powers entire businesses, and many mobile apps are built in JavaScript.
JavaScript is ready for IoT developers to use. This book gets IoT
developers ready to use JavaScript.

Recent Technical Advances


JavaScript wasn’t always a good fit for IoT. While the JavaScript engines
built into web browsers are breathtakingly fast, that speed comes at a
cost. Those engines are far too big to store in a low-cost microcontroller,
and they require orders of magnitude more memory than is built into
the hardware. The XS JavaScript engine is different: created by Kinoma
and maintained by Moddable, it’s optimized for the constraints of the
microcontrollers that power low-cost IoT products. XS is very small and
still plenty fast.
To keep the engine small, you might expect XS to support only a
subset of the JavaScript programming language, but that’s not the case.
XS implements over 99% of the 2020 version of the JavaScript language
specification; that’s more than any web browser. As an optimization, XS
allows you to omit many features of the language to make the engine even
smaller—but that’s your choice. All the features are there if you want to use
them.
Having a small, efficient, and compatible JavaScript engine isn’t
enough. The JavaScript language only performs computations; it needs a
runtime to interact with the outside world. For a web page, the runtime is
the web browser; for a web server, the runtime is Node.js. For IoT products,
this book uses the Moddable SDK as the runtime.

xxix
Introduction

The Moddable SDK includes a large collection of efficient modules


for common tasks like communicating over the internet, controlling IoT
hardware, managing security, and storing data. The Moddable SDK also
has something unusual for an IoT runtime: deep support for high-quality,
rich user interfaces on low-cost touch screens. While you may not yet be
considering a screen for your IoT product, your future customers probably
wish you would, because a screen makes your product easier to set up and
use and enables it to provide more features.

F or Embedded Programmers and Web


Developers
There are no veteran IoT software developers, because the field is too
new. We’re all still learning. Most IoT developers come from one of two
backgrounds: there are developers building software for embedded
systems, who are now being called on to create IoT products with
connectivity, complex behaviors, and countless features; and there are
developers working on the web, who are being called on to build IoT
products on hardware that comes with resource and performance limits
that are unimaginable on the web.
JavaScript is at the intersection of developers coming from the
embedded and web software worlds. The JavaScript language itself
embodies this intersection, arriving from the web with a syntax that
looks a lot like the C and C++ languages long favored by embedded
developers. JavaScript and C/C++ code can call each other, making it
natural to combine both in a product. JavaScript has long been used for
communication on the web, even giving rise to the JSON data interchange
format commonly by IoT products to communicate.
This book is for developers with a background in either embedded
software or web development. For experienced embedded developers
unfamiliar with JavaScript, an early chapter introduces C and C++

xxx
Introduction

programmers to JavaScript. For experienced web developers getting


started in embedded systems, the book provides tips on memory and
performance optimization unique to IoT product development.

Organization of This Book


Here’s how this book is organized:

• Chapter 1 takes you through gathering all the hardware


and software required for this book and running your
first JavaScript application on a microcontroller. Along
the way, it shows how to use the helpful features of
xsbug, the JavaScript source-level debugger.

• Chapter 2 is a fast-paced, practical introduction to


JavaScript for developers who are already familiar with
C or C++. The JavaScript language introduced here is
the same language that’s used on the web, but since
this book focuses on embedded systems, the chapter
addresses some aspects of JavaScript that are seldom
used by web developers.

• Chapter 3 is all about your IoT device’s connection


to the network, including different ways to connect,
how to communicate using various network protocols,
how to make secure connections, and the advanced
topics of how to turn your device into a private Wi-Fi
base station and how to use JavaScript promises with
networking APIs.

• Chapter 4 focuses on Bluetooth Low Energy (BLE),


a wireless communication widely used between two
devices in close proximity to each other. Products
choose to use BLE instead of Wi-Fi if minimizing

xxxi
Introduction

energy use is particularly important and when direct


communication with another device, such as a mobile
phone, is an acceptable alternative to internet access.

• Chapter 5 explains how to work with stored data on


embedded systems, given their code size limitations,
constrained RAM, and performance constraints. It
explains the three primary ways to store data—files,
preferences, and resources—and introduces direct
access to flash memory, an advanced technique that
offers the greatest flexibility.

• Chapter 6 gets you started on writing your own


JavaScript code to interact with hardware. It includes
examples that require just a few widely available,
inexpensive sensors and actuators and shows you how
to communicate with them directly using different
hardware protocols.

• Chapter 7 explains how to play sounds using an


inexpensive speaker that’s easy to attach directly
to an ESP32 or ESP8266. You’ll also learn how you
can achieve higher-quality audio playback using an
external I2S audio driver and how to choose the optimal
audio format for your project.

• Chapter 8 covers first the benefits and cost-­


effectiveness of adding a display to your IoT
product and then the fundamentals of graphics
on microcontrollers, including background on
optimizations and constraints, information about how
to add graphics assets to projects, and an introduction
to various drawing methods. The next two chapters
provide more details.

xxxii
Another Random Document on
Scribd Without Any Related Topics
There is one strange bird song that is half song and half dance that
perhaps most of you may never be able to hear and see; but as it is
worth going miles to hear, and nights of watching to witness, I am
going to set it here as one of your outdoor tasks or feats: you must
hear the mating song of the woodcock. I have described the song
and the dance in “Roof and Meadow,” in the chapter called “One
Flew East and One Flew West.” Mr. Bradford Torrey has an account
of it in his “Clerk of the Woods,” in the chapter named “Woodcock
Vespers.” To hear the song is a rare experience for the habitual
watcher in the woods, but one that you might have the first April
evening that you are abroad.
Go down to your nearest meadow—a meadow near a swampy piece
of woods is best—and here, along the bank of the meadow stream,
wait in the chilly twilight for the speank, speank, or the peent,
peent, from the grass—the signal that the song is about to begin.

VI
One of the dreadful—positively dreadful—sounds of the late spring
that I hear day in and day out is the gobbling, strangling, ghastly
cries of young crows feeding. You will surely think something is
being murdered. The crying of a hungry baby is musical in
comparison. But it is a good sound to hear, for it reminds one of the
babes in the woods—that a new generation of birds is being brought
through from babyhood to gladden the world. It is a tender sound!
The year is still young.

VII
You should hear the hum of the honey-bees on a fresh May day in
an apple tree that is just coming into perfect bloom. The enchanting
loveless of the pink and white world of blossoms is enough to make
one forget to listen to the hum-hum-hum-humming-ing-ing-ing-ing
of the excited bees. But hear their myriad wings, fanning the
perfume into the air and filling the sunshine with the music of work.
The whir, the hum of labor—of a busy factory, of a great steamship
dock—is always music to those who know the blessedness of work;
but it takes that knowledge, and a good deal of imagination besides,
to hear the music in it. Not so with the bees. The season, the day,
the colors, and perfumes—they are the song; the wings are only the
million-stringed æolian upon which the song is played.

VIII
You should hear the grass grow. What! I repeat, you should hear the
grass grow. I have a friend, a sound and sensible man, but a lover of
the out-of-doors, who says he can hear it grow. But perhaps it is the
soft stir of the working earthworms that he hears. Try it. Go out
alone one of these April nights; select a green pasture with a slope
to the south, at least a mile from any house, or railroad; lay your ear
flat upon the grass, listen without a move for ten minutes. You hear
something—or do you feel it? Is it the reaching up of the grass? is it
the stir of the earthworms? is it the pulse of the throbbing universe?
or is it your own throbbing pulse? It is all of these, I think; call it the
heart of the grass beating in every tiny living blade, if you wish to.
You should listen to hear the grass grow.

IX
The fires have gone out on the open hearth. Listen early in the
morning and toward evening for the rumbling, the small, muffled
thunder, of the chimney swallows, as they come down from the open
sky on their wonderful wings. Don’t be frightened. It isn’t Santa
Claus this time of year; nor is it the Old Nick! The smothered
thunder is caused by the rapid beating of the swallows’ wings on the
air in the narrow chimney-flue, as the birds settle down from the top
of the chimney and hover over their nests. Stick your head into the
fireplace and look up! Don’t smoke the precious lodgers out, no
matter how much racket they make.
X
Hurry out while the last drops of your first May thunder-shower are
still falling and listen to the robins singing from the tops of the trees.
Their liquid songs are as fresh as the shower, as if the raindrops in
falling were running down from the trees in song—as indeed they
are in the overflowing trout-brook. Go out and listen, and write a
better poem than this one that I wrote the other afternoon when
listening to the birds in our first spring shower:—
The warm rain drops aslant the sun
And in the rain the robins sing;
Across the creek in twos and troops,
The hawking swifts and swallows wing.

The air is sweet with apple bloom,


And sweet the laid dust down the lane,
The meadow’s marge of calamus,
And sweet the robins in the rain.

O greening time of bloom and song!


O fragrant days of tender pain!
The wet, the warm, the sweet young days
With robins singing in the rain.
CHAPTER XI
TURTLE EGGS FOR AGASSIZ

I TOOK down, recently, from the shelves of a great public library,


the four volumes of Agassiz’s “Contributions to the Natural History
of the United States.” I doubt if anybody but the charwoman, with
her duster, had touched those volumes for twenty-five years. They
are a monumental work, the fruit of vast and heroic labors, with
colored plates on stone, showing the turtles of the United States,
and their life-history. The work was published more than half a
century ago, but it looked old beyond its years—massive, heavy,
weathered, as if dug from the rocks; and I soon turned with a sigh
from the weary learning of its plates and diagrams to look at the
preface.
Then, reading down through the catalogue of human names and of
thanks for help received, I came to a sentence beginning:—
“In New England I have myself collected largely; but I have also
received valuable contributions from the late Rev. Zadoc Thompson
of Burlington; ... from Mr. D. Henry Thoreau of Concord; ... and from
Mr. J. W. P. Jenks of Middleboro.” And then it hastens on with the
thanks in order to get to the turtles, as if turtles were the one and
only thing of real importance in all the world.
Turtles are important—interesting; so is the late Rev. Zadoc
Thompson of Burlington. Indeed any reverend gentleman who would
catch turtles for Agassiz must have been interesting. If Agassiz had
only put a chapter into his turtle book about him! and as for the Mr.
Jenks of Middleboro (at the end of the quotation) I know that he
was interesting; for years later, he was an old college professor of
mine. He told me some of the particulars of his turtle contributions,
particulars which Agassiz should have found a place for in his big
book. The preface says merely that this gentleman sent turtles to
Cambridge by the thousands—brief and scanty recognition. For that
is not the only thing this gentleman did. On one occasion he sent,
not turtles, but turtle eggs to Cambridge—brought them, I should
say; and all there is to show for it, so far as I could discover, is a
small drawing of a bit of one of the eggs!
Of course, Agassiz wanted to make that drawing, and had to have a
fresh turtle egg to draw it from. He had to have it, and he got it. A
great man, when he wants a certain turtle egg, at a certain time,
always gets it, for he gets some one else to get it for him. I am glad
he got it. But what makes me sad and impatient is that he did not
think it worth while to tell us about the getting of it.
It would seem, naturally, that there could be nothing unusual or
interesting about the getting of turtle eggs when you want them.
Nothing at all, if you should chance to want the eggs as you chance
to find them. So with anything else. But if you want turtle eggs
when you want them, and are bound to have them, then you must—
get Mr. Jenks, or somebody else to get them for you.
Agassiz wanted those turtle eggs when he wanted them—not a
minute over three hours from the minute they were laid. Yet even
that does not seem exacting, hardly more difficult than the getting
of hens’ eggs only three hours old. Just so, provided the professor
could have had his private turtle-coop in Harvard College Yard; and
provided he could have made his turtles lay. But turtles will not
respond, like hens, to meat-scraps and the warm mash. The
professor’s problem was not to get from a mud turtle’s nest in the
back yard to his work-table in the laboratory; but to get from the
laboratory in Cambridge to some pond when the turtles were laying,
and back to the laboratory within the limited time. And this might
have called for nice and discriminating work—as it did.
Agassiz had been engaged for a long time upon his “Contributions.”
He had brought the great work nearly to a finish. It was, indeed,
finished but for one small yet very important bit of observation: he
had carried the turtle egg through every stage of its development
with the single exception of one—the very earliest. That beginning
stage had brought the “Contributions” to a halt. To get eggs that
were fresh enough to show the incubation at this period had been
impossible.
There were several ways that Agassiz might have proceeded: he
might have got a leave of absence for the spring term, taken his
laboratory to some pond inhabited by turtles, and there camped until
he should catch the reptile digging out her nest. But there were
difficulties in all of that—as those who are college professors and
naturalists know. As this was quite out of the question, he did the
easiest thing—asked Mr. Jenks of Middleboro to get him the eggs.
Mr. Jenks got them. Agassiz knew all about his getting of them; and
I say the strange and irritating thing is, that Agassiz did not think it
worth while to tell us about it, at least in the preface to his
monumental work.
It was many years later that Mr. Jenks, then a gray-haired college
professor, told me how he got those eggs to Agassiz.
“I was principal of an academy, during my younger years,” he began,
“and was busy one day with my classes, when a large man suddenly
filled the doorway of the room, smiled to the four corners of the
room, and called out with a big, quick voice that he was Professor
Agassiz.
“Of course he was. I knew it, even before he had had time to shout
it to me across the room.
“Would I get him some turtle eggs? he called. Yes, I would. And
would I get them to Cambridge within three hours from the time
they were laid? Yes, I would. And I did. And it was worth the doing.
But I did it only once.
“When I promised Agassiz those eggs, I knew where I was going to
get them. I had got turtle eggs there before—at a particular patch of
sandy shore along a pond, a few miles distant from the academy.
“Three hours was the limit. From the railroad station to Boston was
thirty-five miles; from the pond to the station was perhaps three or
four miles; from Boston to Cambridge we called about three miles.
Forty miles in round numbers! We figured it all out before he
returned, and got the trip down to two hours,—record time:—driving
from the pond to the station; from the station by express train to
Boston; from Boston by cab to Cambridge. This left an easy hour for
accidents and delays.
“Cab and car and carriage we reckoned into our time-table; but what
we didn’t figure on was the turtle.” And he paused abruptly.
“Young man,” he went on, his shaggy brows and spectacles hardly
hiding the twinkle in the eyes that were bent severely upon me,
“young man, when you go after turtle eggs, take into account the
turtle. No! No! that’s bad advice. Youth never reckons on the turtle—
and youth seldom ought to. Only old age does that; and old age
would never have got those turtle eggs to Agassiz.
“It was in the early spring that Agassiz came to the academy, long
before there was any likelihood of the turtles’ laying. But I was eager
for the quest, and so fearful of failure that I started out to watch at
the pond, fully two weeks ahead of the time that the turtles might
be expected to lay. I remember the date clearly: it was May 14th.
“A little before dawn—along near three o’clock—I would drive over to
the pond, hitch my horse near by, settle myself quietly among some
thick cedars close to the sandy shore, and there I would wait, my
kettle of sand ready, my eye covering the whole sleeping pond. Here
among the cedars I would eat my breakfast, and then get back in
good season to open the academy for the morning session.
“And so the watch began.
“I soon came to know individually the dozen or more turtles that
kept to my side of the pond. Shortly after the cold mist would lift
and melt away, they would stick up their heads through the quiet
water; and as the sun slanted down over the ragged rim of tree-
tops, the slow things would float into the warm lighted spots, or
crawl out and doze comfortably on the hummocks and snags.
“What fragrant mornings those were! How fresh and new and
unbreathed! The pond odors, the woods odors, the odors of the
ploughed fields—of water-lily, and wild grape, and the dew-laid soil!
I can taste them yet, and hear them yet—the still, large sounds of
the waking day—the pickerel breaking the quiet with his swirl; the
kingfisher dropping anchor; the stir of feet and wings among the
trees. And then the thought of the great book being held up for me!
Those were rare mornings!
“But there began to be a good many of them, for the turtles showed
no desire to lay. They sprawled in the sun, and never one came out
upon the sand as if she intended to help on the great professor’s
book. The story of her eggs was of small concern to her; her
contribution to the Natural History of the United States could wait.
“And it did wait. I began my watch on the 14th of May; June 1st
found me still among the cedars, still waiting, as I had waited every
morning, Sundays and rainy days alike. June 1st was a perfect
morning, but every turtle slid out upon her log, as if egg-laying
might be a matter strictly of next year.
“I began to grow uneasy,—not impatient yet, for a naturalist learns
his lesson of patience early, and for all his years; but I began to fear
lest, by some subtile sense, my presence might somehow be known
to the creatures; that they might have gone to some other place to
lay, while I was away at the schoolroom.
“I watched on to the end of the first week, on to the end of the
second week in June, seeing the mists rise and vanish every
morning, and along with them vanish, more and more, the poetry of
my early morning vigil. Poetry and rheumatism cannot long dwell
together in the same clump of cedars, and I had begun to feel the
rheumatism. A month of morning mists wrapping me around had at
last soaked through to my bones. But Agassiz was waiting, and the
world was waiting, for those turtle eggs and I would wait. It was all
I could do, for there is no use bringing a china nest-egg to a turtle;
she is not open to any such delicate suggestion.
“Then came a mid-June Sunday morning, with dawn breaking a little
after three: a warm, wide-awake dawn, with the level mist lifted
from the level surface of the pond a full hour higher than I had seen
it any morning before.
“This was the day. I knew it. I have heard persons say that they can
hear the grass grow; that they know by some extra sense when
danger is nigh. For a month I had been watching, had been
brooding over this pond, and now I knew. I felt a stirring of the
pulse of things that the cold-hearted turtles could no more escape
than could the clods and I.
“Leaving my horse unhitched, as if he, too, understood, I slipped
eagerly into my covert for a look at the pond. As I did so, a large
pickerel ploughed a furrow out through the spatter-docks, and in his
wake rose the head of a large painted turtle. Swinging slowly round,
the creature headed straight for the shore, and, without a pause,
scrambled out on the sand.
“She was nothing unusual for a turtle, but her manner was unusual
and the gait at which she moved; for there was method in it and
fixed purpose. On she came, shuffling over the sand toward the
higher open fields, with a hurried, determined see-saw that was
taking her somewhere in particular, and that was bound to get her
there on time.
“I held my breath. Had she been a dinosaurian making Mesozoic
footprints, I could not have been more fearful. For footprints in the
Mesozoic mud, or in the sands of time, were as nothing to me when
compared with fresh turtle eggs in the sands of this pond.
“But over the strip of sand, without a stop, she paddled, and up a
narrow cow-path into the high grass along a fence. Then up the
narrow cow-path, on all fours, just like another turtle, I paddled, and
into the high wet grass along the fence.
“I kept well within sound of her, for she moved recklessly, leaving a
wide trail of flattened grass behind. I wanted to stand up,—and I
don’t believe I could have turned her back with a rail,—but I was
afraid if she saw me that she might return indefinitely to the pond;
so on I went, flat to the ground, squeezing through the lower rails of
the fence, as if the field beyond were a melon-patch. It was nothing
of the kind, only a wild, uncomfortable pasture, full of dewberry
vines, and very discouraging. They were excessively wet vines and
briery. I pulled my coat-sleeves as far over my fists as I could get
them, and with the tin pail of sand swinging from between my teeth
to avoid noise, I stumped fiercely, but silently, on after the turtle.
“TAIL FIRST, BEGAN TO BURY HERSELF”

“She was laying her course, I thought, straight down the length of
this dreadful pasture, when, not far from the fence, she suddenly
hove to, warped herself short about, and came back, barely clearing
me. I warped about, too, and in her wake bore down across the
corner of the pasture, across the powdery public road, and on to a
fence along a field of young corn.
“I was somewhat wet by this time, but not so wet as I had been
before wallowing through the deep, dry dust of the road. Hurrying
up behind a large tree by the fence, I peered down the corn-rows
and saw the turtle stop, and begin to paw about in the loose, soft
soil. She was going to lay!
“I held on to the tree and watched, as she tried this place, and that
place, and the other place. But the place, evidently, was hard to find.
What could a female turtle do with a whole field of possible nests to
choose from? Then at last she found it, and, whirling about, she
backed quickly at it and, tail first, began to bury herself before my
staring eyes.
“Those were not the supreme moments of my life; perhaps those
moments came later that day; but those certainly were among the
slowest, most dreadfully mixed of moments that I ever experienced.
They were hours long. There she was, her shell just showing, like
some old hulk in the sand alongshore. And how long would she stay
there? and how should I know if she had laid an egg?
“I could still wait. And so I waited, when, over the freshly awakened
fields, floated four mellow strokes from the distant town clock.
“Four o’clock! Why there was no train until seven! No train for three
hours! The eggs would spoil! Then with a rush it came over me that
this was Sunday morning, and there was no regular seven o’clock
train,—none till after nine.
“I think I should have fainted had not the turtle just then begun
crawling off. I was weak and dizzy; but there, there in the sand,
were the eggs! and Agassiz! and the great book! Why, I cleared the
fence—and the forty miles that lay between me and Cambridge—at
a single jump! He should have them, trains or no. Those eggs should
go to Agassiz by seven o’clock, if I had to gallop every mile of the
way. Forty miles! Any horse could cover it in three hours, if he had
to; and, upsetting the astonished turtle, I scooped out her long
white eggs.
“On a bed of sand in the bottom of the pail I laid them, with what
care my trembling fingers allowed; filled in between them with more
sand; so with layer after layer to the rim; and covering all smoothly
with more sand, I ran back for my horse.
“That horse knew, as well as I, that the turtles had laid, and that he
was to get those eggs to Agassiz. He turned out of that field into the
road on two wheels, a thing he had not done for twenty years,
doubling me up before the dashboard, the pail of eggs miraculously
lodged between my knees.
“I let him out. If only he could keep this pace all the way to
Cambridge!—or even halfway there, I would have time to finish the
trip on foot. I shouted him on, holding to the dasher with one hand,
holding the pail of eggs with the other, not daring to get off my
knees, though the bang on them, as we pounded down the wood-
road, was terrific. But nothing must happen to the eggs; they must
not be jarred, or even turned over in the sand before they came to
Agassiz.
“In order to get out on the pike it was necessary to drive back away
from Boston toward the town. We had nearly covered the distance,
and were rounding a turn from the woods into the open fields,
when, ahead of me, at the station it seemed, I heard the quick,
sharp whistle of a locomotive.
“What did it mean? Then followed the puff, puff, puff, of a starting
train. But what train? Which way going? And jumping to my feet for
a longer view, I pulled into a side road that paralleled the track, and
headed hard for the station.
“We reeled along. The station was still out of sight, but from behind
the bushes that shut it from view, rose the smoke of a moving
engine. It was perhaps a mile away, but we were approaching, head
on, and, topping a little hill, I swept down upon a freight train, the
black smoke pouring from the stack, as the mighty creature pulled
itself together for its swift run down the rails.
“My horse was on the gallop, following the track, and going straight
toward the coming train. The sight of it almost maddened me—the
bare thought of it, on the road to Boston! On I went; on it came, a
half—a quarter of a mile between us, when suddenly my road shot
out along an unfenced field with only a level stretch of sod between
me and the engine.
“With a pull that lifted the horse from his feet, I swung him into the
field and sent him straight as an arrow for the track. That train
should carry me and my eggs to Boston!
“The engineer pulled the whistle. He saw me stand up in the rig,
saw my hat blow off, saw me wave my arms, saw the tin pail swing
in my teeth, and he jerked out a succession of sharp Halts! But it
was he who should halt, not I; and on we went, the horse with a
flounder landing the carriage on top of the track.
“The train was already grinding to a stop; but before it was near a
standstill, I had backed off the track, jumped out, and, running
down the rails with the astonished engineers gaping at me, had
swung aboard the cab.
“They offered no resistance; they hadn’t had time. Nor did they have
the disposition, for I looked strange, not to say dangerous. Hatless,
dew-soaked, smeared with yellow mud, and holding, as if it were a
baby or a bomb, a little tin pail of sand!
“‘Crazy,’ the fireman muttered, looking to the engineer for his cue.
“I had been crazy, perhaps, but I was not crazy now.
“‘Throw her wide open,’ I commanded. ‘Wide open! These are fresh
turtle eggs for Professor Agassiz of Cambridge. He must have them
before breakfast.’
“Then they knew I was crazy, and, evidently thinking it best to
humor me, threw the throttle wide open, and away we went.
“I kissed my hand to the horse, grazing unconcernedly in the open
field, and gave a smile to my crew. That was all I could give them,
and hold myself and the eggs together. But the smile was enough.
And they smiled through their smut at me, though one of them held
fast to his shovel, while the other kept his hand upon a big ugly
wrench. Neither of them spoke to me, but above the roar of the
swaying engine I caught enough of their broken talk to understand
that they were driving under a full head of steam, with the intention
of handing me over to the Boston police, as perhaps the safest way
of disposing of me.
“I was only afraid that they would try it at the next station. But that
station whizzed past without a bit of slack, and the next, and the
next; when it came over me that this was the through freight, which
should have passed in the night, and was making up lost time.
“Only the fear of the shovel and the wrench kept me from shaking
hands with both men at this discovery. But I beamed at them; and
they at me. I was enjoying it. The unwonted jar beneath my feet
was wrinkling my diaphragm with spasms of delight. And the
fireman beamed at the engineer, with a look that said, ‘See the
lunatic grin; he likes it!’
“He did like it. How the iron wheels sang to me as they took the
rails! How the rushing wind in my ears sang to me! From my stand
on the fireman’s side of the cab I could catch a glimpse of the track
just ahead of the engine, where the ties seemed to leap into the
throat of the mile-devouring monster. The joy of it! of seeing space
swallowed by the mile!
“I shifted the eggs from hand to hand and thought of my horse, of
Agassiz, of the great book, of my great luck,—luck,—luck,—until the
multitudinous tongues of the thundering train were all chiming ‘luck!
luck! luck!’ They knew! they understood! This beast of fire and
tireless wheels was doing its best to get the eggs to Agassiz!
“We swung out past the Blue Hills, and yonder flashed the morning
sun from the towering dome of the State House. I might have
leaped from the cab and run the rest of the way on foot, had I not
caught the eye of the engineer watching me narrowly. I was not in
Boston yet, nor in Cambridge either. I was an escaped lunatic, who
had held up a train, and forced it to carry me from Middleboro to
Boston.
“Perhaps I had overdone the lunacy business. Suppose these two
men should take it into their heads to turn me over to the police,
whether I would or no? I could never explain the case in time to get
the eggs to Agassiz. I looked at my watch. There were still a few
minutes left in which I might explain to these men, who, all at once,
had become my captors. But how explain? Nothing could avail
against my actions, my appearance, and my little pail of sand.
“I had not thought of my appearance before. Here I was, face and
clothes caked with yellow mud, my hair wild and matted, my hat
gone, and in my full-grown hands a tiny tin pail of sand, as if I had
been digging all night with a tiny tin shovel on the shore! And thus
to appear in the decent streets of Boston of a Sunday morning!
“I began to feel like a lunatic. The situation was serious, or might
be, and rather desperately funny at its best. I must in some way
have shown my new fears, for both men watched me more sharply.
“Suddenly, as we were nearing the outer freight-yard, the train
slowed down and came to a stop. I was ready to jump, but still I
had no chance. They had nothing to do, apparently, but to guard
me. I looked at my watch again. What time we had made! It was
only six o’clock,—a whole hour left in which to get to Cambridge!
“But I didn’t like this delay. Five minutes—ten—went by.
“‘Gentlemen,’ I began, but was cut short by an express train coming
past. We were moving again, on—into a siding—on to the main track
—on with a bump and a crash and a succession of crashes, running
the length of the train—on, on at a turtle’s pace, but on,—when the
fireman, quickly jumping for the bell-rope, left the way to the step
free, and—
“I never touched the step, but landed in the soft sand at the side of
the track, and made a line for the freight-yard fence.
“There was no hue or cry. I glanced over my shoulder to see if they
were after me. Evidently their hands were full, or they didn’t know I
had gone.
“But I had gone; and was ready to drop over the high board-fence,
when it occurred to me that I might drop into a policeman’s arms.
Hanging my pail in a splint on top of a post, I peered cautiously over
—a very wise thing to do before you jump a high board-fence.
There, crossing the open square toward the station, was a big, burly
fellow with a club—looking for me!
“I flattened for a moment, when some one in the freight-yard yelled
at me. I preferred the policeman, and, grabbing my pail, I slid softly
over to the street. The policeman moved on past the corner of the
station out of sight. The square was free, and yonder stood a cab.
“Time was flying now. Here was the last lap. The cabman saw me
coming, and squared away. I waved a dollar-bill at him, but he only
stared the more. A dollar can cover a good deal, but I was too much
for one dollar. I pulled out another, thrust them both at him, and
dodged into the cab, calling, ‘Cambridge!’
“He would have taken me straight to the police-station, had I not
said, ‘Harvard College. Professor Agassiz’s house! I’ve got eggs for
Agassiz,’ pushing another dollar up at him through the hole.
“It was nearly half past six.
“‘Let him go!’ I ordered. ‘Here’s another dollar if you make Agassiz’s
house in twenty minutes. Let him out; never mind the police!’
“He evidently knew the police, or there were none around at that
time on a Sunday morning. We went down the sleeping streets, as I
had gone down the wood-roads from the pond two hours before,
but with the rattle and crash now of a fire brigade. Whirling a corner
into Cambridge Street, we took the bridge at a gallop, the driver
shouting out something in Hibernian to a pair of waving arms and a
belt and brass buttons.
“Across the bridge with a rattle and jolt that put the eggs in
jeopardy, and on over the cobble-stones, we went. Half standing, to
lessen the jar, I held the pail in one hand and held myself in the
other, not daring to let go even to look at my watch.
“But I was afraid to look at the watch. I was afraid to see how near
to seven o’clock it might be. The sweat was dropping down my nose,
so close was I running to the limit of my time.
“Suddenly there was a lurch, and I dived forward, ramming my head
into the front of the cab, coming up with a rebound that landed me
across the small of my back on the seat, and sent half of my pail of
eggs helter-skelter over the floor.
“We had stopped. Here was Agassiz’s house; and without taking
time to pick up the eggs that were scattered, I jumped out with my
pail and pounded at the door.
“No one was astir in the house. But I would stir some one. And I did.
Right in the midst of the racket the door opened. It was the maid.
“‘Agassiz,’ I gasped, ‘I want Professor Agassiz, quick!’ And I pushed
by her into the hall.
“‘Go ’way, sir. I’ll call the police. Professor Agassiz is in bed. Go ’way,
sir!’
“‘Call him—Agassiz—instantly, or I’ll call him myself.’
“But I didn’t; for just then a door overhead was flung open, a great
white-robed figure appeared on the dim landing above, and a quick
loud voice called excitedly,—
“‘Let him in! Let him in. I know him. He has my turtle eggs!’
“And the apparition, slipperless, and clad in anything but an
academic gown, came sailing down the stairs.
“The maid fled. The great man, his arms extended, laid hold of me
with both hands, and dragging me and my precious pail into his
study, with a swift, clean stroke laid open one of the eggs, as the
watch in my trembling hands ticked its way to seven—as if nothing
unusual were happening to the history of the world.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like