100% found this document useful (2 votes)
341 views

Download Complete MicroPython for Microcontrollers 1st Edition Günter Spanner PDF for All Chapters

Spanner

Uploaded by

delysmohrat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
341 views

Download Complete MicroPython for Microcontrollers 1st Edition Günter Spanner PDF for All Chapters

Spanner

Uploaded by

delysmohrat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Visit https://ebookgate.

com to download the full version and


explore more ebooks

MicroPython for Microcontrollers 1st Edition Günter


Spanner

_____ Click the link below to download _____


https://ebookgate.com/product/micropython-for-
microcontrollers-1st-edition-gunter-spanner/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Interfacing PIC Microcontrollers 2nd Edition Martin Bates

https://ebookgate.com/product/interfacing-pic-microcontrollers-2nd-
edition-martin-bates/

ebookgate.com

AS pure mathematics C1 C2 3rd ed Edition Val Hanrahan

https://ebookgate.com/product/as-pure-mathematics-c1-c2-3rd-ed-
edition-val-hanrahan/

ebookgate.com

Microcontrollers High Performance Systems and Programming


1st Edition Julio Sanchez

https://ebookgate.com/product/microcontrollers-high-performance-
systems-and-programming-1st-edition-julio-sanchez/

ebookgate.com

Warships in the War of the Pacific 1879 83 1st Edition


Angus Konstam

https://ebookgate.com/product/warships-in-the-war-of-the-
pacific-1879-83-1st-edition-angus-konstam/

ebookgate.com
A Slow Death 83 Days of Radiation Sickness Nhk Tv Crew

https://ebookgate.com/product/a-slow-death-83-days-of-radiation-
sickness-nhk-tv-crew/

ebookgate.com

Microcontrollers With C Cortex M and Beyond 1st Edition


Klaus Elk

https://ebookgate.com/product/microcontrollers-with-c-cortex-m-and-
beyond-1st-edition-klaus-elk/

ebookgate.com

C2 Re envisioned The Future of the Enterprise 1st Edition


Marius S. Vassiliou

https://ebookgate.com/product/c2-re-envisioned-the-future-of-the-
enterprise-1st-edition-marius-s-vassiliou/

ebookgate.com

The Vocabulary Files C2 Advanced IELTS 7 0 8 0 9 0 1st


Edition Andrew Betsis

https://ebookgate.com/product/the-vocabulary-files-c2-advanced-
ielts-7-0-8-0-9-0-1st-edition-andrew-betsis/

ebookgate.com

PIC Microcontrollers An Introduction to Microelectronics


2nd Ed 2nd Edition Martin P. Bates

https://ebookgate.com/product/pic-microcontrollers-an-introduction-to-
microelectronics-2nd-ed-2nd-edition-martin-p-bates/

ebookgate.com
books

MicroPython for
Microcontrollers
Projects with Thonny-IDE, uPyCraft-IDE, and ESP32

Günter Spanner
MicroPython for Microcontrollers
Projects with Thonny-IDE, uPyCraft-IDE, and ESP32

Dr Günter Spanner
● This is an Elektor Publication. Elektor is the media brand of
Elektor International Media B.V.
PO Box 11, NL-6114-ZG Susteren, The Netherlands
Phone: +31 46 4389444

● All rights reserved. No part of this book may be reproduced in any material form, including photocopying, or
storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this
publication, without the written permission of the copyright holder except in accordance with the provisions of the
Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency
Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to
reproduce any part of the publication should be addressed to the publishers.

● Declaration
The Author and the Publisher have used their best efforts in ensuring the correctness of the information contained
in this book. They do not assume, and hereby disclaim, any liability to any party for any loss or damage caused by
errors or omissions in this book, whether such errors or omissions result from negligence, accident or any other
cause.

● British Library Cataloguing in Publication Data


A catalogue record for this book is available from the British Library

● ISBN 978-3-89576-436-3 Print


ISBN 978-3-89576-437-0 eBook
ISBN 978-3-89576-438-7 ePub

● © Copyright 2021: Elektor International Media B.V.


Translation: Carmen Jacquemijns
Editor: Jan Buiting
Prepress Production: D-Vision, Julian van den Berg

Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro
engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops
and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social
media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com

●4
Content

Notices and Disclaimers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Demo Programs Download Archive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Chapter 1 • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1.1 Python, C, or Arduino? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1.2 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Chapter 2 • A Variety of ESP Boards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.1 Commissioning and function test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.2 ESP32 on battery power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Chapter 3 • P
 rogramming and Development Environments . . . . . . . . . . . . . . . . . . 19

3.1 Installing the uPyCraft IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.2 MicroPython for the ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.3 "Hello World" for the controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.4 For professionals: Working with esptool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

3.5 Thonny — a Python-IDE for beginners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

3.6 Working with Thonny . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3.7 Working with files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3.8 Troubleshooting tips for the Thonny IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Chapter 4 • First Steps in Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

4.1 Never without: Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

4.2 The Print() statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4.3 Indentations and blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

4.4 The hardware under control: digital inputs and outputs . . . . . . . . . . . . . . . . . . . . 45

4.5 Time control and sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

4.6 Important values: variables and constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

4.7 Numbers and types of variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

4.8 Converting number types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

4.9 Little Big Data: Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

4.10 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

4.11 With format, please: appealing text and data output . . . . . . . . . . . . . . . . . . . . . . . 55

4.12 Characters in chains: strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

Chapter 5 • The Controller in Practical Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

5.1 LED flasher as alarm system simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

●5
MicroPython for Microcontrollers

5.2 Useful in an emergency: automatic SOS signal . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Chapter 6 • Program Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

6.1 Conditions and loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

6.2 Running lights and airport lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

6.3 Electronic rainbow: RGB LED in use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

6.4 SOS compact-style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

6.5 Trial and error: try and except . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Chapter 7 • Analogue-Signal Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

7.1 Pulsewidth modulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

7.2 For romantic evenings: heartbeat simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

7.3 Light alarm clock for a relaxed wake-up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

7.4 Mood-Light with multicolour LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

7.5 Clean and smooth: analogue values from the DAC . . . . . . . . . . . . . . . . . . . . . . . 76

7.6 Output of time-dependent voltages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

7.7 For interesting curves: An arbitrary function generator . . . . . . . . . . . . . . . . . . . . 78

Chapter 8 • Interrupts and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

8.1 Disruption wanted: Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

8.2 Automatic night light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

8.3 Masters of Time: Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

8.4 A multifunctional flashing light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

Chapter 9 • Using Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

9.1 Acquisition of measurement and sensor values . . . . . . . . . . . . . . . . . . . . . . . . . 90

9.2 Precise recording of voltages: a DIY voltmeter . . . . . . . . . . . . . . . . . . . . . . . . . . 92

9.3 Linearity correction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

9.4 Linearization by limitation of the value range . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

9.5 Linearization of the ADC input by means of compensation polynomial . . . . . . . . . . 97

9.6 Voltage measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

9.7 Cross-interferences: side effects in sensor technology . . . . . . . . . . . . . . . . . . . . 101

9.8 Touching permitted: capacitive touch sensors . . . . . . . . . . . . . . . . . . . . . . . . . 102

9.9 Well chilled or overheated: temperature sensors provide clarity . . . . . . . . . . . . . 105

9.10 Digital temperature recording for error-free data transmission . . . . . . . . . . . . . 108

9.11 The DS18×20 One-Wire sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

●6
Content

9.12 Data power: multi-sensor array with the DS18x20 thermal sensor . . . . . . . . . . 110

9.13 In full view: optical sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

9.14 For film and photo professionals: electronic luxmeter . . . . . . . . . . . . . . . . . . . 113

9.15 Electronic bats: distance measurement with ultrasound . . . . . . . . . . . . . . . . . . 115

9.16 No more dents and scratches: distance warning device for garages . . . . . . . . . 119

9.17 Optimum indoor climate for flora and fauna . . . . . . . . . . . . . . . . . . . . . . . . . . 121

9.18 "Trust me ...": sensor comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

9.19 Air pressure and altitude measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

9.20 Detecting magnetic fields with the Hall sensor . . . . . . . . . . . . . . . . . . . . . . . . 129

9.21 Alarm detectors monitor door and gate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

Chapter 10 • Display Technology and Small-Size Screens . . . . . . . . . . . . . . . . . . 132

10.1 Graphical representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

10.2 OLED display as data plotter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

10.3 The exact time please: digital clock with OLED display . . . . . . . . . . . . . . . . . . 140

10.4 Not just for athletes: a stopwatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

10.5 Just touch: stop watch with sensor keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

10.6 Great climate with the BME280 sensor! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

Chapter 11 • LED Matrices and Large Displays . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

11.1 LED matrix in action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

11.2 Running scripts and animated graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

Chapter 12 • Physical Computing: Servos Bring Movement into Play . . . . . . . . . 155

12.1 A servo tester . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

12.2 Mega-display servo thermometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

Chapter 13 • RFID and Wireless Data Transmission . . . . . . . . . . . . . . . . . . . . . . . 161

13.1 Reading cards and chips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

13.2 Contactless and secure: RFID lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

Chapter 14 • MicroPython and the Internet of Things (IoT) . . . . . . . . . . . . . . . . 167

14.1 For modern detectives: a network scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

14.2 Connected but no cables: WLAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

14.3 Switch and control with the web server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

14.4 The WLAN web server in action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

14.5 Reading out sensor data via WLAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

●7
MicroPython for Microcontrollers

14.6 Recording environmental parameters: WLAN Thermo/Hygrometer . . . . . . . . . . 179

Chapter 15 • Simple and Good: The MQTT Protocol . . . . . . . . . . . . . . . . . . . . . . . 183

15.1 MQTT via ThingSpeak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

Chapter 16 • Sending Data to the Internet via ThingSpeak . . . . . . . . . . . . . . . . . 190

16.1 Rain or storm? Virtual weather station available worldwide . . . . . . . . . . . . . . . 190

16.2 Graphical representation of data in ThingSpeak . . . . . . . . . . . . . . . . . . . . . . . 194

16.3 Data for the smartphone with the ThingView app . . . . . . . . . . . . . . . . . . . . . . 195

16.4 Against unwanted visitors: Optical room surveillance . . . . . . . . . . . . . . . . . . . 196

Chapter 17 • Micropower Techniques and Sleep Modes . . . . . . . . . . . . . . . . . . . . 199

17.1 Saving power protects the environment: low-power technologies . . . . . . . . . . . 199

17.2 Disabling unnecessary consumers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

17.3 Weather station with battery or solar operation . . . . . . . . . . . . . . . . . . . . . . . 201

Chapter 18 • Bus Systems for Efficient Communication . . . . . . . . . . . . . . . . . . . 202

18.1 Basics and applications of the I²C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202

18.2 The SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

18.3 The members of the SPI family . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

18.4 Controlling SD and µSD cards via SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

Chapter 19 • Building Circuits with Components and Breadboards . . . . . . . . . . . 212

19.1 Breadboards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

19.2 Wire jumpers and jumper cables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

19.3 Resistors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

19.4 Light-emitting diodes (LEDs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

19.5 Capacitors and electrolytic capacitors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

Chapter 20 • Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

Chapter 21 • Hardware Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

Chapter 22 • List of Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

Chapter 23 • Bill of Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

●8
Notices and Disclaimers

Notices and Disclaimers

1. The circuits in this book are for educational purposes only.

2. The circuits in this book may only be operated with batteries and/or tested, dou-
ble insulated safety power supplies. Insulation faults of a simple power supply
unit can lead to life-threatening voltages on non-insulated components.

3. Powerful LEDs can cause eye damage. Never look directly into an LED!

4. Neither the Author or the Publisher accept any liability for damage resulting from
the construction of the described projects, or attempts to do so.

5. Electronic circuits can emit electromagnetic interference radiation. Since neither


the Publisher or the Author have any influence on the user's skills in assembling,
operating, and controlling electronic circuits, the user alone is responsible for
compliance with the relevant emission limit values.

●9
MicroPython for Microcontrollers

Demo Programs Download Archive

The demo programs mentioned in this book can downloaded free of charge as a single ar-
chive file (.zip) from the book resources web page:

www.elektor.com/micropython-for-microcontrollers

If a program from the download archive file appears to differ from the version described in
the book, the downloaded version should be used as it may reflect updates made by the
author since printing the book.

● 10
Chapter 1 • Introduction

Chapter 1 • Introduction

The introduction of the ESP32 chip from Espressif Systems marks a new generation of
microcontrollers, which offer excellent performance, Wi-Fi, and Bluetooth functionality at
an unrivalled price. These features have taken the maker scene by storm. The most diverse
applications and projects in the areas of Internet of Things (IoT) and home automation can
be implemented easily and cost-effectively. The ESP32 is as easy to program as the classic
Arduino boards. In comparison, however, the ESP32 also offers, among other things:

• Larger flash and SRAM memory


• Much higher CPU speed
• Integrated Wi-Fi / WLAN
• Bluetooth functionality
• More GPIO pins
• Extensive interface functionality
• Analogue/digital converter with higher resolution
• Digital/analogue converter
• Security and encryption functions

For these reasons, it can be considered the most promising successor to Arduino. The term
"Arduino killer" is often used in this context.

This book introduces the programming of modern single-chip systems (Systems on Chip —
SoCs). In addition to the technical background, the focus is on the programming language
Python, especially in its variant "MicroPython". Basic relationships between electronics and
electrical engineering will only be dealt with to the extent that it is essential for the design of
the circuits and experiments.

The "hardware" for getting started can be kept very simple anyway. At first, only a controller
board and some light emitting diodes as well as suitable series resistors are required. The
PC or laptop required for programming the chip should be available in every household. The
appropriate programming environment can be downloaded free of charge from the internet.
When working with a MicroPython programming environment, however, the first problems
quickly arise. A good introduction can therefore lead to excellent performances.

Python has experienced an enormous upswing in recent years. Various single-board systems
like the Raspberry Pi have especially contributed to its popularity. But Python has also found
widespread use in other areas such as artificial intelligence or machine learning. Hence it
is a logical choice to use Python or the variant MicroPython for the application in SoCs, too.

However, we will not restrict ourselves to a mere introduction to the programming lan-
guage. In many cases, the learned programming skills are put into practice together
with electronic circuitry. The fully described projects are all suitable for use in laborato-
ries or in everyday life. In addition to the educational effect, the pleasure of assembling
complete and useful devices is therefore also in the foreground. Through the use of lab-
oratory plug-in boards, circuits of all kinds can be realised with little effort. The testing

● 11
MicroPython for Microcontrollers

and trial of applications thus becomes an educational pleasure.

Due to the various applications such as weather stations, digital voltmeters and function
generators, the presented projects are also ideally suited for internships or study courses in
the natural sciences or in science and technology lessons.

1.1 Python, C, or Arduino?


For beginners, the Arduino programming environment is one of the easiest places to pro-
gram the ESP32. Behind this interface is the Arduino version of C, as well as C++. These
two programming languages have been popular for years for the development of embedded
systems. The Arduino version of C made it even easier to get started. In addition, one of the
largest technology communities in the world developed for this purpose. With new libraries,
software fixes and board support, problems could usually be solved quickly. However, the
restriction that Arduino-C only works in its designated environment is not insignificant. Es-
pecially for the development of more extensive projects, useful and important functions are
missing. Therefore, Arduino-C remained mostly limited to hobby and beginner projects.

MicroPython is relatively new. The user community is growing, and more and more platforms
are supported. MicroPython is essentially a slim version of Python, one of the most popular
programming languages in the world. Therefore, specific problems can be dealt with not only
in MicroPython communities. In fact, general Python forums are increasingly contributing to
solving MicroPython issues.

In addition to community support, MicroPython also has certain features that put it well
above the class of the Arduino. One of these features is the so-called REPL function. REPL
stands for "Read-Evaluate-Print Loop". This allows programs and code sections to be execut-
ed quickly. Compiling or uploading is not necessary. In this way, parts of a code can be tested
quickly and efficiently during development.

MicroPython contains a very compact implementation of the Python interpreter. It requires


only 256 KB flash memory and 16 KB RAM. Nevertheless the interpreter is designed for max-
imum compatibility with the standard Python. Syntax and language range correspond largely
to Python version 3.4, so experienced Python programmers should be able to find their way
around immediately. In addition, a few language elements beyond the standard are defined,
which keep the memory requirements low and increase the execution speed.

1.2 Requirements
In order to work successfully with this book, the following requirements should be met:

• Secure handling of the Windows operating system;


• Basic knowledge of any programming language such as C, Java or similar;
• Basic knowledge in the field of electronics, especially in the area of "current —
voltage — resistance" is assumed.

For specialized knowledge in the field of electronics, please refer to the extensive technical
literature, especially from Elektor, through their books, magazines, and kits. The hardware

● 12
Chapter 1 • Introduction

structure was deliberately kept simple, as the focus should be on programming with MicroPy-
thon. Nevertheless, different components and parts are required. Explanations can be found
in the individual chapters in which the components are used first. In addition, the last sec-
tions of the book explain some basic components such as resistors or light emitting diodes.
You can consult these if there are any unclarities concerning individual components.

Further requirements are

• a PC or laptop with USB interface,


• the Windows 10 operating system,
• internet access.

It is also useful to employ an active USB hub between the computer and the controller. This
has the advantage that it guarantees a certain protection for the PC. The hub should have
its own 5 V power supply through a separate power supply unit. Then the PC or laptop is best
protected against short-circuits behind the hub, as it is very unlikely that a short circuit will
"blow through" an active hub to the USB port of the computer.

● 13
MicroPython for Microcontrollers

Chapter 2 • A Variety of ESP Boards

The ESP32 is a modern and extremely powerful microcontroller. In addition to a high clock
frequency and the extensive internal functional units, the chip has integrated Wi-Fi and
Bluetooth. The controller was developed by Espressif Systems, a Chinese company based
in Shanghai, and is enjoying increasing popularity. The performance features of the ESP far
exceed the well-known Arduino boards in terms of price and performance.

As the ESP32 is only available as an SMD chip, a so-called break-out board (BoB) or devel-
opment board is required if the controller is to be used in a non-professional environment.
In the meantime, a virtually unmanageable variety of different versions is available on the
market. The best-known versions are:

Board Pins Buttons LiPo Charger

ESP32-PICO-KIT 34 EN and BOOT no

JOY-iT NodeMCU 30 EN and BOOT no

ESP32 DEV KIT DOIT 30/36 EN and BOOT no

Adafruit HUZZAH32 28 RESET yes

ESP32 Thing 40 EN and BOOT yes

LOLIN32 40 EN and BOOT no

Node-ESP-Board 38 EN and BOOT no

The following image shows just three different versions:

Figure 2.1: ESP32 boards (PICO-KIT, Node-ESP and NodeMCU).

These boards have the necessary prerequisites to operate the ESP controller on a solderless
plug-in board or breadboard. Frequently, in addition to the controller, other components
such as pushbuttons, a Li-ion battery charger, or various LEDs are mounted on the boards

● 14
Chapter 2 • A Variety of ESP Boards

available. This means that initial tests and experiments can be carried out without external
circuitry.

The following section summarizes the most important data about ESP32. The overview
should only provide a first impression. A deeper understanding of the individual features
and functions is then provided in the relevant sections in the book.

Processor: 160 / 240 MHz Tensilica LX6 dual-core microprocessor


Memory: 520 KByte SRAM / 16 MByte Flash memory
Power supply: 2.2 V to 3.6 V
Power consumption: Standard: approx. 50 - 70 mA
Wi-Fi mode: approx. 80 - 170 mA
Deep sleep mode: approx. 2.5 µA
Ambient temperature: –40 °C to +125 °C
Inputs/Outputs (GPIOs): 32 general purpose ports with PWM
Function and timer logic
Wi-Fi: 802.11 b/g/n/e/i
Network throughput: 135 MBit/s (via UDP protocol)
Receiver sensitivity: –98 dBm
Bluetooth: V4.2 BR/EDR and BLE
Bluetooth functionality: Classic and Bluetooth Low Energy (with integrated antenna)
Sensors: Hall sensor
10× capacitive touch sensor
Interfaces: 3× UART with flow control via hardware 3x SPI interfaces
CAN bus 2.0 controller
2× I2S and 2xI2C interfaces
18 analogue inputs with 12-bit analogue-to-digital converters
2 analogue outputs with 10-bit digital-to-analogue converters
Infrared (IR) (TX/RX)
Motor PWM
LED-PWM with up to 16 channels
Interface for external SPI flash memory for up to 16 MB
SD card hardware
Security: Wi-Fi: WFA, WPA/WPA2 and WAPI Secure Boot
Flash Encryption
Cryptographic Hardware Acceleration Elliptic Curve Cryptogra-
phy (ECC)
Random Number Generator (RNG)

The ESP32-PICO-KIT is usually employed for the application examples in this book. Alter-
natively the ESP32 DEV KIT or another board can be used. The variant used is mentioned
explicitly in each case. In principle, however, the various boards are largely compatible. They
differ mainly in size and in pin arrangement order. Figure 2.2. shows the PICO-KIT with its
functional units and connections.

● 15
MicroPython for Microcontrollers

Figure 2.2: ESP32 PICO-KIT board.

The breakout boards are best suited as experimental and development boards. Via the port
connections, electronic components such as LEDs, temperature sensors or even smaller ac-
tuators such as R/C model servos can be connected directly. The Pico Kit board has the fol-
lowing features, among others:

• ESP controller with two 32-bit cores


• Fast Wi-Fi and WLAN interface (up to 150 MBit/s)
• ADC & DAC functionality
• Touch Sensor Unit
• Host Controller for SD/SDIO/MMC
• SDIO/SPI Controller
• EMAC and PWM unit for controlling LEDs and motors
• UART, SPI, I²C and I²S interfaces
• Infrared remote-control controller
• GPIO Interface
• Bluetooth/Bluetooth LE (4.2)
• USB-to-Serial-Chip for access via USB interface

2.1 Commissioning and function test


As soon as a board is available, it should be subjected to an initial functional test. For this
purpose, a USB cable is connected to a PC or laptop and the micro-USB socket of the board.
If present, a USB hub should already be connected in between.

On most boards, an LED will light up when connected to a powered USB port. If, contrary to
expectations, this so-called "power-on" LED does not light up, the USB connection should be
disconnected immediately. In this way you can prevent a possible short circuit from causing
major damage. For further troubleshooting, helpful hints are given in the corresponding
chapter at the end of the book.

ESP boards should always be operated in a solderless plug-in board (see Figure 2.3). How-
ever, if you do work without a breadboard, make sure that the base used is not conductive,

● 16
Chapter 2 • A Variety of ESP Boards

otherwise short circuits between the pins may occur. Next to the ESP board itself, this can
even destroy the USB port of the PC.

Figure 2.3: ESP board plugged into a breadboard.

2.2 ESP32 on battery power


In most cases, an ESP board is supplied with power via the Micro-USB socket. Since the con-
troller is connected to a PC or laptop during program creation anyway, no additional power
supply is required.

If a direct data exchange with the PC is no longer necessary, the board can also be supplied
by a USB power supply. This should be able to supply at least 1,000 mA (1 A; 1 amp) of
current output to avoid unwanted voltage drops. In addition, there is a certain amount of
reserve power to operate some LEDs, displays or sensors.

Even without a USB connection, the board can send and receive data via Wi-Fi and Blue-
tooth. In order to achieve complete independence from power and data cables, the module
then only needs to be powered by (rechargeable) batteries.

Some boards have a Lithium-Ion (Li-Ion) battery connector for this purpose (see Figure 2.4).
There, suitable cells can be connected directly via the standard plug. An internal voltage
regulation then ensures that the controllers are optimally supplied. In addition, a connected
battery is charged as soon as the board is connected to a live USB socket.

For this application, cells with a capacity of about 1,500 mAh or more are suitable. Smaller
batteries below 300 mAh should not be used, as they could be overcharged by the integrated
charge controller.

With a typical power consumption of approx. 50 mA, the 1,500 mAh variant can achieve an
operating time of around 30 hours, i.e. just over a day. When using the controller's sleep
functions, even considerably longer operating times can be achieved.

● 17
MicroPython for Microcontrollers

Single cell LiPo (Lithium Polymer) or Lithium-Ion batteries provide sufficient power for the
ESP32. However, their voltage of 3.7 to 4.2 V, depending on the state of charge, is too high
for the ESP32. It is therefore regulated down via an internal module.

As working with Li-ion batteries is always associated with a certain degree of danger, the
following information should not be omitted:

• Lithium-Ion batteries react sensitively to incorrect charging currents or voltag-


es. Under certain circumstances there is even a risk of fire or explosion.
• Each user is responsible for their own construction and operation of the project.
• Neither the Publisher nor the Author assumes any liability.

Figure 2.4: NodeESP board in battery mode.

● 18
Chapter 3 • Programming and Development Environments

Chapter 3 • P
 rogramming and Development
Environments

Unlike the situation with, say, an Arduino system, there are several Integrated Developing
Environments (IDEs) available for working with MicroPython. In principle, you can write pro-
grams with all IDEs and load them onto the controller. The two most widespread program-
ming environments are currently:

• µPyCraft
• Thonny

Both have their own specific advantages and disadvantages. The differences lie mainly in the
different procedures for developing and managing program code for the application projects.

The first variant called µPyCraft offers a comparatively simple interface for MicroPython
development on the ESP32 controller. It works with simple graphic elements and resembles
text-oriented operating systems. The handling of the individual functions is easy to under-
stand and working with the different menus is easy to learn.

Thonny, on the other hand, has a fully graphical interface in Windows style. The IDE is very
popular among makers, especially because it is available under the Raspbian operating sys-
tem on the Raspberry Pi. Many Raspberry Pi users are therefore already very familiar with
Thonny.

The IDEs stand for the most important operating systems such as

• Windows PC
• Mac OS X
• Linux Ubuntu

which are available free of charge on the internet.

If problems occur during installation or use of either system, the other version can be used
as an alternative programming system. The version to choose depends of course on the
personal inclinations and habits of the user.

3.1 Installing the uPyCraft IDE


Before installing uPyCraft IDE, the latest version of Python 3.7.X should be installed on the
computer you are using. If it is not, the installation can be done according to the following
instructions:

1. Download the installation file from the Python download page at:

www.python.org/downloads

● 19
MicroPython for Microcontrollers

2. After the download operation, a file named

python-3.7.X.exe

should reside on your computer. Double-clicking on the file starts the


installation.

3. Select "Add Python 3.7 to PATH" and click the "Install Now" button.

4. The installation process is completed after a few seconds and the message
"Setup was successful" is displayed. The window can then be closed.

Now the uPyCraft IDE for Windows can be downloaded from

https://github.com/DFRobot/uPyCraft

as a file called uPyCraft_V1.x.exe. After clicking on this .exe file, the uPyCraft-IDE will open:

Figure 3.1: uPyCraft-IDE

After the IDE is installed on the computer, the ESP32 firmware can be loaded onto the chip.
The current version of the MicroPython firmware for the ESP32 can be found at

http://micropython.org/download#esp32

There you scroll to the section "ESP32 modules". After clicking the link to "Generic ESP32
module" you will get to the download page of the ESP32-BIN file. This will look as follows:

esp32-idf3-20191220-v1.12.bin

Now you can start the uPyCraft-IDE. Under

Tools -> Serial

● 20
Chapter 3 • Programming and Development Environments

select the ESP32-COM port, here as COM5:

Figure 3.2: Selecting the port.

If the ESP32 board is connected to the computer but the ESP32 port does not appear in the
uPyCraft IDE, the appropriate USB driver may be missing. In this case, the driver must be
reinstalled. A corresponding driver can be found under

https://www.silabs.com/products/development-tools/software/usb-to-uart-
bridge-vcp-drivers

Afterwards you can follow

Tools -> Board

Next, the option "esp32" must be selected:

Figure 3.3: Selecting the board type

Now the MycroPython interpreter can be written onto the ESP32 using

Extras -> Burn Firmware

● 21
MicroPython for Microcontrollers

The appropriate options are:

• board: esp32
• burn_addr: 0x1000
• erase_flash: yes
• com: COMX (here COM5, see above)

Under "USERS", select the downloaded ESP32-BIN file, as shown in Figure 3.4.

Figure 3.4: The parameters for flashing the firmware

If all settings are correctly selected, the "BOOT / FLASH" button on the ESP32 board must
be pressed on some board variants. As soon as the "EraseFlash" process begins, the key can
be released. After a few seconds, the firmware should have flashed onto the ESP32 board.
However, in many cases the download will start without pressing the buttons.

If the "EraseFlash" display does not start or an error message is displayed, repeat the steps
described above. Also press the "BOOT / FLASH" key again to ensure that ESP32 enters the
flash mode.

3.2 MicroPython for the ESP32


With a few exceptions, all features and functions of Python are also available in MicroPython.
The biggest difference is that the micro version was designed for use on single-chip systems
and therefore the classic routines required only for the PC are missing.

For this reason MicroPython does not contain the complete standard library, but only the
parts relevant for microcontrollers. Therefore, all modules required for accessing the used
hardware are available. With the corresponding libraries you can therefore easily access
the GPIO pins. Especially for the ESP32 there are also modules available to support network
connections (Wi-Fi) and Bluetooth. In particular, the following boards are supported:

• ESP32
• ESP8266
• PyBoard
• Teensy 3.X
• WiPy - Pycom

● 22
Chapter 3 • Programming and Development Environments

Although not all functions of the ESP controller are fully available in MicroPython as of yet,
the libraries contain the most important commands and routines. Therefore many projects
and applications can be implemented smoothly. In addition, the implementation of the miss-
ing features is progressing rapidly, so that even this small beauty flaw will be quickly elim-
inated.

Once the MicroPython firmware has been installed on the ESP32, you can also easily return
to the Arduino IDE, for example. To do this, simply load the new C code with the IDE onto
the controller. A special deletion procedure is not necessary. However, if you want to use
MicroPython again afterwards, the MicroPython firmware must be flashed again.

3.3 "Hello World" for the controller


Unlike AVR controllers, such as those used in the Arduino system, the ESP32 can accommo-
date a complete file system. The first generations of controllers were programmed in either
Assembler or C. The program code was therefore created and compiled in a development
environment. Then only the finished "machine code" was transferred to the controller. The
memory of the target system therefore always contained exactly one program.

In contrast, when programming in MicroPython, several programs can be stored on the


ESP32 chip. These can then be processed directly by the interpreter that is also available on
the system. The file system can be managed directly with the uPyCraft-IDE. It is therefore
advisable to familiarise yourself with the IDE a little more closely before loading the first
application program onto the ESP. The development environment contains, similar to many
other programming tools, the following components (see also Figure 3.1)

1. Folders and files


2. Editor
3. MicroPython Shell / Terminal
4. Tools

In the left sub-window ("Folders and files"), the files currently stored on the ESP board are
visible in the device folder ("device"). As soon as the board is connected to uPyCraft-IDE via a
serial connection, all saved files will be loaded when opening the device folder. Directly after
the installation of the Python interpreter only a "boot.py" file is visible here. To execute the
application code, a main.py file should also be created. You can create a main.py file using:

file → new

This creates a new file ("untitled"). Through the floppy disk icon in the "Tools" window this
file can be saved locally under the name "main.py" on the ESP chip.

● 23
MicroPython for Microcontrollers

Figure 3.5: Creating a new file "main.py".

The following two files are now in the device folder:


• boot.py: executed every time the board is rebooted
• main.py: main script for the application code

The SD folder follows under the device folder. This folder is intended for accessing files stored
on an SD card. Some ESP-32 boards have an SD card slot. If a µSD card is inserted here, the
files on the card appear in the "sd" folder.

The uPy_lib folder follows below. Here the integrated IDE library files are shown. Here you
can find different files directly after the installation of the MicroPython interpreter. These are
provided as standard libraries.

Figure 3.6: Standard libraries in the uPy_lib folder.

The last folder contains the so-called "workSpace". This is a directory for saving application
files. The files displayed here are stored on the computer connected via the interface. All
active files should be stored there.

When uPycraft is used for the first time, it is therefore recommended that a suitable working
directory called "workSpace" be created and then used consistently for working with the
controller.

In the Editor area (2) the code for the .py application programs is created. The Editor opens
a new tab for each file.

● 24
Chapter 3 • Programming and Development Environments

The section below the Editor area is the "MicroPython Shell/Terminal" (3) All commands
entered here are immediately executed by the ESP board. In addition, the terminal also
displays information about the status of a running program. Any syntax errors in the current
program or error messages during uploading, etc., appear here.

With the symbols in the "Tools" area at the far right of the main window (4), tasks can be
executed quickly and directly. The buttons have the following functions:

• New File: Creates a new file in the editor


• Open File: Opens a file on the computer
• Save File: Saves a file
• Download and run: Upload code to the ESP board and run it
• Stop: Ends code execution. This corresponds to entering CTRL + C in the shell
• Connect/Disconnect: Connect or disconnect the serial interface. The serial port
can be selected under Tools -> Serial
• Undo: undoes the last change in the code editor
• Redo: Repeat last change in code editor
• Syntax check: Checks the syntax of the current code
• Clear: Deletes the shell / terminal window messages

In order to become familiar with writing a program and executing code on the ESP32, a
short Python program will be developed and executed below, which makes a LED flash. The
first step is to establish communication with the ESP board:

1. Select the current board via Tools -> Board


2. In Tools -> Port select the COM-Port to which the ESP-Board is connected
3. The Connect button then establishes serial communication with the ESP32
module
4. After a successful connection to the board, ">>>" is displayed in the shell
window.

Now a print command can be entered to test whether the communication is working cor-
rectly:

>>> print ('test')

The answer

Test
>>>

appears in the terminal window. When the message is displayed, everything is OK. Other-
wise, check that serial communication with the board is established and that the MicroPy-
thon firmware has been flashed successfully to the board.

● 25
MicroPython for Microcontrollers

Now a LED flashing script can be created. The following steps are required for this:

1. The following program is entered into the Editor window of the file main.py,
which was created above:

from machine import Pin


from time import sleep
led = Pin(2, Pin.OUT)
while True:
led.value(not led.value())
sleep(1)

2. By clicking on the "Stop" button, a script that may still be running can be stopped
3. With a click on the button "Download And Run" the script is written to the con-
troller
4. The shell window should now show the message "download ok".

Figure 3.7: Successful download of the first program.

Now the integrated LED of the ESP32 board should flash every second. This means that
the first Python program was successfully transferred to the controller and executed im-
mediately.

● 26
Chapter 3 • Programming and Development Environments

Figure 3.8: Internal LED at port 02 in action.

Some boards do not have an integrated LED. In this case, an LED including series resistor
must be connected to the controller (see, for example, Figure 4.6 and Figure 4.7). Further
details and information on the flashing program and on connecting external LEDs can be
found in Section 4.4.

3.4 For professionals: Working with esptool


If problems occur with the µPyCraft-IDE or if other reasons stop you from using it, you can
also load the MicroPython firmware onto the controller with the help of a utility called esp-
tool.

It is then even possible to transfer programmes to the controller via a terminal such as PUTTY
or TeraTerm. However, this method already requires some in-depth knowledge of the com-
mand line interface or the device manager. This procedure is therefore less recommended
for beginners. Nevertheless, the method will be described here, as it also provides further
insights into the handling of the controller programming. In addition, the methods presented
here can also be easily transferred to Linux or UNIX systems.

In order to work with esptool, Python 3.7.X or a newer Python installation should be installed
on the System System. The current version of esptool can then be downloaded to the com-
puter via a terminal window using

pip install esptool

With some Python installations, this instruction may cause an error message to appear. In
this case, the following instructions may lead to the destination:

pip3 install esptool


python -m pip install esptool
pip2 install esptool

● 27
MicroPython for Microcontrollers

Now the esptool file should be installed in the standard directory for executable files. To
access the controller, its serial port number must be known. This can be found in the Device
Manager:

Figure 3.9: The COM port of the ESP32 in the Device Manager.

In the figure, the port number is COM3, for example. This allows the following command to
be executed in the terminal window:

esptool --port COM3 flash_id

This provides information about the ESP32 system connected to that port:

Figure 3.10: Information about ESP32.

The lines

...
Detecting chip type... ESP32
Chip is ESP32-PICO-D4 (revision 1)
Features: WiFi, BT, Dual Core, Embedded Flash

● 28
Chapter 3 • Programming and Development Environments

Crystal is 40MHz
MAC: d8:a0:1d:40:54:14
...
Device: 4016
Detected flash size: 4MB

thus provide important information about the chip type, the board, the available interfaces,
the crystal frequency and the available flash memory.

Now you can use the instruction

esptool --port COM3 erase_flash

to erase the flash memory of the chip.

Figure 3.11: Successful erasing of the flash memory.

This clears the way for uploading the MicroPython firmware. The download of the firmware
from the internet was already described in the last chapters. The command for the upload is

esptool --port COM3 --baud 460800 write_flash -fm dio 0x1000


C:\Users\Documents\workSpace\esp32-xxxxxxxx-vx.x.x.bin

Of course, the correct path where the esp32-20xxxxxx- vx.x.x.bin file is located must again
be specified here. After a few seconds, the upload should be finished:

● 29
MicroPython for Microcontrollers

Figure 3.12: Upload of the firmware is completed.

Now you can contact the ESP via PUTTY or TeraTerm. The baud rate must be set to 115200:

Figure 3.13: MicroPython reports to the TeraTerminal.

A first Python program can already be loaded via the terminal, for example:

from machine import Pin


import time
p23 = Pin(23, Pin.OUT)
while True:
p23.value(1)
time.sleep(1)
p23.value(0)
time.sleep(.1)

● 30
Chapter 3 • Programming and Development Environments

Figure 3.14: Programming via TeraTerminal.

After the program has been transmitted, an LED connected to port 23 should flash at a
1-second rate.

The console offers the usual help system, which can provide useful information if neces-
sary:

Figure 3.15: Help function in the terminal.

● 31
MicroPython for Microcontrollers

3.5 Thonny — a Python-IDE for beginners


Thonny is a good alternative to uPyCraft. Although even this programming environment is
not yet completely bug-free, you can generally work well with it. In addition, the system
is constantly being updated and improved, so this flaw will also be eliminated in the fore-
seeable future. Thonny is also available for all common operating systems. Under Raspbian
for Raspberry Pi it is even installed by default. The installation is relatively simple, so there
should be hardly any problems in the installation process. A prerequisite for working with
Thonny is that the MicroPython firmware has already been loaded onto the ESP32. For be-
ginners, the use of the µPyCraft-IDE is recommended. Experts can also use esptool (see last
chapter) to bypass the µPyCraft-IDE completely.

The examples in this book were created with Thonny 3.2. In principle, future versions
should be compatible with it. However, in case of unexpected problems, you should return
to the version mentioned above. The appropriate package can be downloaded from

https://thonny.org

When the download is complete, you can run the installation file. Now you only have to
follow the assistant until the installation process is finished. Afterwards the Thonny-IDE can
be opened.

Figure 3.16: The Thonny-IDE after start-up.

Now the ESP32 board can be connected to the computer. To test the installation, Thonny
must be configured for the MicroPython interpreter. In addition, the board used must be
selected. The following steps are necessary for this:

1. Run → Interpreter opens the following window:

● 32
Chapter 3 • Programming and Development Environments

Figure 3.17: The options window in Thonny.

2. In the first selection window, select "MicroPython" (generic).


3. The COM interface of the ESP32 must be entered under Port.

Now the Thonny-IDE should be connected to the board and the shell window should show
the prompt ">>>". Alternatively the option "Try automatic recognition" can be selected.
However, this does not work reliably with all boards. Finally, the help() command is entered
into the shell. This will return a welcome message and some information:

Welcome to MicroPython on the ESP32!


For generic online docs please visit http://docs.micropython.org/
For access to the hardware use the ‚machine' module:

import machine
pin12 = machine.Pin(12, machine.Pin.OUT)
pin12.value(1)
pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
print(pin13.value())
i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))
i2c.scan()
i2c.writeto(addr, b'1234')
i2c.readfrom(addr, 4)

Basic WiFi configuration:

import network

● 33
MicroPython for Microcontrollers

sta_if = network.WLAN(network.STA_IF); sta_if.active(True)


sta_if.scan() # Scan for available access points
sta_if.connect("<AP_name>", "<password>") # Connect to an AP
sta_if.isconnected() # Check for successful connection

Control commands:
CTRL-A -- on a blank line, enter raw REPL mode
CTRL-B -- on a blank line, enter normal REPL mode
CTRL-C -- interrupt a running program
CTRL-D -- on a blank line, do a soft reset of the board
CTRL-E -- on a blank line, enter paste mode

For further help on a specific object, type help(obj)


For a list of available modules, type help('modules')

The installation and commissioning of Thonny has thus been successfully completed. The
hardware functions can now be activated via shell instructions. First of all the machine
module can be imported:

>>> from machine import Pin

Then, an LED connected to port 23 can be switched on via

>>> led = Pin(23, Pin.OUT).value(1)

Alternatively, the standard LED available on most boards can be used. Via

>>> led = Pin(23, Pin.OUT). value(0)

the corresponding LED is switched off again.

3.6 Working with Thonny


In the Thonny-IDE there are several different sections, among which are the editor and the
MicroPython shell or terminal:

• In the editor area, code is created and edited. Multiple files can be opened, with
a new tab available for each file.

• In the MicroPython shell, commands are entered that are to be executed imme-
diately by the ESP card. The terminal also provides information about the status
of an executed program, indicates errors related to uploading, syntax errors,
print messages, etc.

Other useful tabs are also available. These can be configured in the View menu. The "Var-
iables" tab in particular can often be used to great advantage. It shows all variables of a
program and their current values.

● 34
Chapter 3 • Programming and Development Environments

In order to become familiar with writing programs and executing code on the ESP32, the
already known script is used again, which makes the integrated LED of an ESP32 board or
an external LED blink.

At first a main.py file is created on the board:

1. When Thonny starts for the first time, the editor shows a file without title.
This file is saved as main.py. For this purpose, the file is saved via

file → save as

renamed to main.py and saved on the board ("Micro Python Device").

2. Now a tab named "main.py" is available.

3. The following code is entered here:

from machine import Pin


import time
p23 = Pin(23, Pin.OUT)
while True:
p23.value(1)
time.sleep(1)
p23.value(0)
time.sleep(.1)

The code is available in the download package for this book and can be used initially via
copy and paste. Later it is explained how files can be copied directly from the PC to the
controller.

Via the green arrow or

run → run current script

or by pressing function key F5, the code is transmitted to the controller. The following in-
formation is output to the shell:

MicroPython v1.9.4 on 2018-05-11; ESP32 module with ESP32


Type "help()" for more information.
>>> %Run -c $EDITOR_CONTENT

When the ESP is restarted, first the boot.py and then the main.py is executed. If boot.py
is not present, it is started immediately with main. So the program should become active
immediately after uploading, and the LED on the selected port (No. 23 in the example
above) should blink.

● 35
MicroPython for Microcontrollers

With some board variants, it may also be necessary to press the ESP EN / RESET key.

3.7 Working with files


To upload a file with a unique name to the ESP using the Thonny IDE, the following steps
are required:

• Creating a new file


• Save the file on the computer with the exact name, for example "blink.py".

The file can be opened as a new tab in the "This Computer" subwindow. It can then be
opened via the menu

file → save as

on which ESP can be saved under its name ("blink.py") The second selection "MicroPython
device" must be selected in the query (see figure).

Figure 3.18: Query when saving

The file is now uploaded to the board and appears in the sub-window "Files". From there it
can now be started with the green arrow key or F5.

Accordingly, it is also possible to download files from the chip to the computer by selecting
"This Computer". Other commands for deleting or renaming files etc. are also found in the
"file" menu.

3.8 Troubleshooting tips for the Thonny IDE


In the current section some error messages of the Thonny-IDE will be discussed. The cor-
responding problems are usually relatively easy to solve:

• In many cases, restarting ESP with the integrated EN/RST key is already
successful.
• Within the Thonny-IDE, communication problems between PC and chip can often
be solved by pressing the "Stop / Restart Backend" button (or CTRL-F2).

Otherwise, the following tips may help:

● 36
Chapter 3 • Programming and Development Environments

Error 1: No connection to the board.

In this case, the error messages are displayed:

========================= RESTART =========================


Unable to connect to COM4
Error: could not open port 'COM4': FileNotFoundError(2, 'The system cannot
find the file specified.', None, 2)

or:

========================= RESTART =========================


Could not connect to REPL.
Make sure your device has suitable firmware and is not in bootloader mode!
Disconnecting.

or:

========================= RESTART =========================


Lost connection to the device (EOF).

In this case it is often helpful to interrupt the USB connection to the module and then re-es-
tablish it. You should also check whether the correct serial port is set under

Run -> Select Interpreter

This error could also indicate that the serial port is already being used by another program
such as a serial terminal or the Arduino IDE. If this is the case, make sure that all programs
that may be communicating serially with the ESP card are closed. Then the Thonny IDE
should be restarted.

Error 2: Thonny IDE does not answer or gives an internal error.

After closing and re-opening the active window, you should be able to continue working
normally. If there are repeated crashes, the whole Thonny-IDE should be restarted.

Error 3: Thonny IDE no longer responds to the "Stop / Restart Backend" key.

After pressing the button "Stop / Restart Backend" you should wait a few seconds. The ESP
needs time to restart and restore serial communication with Thonny. If the "Stop" button
is clicked several times or very quickly one after the other, the ESP module does not have
enough time to restart properly. This may cause the Thonny IDE to crash.

Error 4: Problem when restarting the ESP card, running a new script or opening the serial
port.

● 37
MicroPython for Microcontrollers

If the following error message appears:

Brownout detector was triggered

or if there are continued reboots, or if the information:

ets Jun 8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)


configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:4732
load:0x40078000,len:7496
load:0x40080400,len:5512

is displayed, this may indicate a hardware problem. This is often caused by one of the fol-
lowing problems:

• USB cable of poor quality,


• USB cables too long,
• The ESP board has a defect, e.g. a bad solder joint,
• Faulty computer USB connection,
• The computer's USB port does not supply enough power.

In these cases, the use of a high quality and shortest possible USB cable will help. Changing
to a different USB socket on the PC can also be helpful. For laptops, an active USB hub with
its own external power supply should be used. This way you are no longer dependent on
the performance of the laptop USB power supply.

If the problems persist or other strange error messages appear, it is recommended to up-
date the ESP board with the latest version of the MicroPython firmware. This will at least
prevent errors that have already been corrected from making work more difficult.

Error 5: No connection between PC and ESP32.

It may happen that the controller is too loaded to establish a USB connection. In this case,
clicking the button "Stop/ Restart Backend" several times may bring the desired success.
However, this repeated clicking should take place at certain intervals (see above).

When running a script that uses Wi-Fi, switches to sleep mode, or performs multiple tasks
in parallel, it is recommended that you try to establish communication three or four times.
If this is still not possible, the ESP should be flashed again with the current MicroPython
firmware.

● 38
Chapter 4 • First Steps in Programming

Chapter 4 • First Steps in Programming

Python has been one of the most frequently used programming languages for several
years. One of the reasons for this is that it was very simply designed and is therefore easy
to learn. The development of MicroPython makes the programming of microcontroller sys-
tems comparatively simple and straightforward. This makes the programming language also
very suitable for beginners in the world of embedded systems.

The developers of MicroPython have set themselves the goal of making the programming
of digital electronics as easy as possible. In this way, the largest possible circle of users can
be addressed. Python programs can be found in the hobby area as well as in education
or scientific use. But professional developers too, increasingly work with Python. In the IT
industry, numerous market leaders such as Google or Amazon have been using Python for
their software developments for a long time.

In addition, freely available modules and libraries such as MatPlotLib, NumPy, SciKit or
SciPy provide extensive possibilities. These range from scientific data analysis to machine
learning and artificial intelligence.

MicroPython was developed as a slim version of Python 3. Since the language has to be in-
terpreted, it is generally slower than compiled systems. MicroPython was designed to work
as efficiently as possible on small embedded systems. Therefore it can also be run on micro-
controllers which are much slower clocked and have much less memory than typical personal
computers.

A disadvantage of classical Python programming is that low-level controls are very difficult to
implement. For this reason, the classic Python variants are used rather secondary in hard-
ware-related programming. This shortcoming is largely eliminated by MicroPython. Based on
the standard, the Micro version is also strongly based on Python 3 in its syntax. In addition
there are virtual machines and the associated libraries.

If one compares the two most popular programming languages in the microcontroller envi-
ronment, one finds that Python is more often preferred over C/C++. In the rankings of the
most popular programming languages, Python more and more often reaches the first place.
The competitor C/C++, on the other hand, is increasingly being relegated to lower ranks.
The reason for this development is mainly based on the following advantages of Python:

• Python is very beginner-friendly due to its simple language structure.


• Various internet forums support the programmer with tutorials and example
codes.
• There are extensive libraries available.

Beginners usually find solutions to their problems quickly in the forums. In other languages
this form of mutual support is not as pronounced.

● 39
MicroPython for Microcontrollers

In C, programming is done via control registers, pointers and other structures and instruc-
tions that are often difficult to understand. The firmware for the target controller must be
programmed, compiled and finally transferred to the controller with a programming device.
MicroPython integrates all these steps. With a simple mouse click, users can control low-lev-
el hardware such as LEDs, displays, or motors. The acquisition of analogue voltage values
or working with SD cards becomes child's play with the appropriate libraries. Integrated
memory cleaning and a dynamic allocation process enables efficient memory management
in Python. This means that you hardly need to resort to pointers or similar constructs, which
are usually difficult for beginners to penetrate.

The often-cryptic C-symbols like x++, <<, >> etc. as well as the complex variable declara-
tion represent a hurdle for the beginner which should not be underestimated. Python is known
for its simplicity and the excellent readability of the code.

Since MicroPython was developed as a "light version" for microcontroller applications, not
all libraries and functions of standard Python are supported. Nevertheless, you can easily
switch to the micro version if you are already familiar with Python. Only a few syntactical
structures or instructions are not available or applicable in MicroPython.

Python is interpreted. This means that the original program code is processed directly by the
target processor. Compilation is therefore not necessary. Python therefore offers the possi-
bility to execute a program once written on a wide variety of systems. For this purpose, only
a corresponding interpreter must be installed. One of the biggest advantages of Python code
is its comprehensive compatibility. Python programs can be executed on classic computers
under Windows, MacOS or Linux as well as on small single-board systems such as the Rasp-
berry Pi or comparable microsystems. Especially the use on the "RPi" (German: "Raspi") has
also contributed to the increasing popularity of Python.

With new powerful controllers such as ESP32, it has now even become possible to use Py-
thon efficiently and conveniently in this area as well. Firmly integrated constructs ensure
that programs can be easily developed on both a small and large scale. Python is therefore
excellently scalable. The possible encapsulation of data and program code in clear, usable
modules, i.e. objects, makes Python an object-oriented programming language. C++ is
generally used nowadays, especially in hardware-oriented programming. Classical Python
variants were not well suited for this purpose until now. With MicroPython this gap is now
closed.

C++ includes client applications as well as powerful server applications, device drivers and
embedded driver components. The area of application ranges from system software to ap-
plication programming. Since Python is a relatively new programming language compared
to C, it has not yet found universal use in all areas of information technology. However, it can
be seen that Python is gaining ground in practically all areas.

The main disadvantage of Python is certainly its comparatively low processing speed. Here
compiled languages like C can clearly show their advantages. Fast control loops or real-time
systems, vehicle controls and safety enquiries can be realised much easier and safer in C.

● 40
Chapter 4 • First Steps in Programming

Since these areas of application hardly play a role for non-professional users, though, the
speed disadvantage is hardly significant.

Python has also gained special importance in the highly topical field of artificial intelligence
(AI). Through extensive libraries such as NumPi, SciPi etc. and distributions such as Anacon-
da, Python has become the most popular programming language by far. All doors are there-
fore open for the experienced Python user. From hardware-related controller programming
to AI applications — with Python there are no limits to intuition and creativity.

In this chapter the basics of MicroPython will be compiled. You should have a functional
programming environment available, because the commands and instructions are always
illustrated with practical examples. These can then be immediately tested directly on the
target hardware, i.e. the ESP32. This does not remain a purely theoretical programming
course, but the knowledge acquired can be immediately put into practice.

4.1 Never without: Comments


Explanatory comments are important in any programming language. This is the only way to
know months or years later what a certain program section does, without having to delve
into old details over and over again.

It is not necessary to comment each program line individually. Experienced coders should
be able to understand individual instructions without comment. Only in the case of special
constructs or unusual or innovative lines of code is a single line comment recommended. For
subprograms or whole logical program sections on the other hand, a short explanation of how
they work should not be missing.

Simple comments will be introduced with the # sign. They begin with # and end with the
end of the line:

>>> print("hello ESP32") # this is a comment


hello ESP32

Multi-line comments can also be marked with a triple double-quate (") character ("""). The
same character string then ends the comment:

"""
first comment line
second comment line
"""

In practice this may look like this:

'''
This is a multi-line comment.
Prints "hello world".
'''

● 41
MicroPython for Microcontrollers

print("hello world")

Alternatively, the commentary function can be used in Thonny. It allows to mark several
lines as comments at the same time with the # (hash) sign.

Figure 4.1: Comment function in Thonny.

The commentary function is also very suitable for commenting-out certain parts of the pro-
gram. If, for example, when testing a more extensive code, certain sections are not to be exe-
cuted on a trial basis, these can be marked with comment signs. The lines are then no longer
observed by the interpreter. This makes a time-consuming deletion and later reinsertion of
the program sections unnecessary.

Comments help beginners in particular to gain a better understanding of the program


structure. From the technical point of view the interpreter ignores all comments, i.e. they
have no influence on the program flow.

4.2 The Print() statement


Information can be output to the terminal using the print() instructions. The command can
be executed directly in the terminal:

Figure 4.2: Print command in the console.

On the other hand, it is used in programs to output text-based information:

● 42
Chapter 4 • First Steps in Programming

Figure 4.3: Print command as program instruction.

print () can contain several strings divided by ",":

>>> print("hello", "world!")


hello world!

The print() statement performs a line break by default. With

end = ""

this can be suppressed:

print("hello", end=" ")


print("world")

and leads to the following result:

hello world

The following two illustrations illustrate the print instruction versions again in the Thonny-
IDE:

Figure 4.4: Print command as program instruction in Thonny.

● 43
MicroPython for Microcontrollers

Figure 4.5: Print command in the Thonny console.

4.3 Indentations and blocks


MicroPython distinguishes different blocks by indentation. It is not necessary to use curly
braces ("{}") or similar. This is one of the main differences to most other languages like C,
Pascal, Basic etc. The advantage of this method is that one is practically forced to a certain
degree of program structure.

if True:
# block 01
print ("True")
else:
# block 02
print ("False")

The number of spaces for indentations is variable, but the same block must always maintain
the same number of spaces for indentations.

Otherwise, an error message is displayed:

if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") # The different indentation will lead to a runtime error.

This leads to the following message:

>>> %Run -c $EDITOR_CONTENT


Traceback (most recent call last):
File "<stdin>", line 6
IndentationError: unexpected indent

● 44
Chapter 4 • First Steps in Programming

In conditions and loops, blocks are formed in an identical way.

4.4 The hardware under control: digital inputs and outputs


Unlike programming on a PC or a laptop, MicroPython usually focuses on direct access to
hardware functions. Especially the control of individual input/output pins (I/O pins or GPIO
for General Purpose Input Output) is of central importance.

To test the instructions in practice, all you need to do is connect an LED with a series resistor
to the ESP32. The following figure shows the corresponding wiring diagram:

Figure 4.6: Circuit diagram for LED at port 25.

The structure of the circuit on a breadboard looks like this:

Figure 4.7: LED hooked up on port 25.

On the software side, a digital pin must first be initialized. For this purpose, a variable is
created which corresponds to the pin. This is not just a pin number, but a complete object
that knows all aspects of the pin. To use pins, the class "Pin" must be imported from the
module "machine".

From machine import Pin

● 45
MicroPython for Microcontrollers

After that, the initialisation of a single pin can already be done:

led = Pin(25, Pin.OUT)

The number 25 is the GPIO number. This is usually found as a printed circuit board number
near the corresponding pin. The instruction defines the pin as an output.

Figure 4.8: Pin numbers here (here 25 and 26) on the ESP board.

Now the pin can be used:

led.value(1)

This sets the I/O port to "1", i.e. it now carries a voltage of 3.3 V. If everything is connected
correctly, the LED on port 25 will light up after the command is executed via the console.
Resetting the pin to "0" (0 volts) will carry out the following instruction:

led.value(0)

Together with the sleep instruction (see also the following chapter) from the time module
you can now program a LED flasher (blink_simple.py):

# blink_simple.py

from machine import Pin


from time import sleep
led = Pin(25, Pin.OUT)
while True:
led.value(1)
sleep(1)
led.value(0)
sleep(1)

Due to the wait instruction

sleep(1)

the LED now flashes at one-second intervals, i.e. with a period of two seconds or a frequen-
cy of 0.5 hertz.

● 46
Random documents with unrelated
content Scribd suggests to you:
before coming down. My stand was a weathered stump beside the road, against
which I sat on a carpet of moss, without concealment of any kind. At a short distance
lay the grouse, a poor crumpled thing, just as he had wilted under the hawk’s swoop.

Thus a half-hour or more passed comfortably. A gorgeous cock-partridge sauntered


into the open, saw me when I nodded to him, and went slowly off with that graceful,
balancing motion which a grouse affects when he is well satisfied with himself. Then,
as the sun rose, there was a swift-moving shadow, a rustle of pinions; the goshawk
swept down the road in front of me and lit beside his game. He was a handsome
bandit, in full adult plumage; his gray breast was penciled in shadowy lines, while his
back was a foggy blue, as if in his northern home he had caught the sheen of the
heavens above and of rippling waters beneath his flight. His folded wings stood out
squarely from his shoulders with an impression of power, [219]like an eagle’s. There
was something noble in his poise, in his challenging eye, in the forward thrust of his
fierce head; but the spell was broken at the first step. He moved awkwardly,
unwillingly it seemed; his great curving talons interfered with his footing when he
touched the earth.

This time, instead of a rifle, there was a trim shotgun across my knees. The hawk
was mine whether he stood quiet or leaped into swift flight, and feeling sure of him
now I watched awhile, wondering whether he would break up his game with his
claws, as some owls do, or tear it to pieces with his hooked beak. For a moment he
did neither, but stood splendidly alert over his kill. Once he turned his head
completely around over either shoulder, sweeping his piercing glance over me, but
seeing nothing unusual. Then he seized his game in one foot and struck his beak into
the breast, making the feathers fly as he laid the delicate flesh open. When I found
myself weakening, growing sentimental at the thought that it was his last meal, his
last taste of freedom and the wild, I remembered the grouse and got quietly on my
feet. Though busy with his feast, he caught the first shadow of a motion; I can still
see the gleam in his wild eyes as he sprang aloft.

I thought him beyond all harm as he lay on his back, one outstretched wing among
the feathers [220]of his victim; but he struck like a flash when I reached down for him
carelessly. “Take that! and that! and remember me!” he said, driving his weapons up
with astonishing force, a force that kills or paralyzes his game at the first grip. Four of
his needle-pointed talons went to the bone, and the others were well buried in the
flesh of my arm. The old viking had been some time with his ancestors before I pried
him loose.

As for the sense of smell, on which most animals depend for accurate information, I
have tried numerous experiments with deer, moose, bear and other creatures to learn
how far they can wind a man, and how their powers compare one with another.
There is no definite answer to the problem, so baffling are the conditions of observing
these shy beasts; but you are in for some surprises, at least, when you attempt to
solve it in the open. You will learn, for example, that when a gale is blowing the
animals are more at sea than in a dead calm; or that in a gusty wind you can
approach them about as easily from one side as from another. Such a wind rolls and
eddies violently, rebounding from every hill or point or shore in such erratic fashion
that the animals have no means of locating a danger when they catch a fleeting sniff
of it. It is for this reason, undoubtedly, that all game is uncommonly [221]wild on a
windy day: the constant motion of leaves or tossing boughs breeds confusion in their
eyes, and the woodsy smells are so broken by cross-currents that they cannot be
traced to their source. So it has happened more than once on a gusty day that a deer,
catching my scent on the rebound, has whirled and rushed straight at me, producing
the momentary illusion that he was charging.

With a steady but not strong wind blowing in their direction, I have seen deer
become alarmed while I was yet a quarter-mile away; this on a lake, where there was
nothing to interfere with the breeze or the scent. On the burnt lands or the open
barrens I have seen bear and caribou throw up their heads and break away while I
was even farther removed. In a light breeze the distance is much shorter, varying
from fifty to two hundred yards, according to the amount of moisture in the air. On
days that are still or very dry, or when the air is filled with smoke from a forest fire
(the latter soon inflames all sensitive nostrils), the animals are at sea again, and
depend less on their noses than on their eyes or ears.

Another surprising thing is, that the animal’s ability to detect you through his sense of
smell is largely governed by your own activity or bodily condition. Thus, when a man
is perspiring freely or moving quickly, his scent is stronger and [222]travels much wider
than when he is sauntering about. But if a man sits absolutely quiet, a clean man
especially, no animal can detect him beyond a few feet, I think, for the reason that a
resting man is like a resting bird or beast in that he gives off very little body scent,
which remains on the ground close about him instead of floating off on the air
currents. Even when the trees are tossing in a gale there is little stir on the ground,
not in the woods at least, and the closer you hold to Mother Earth the less likelihood
is there of any beast smelling you.

All ground-nesting birds depend for their lives on this curious provision of nature.
Were it not for the fact that practically no scent escapes while they are brooding their
eggs, very few of them would live to bring forth a family in a wood nightly traversed
by such keen-nosed enemies as the fox and the weasel. My old setter would wind a
running grouse or quail at an incredible distance, and would follow him by picking his
scent from the air; but I have taken that same dog on a leash near the same birds
when they were brooding their eggs, and he could not or would not detect them
unless he were brought within a few feet, or (a rare occurrence) unless a creeping
ground-breeze blew directly from the nest into his face. [223]

The same provision guards animals, such as deer and caribou, which build no dens
but leave their helpless young on the ground. Two or three times, after finding a fawn
in the woods, I have tested his concealment by means of my young dog’s nose; and I
may add that Rab will point a deer as stanchly as he points a grouse or woodcock, for
he is still in the happy, irresponsible stage when everything that lives in the woods is
game to him. So long as the fawn remains motionless where his mother hid him, the
dog must be almost on top of him before pointing or showing any sign of game. But
if the little fellow runs or even rises to his feet at our approach (fawns are apt to do
this as they grow older), the dog seems to catch the scent after the first motion; he
begins to cat-foot, his nose up as in following an air trail, and steadies to a point
while he is still many yards away from where the fawn was hiding.

The nose of a wolf is keener than that of any dog I ever knew; yet I once trailed a
pack of wolves that passed within sixteen measured feet of where two deer were
sleeping in a hole in the snow. The wolves were hunting, too, for they killed and
partially ate a buck a little farther on; but the trail said that they had passed close to
these sleeping deer without detecting them. [224]

As for the man-scent, you may judge of that by the violent start or the headlong rush
when an animal catches the first alarming whiff of it. If he passes quietly on his way,
therefore, you may be reasonably sure he has not smelled you. To the latter
conclusion I have been forced many times when I have been watching in the woods,
sitting quiet for hours at a stretch, and a deer or bear or fox, or some other beast
with nose as keen as a brier, has passed at a dozen yards’ distance without a sign to
indicate that he was aware of me. Some of these animals came much nearer; so near,
in fact, that I was scary of a closer approach until I had called their attention to what
lay ahead of them.

So long as you are seen or suspected, you need have little fear of any wild beast
(only the tame or half-tame are dangerous), but a brute that stumbles upon you in an
unexpected place or moment is always a problem. Nine times out of ten he will fall all
over himself in his haste to get away; but the tenth time he may fall upon you and
give you a mauling. Moose, for example, are apt to strike a terrible blow with their
fore feet, or to upset a canoe when the jack-light approaches them; not to attack, I
think, at least not consciously, but in blind panic or to ward off a fancied enemy. So
when I have watched from the shore of a lake [225]and a moose came swinging along
without noticing me, I have risen to my feet or thrown my hat at the big brute when
he was as near as I cared to have him. And more than once, after a tremendous start
of surprise, he has come nearer with his hackles up as soon as he got over the first
effect of my demonstration. Yet when I am roaming the woods that same brute will
catch my scent at from two to five hundred yards, and rush away before I can get
even a glimpse of him.

That the same surprising sense-limitation is upon deer and other game animals may
be inferred from the following experience, which is typical of many others. I was
perched among some cedar roots on the shore of a pond, one September day,
watching a buck with the largest antlers I have ever seen on one of his kind. I had
been some time quiet when he glided out to feed in a little bay, on my right; and my
heart was with him in the wish that he might keep his noble crown through the
hunting season, for his own pleasure and the adornment of the woods and the
confusion of all head-hunters. There was no breeze; but a moistened finger told of a
faint drift of air from the lake to the woods.

As I watched the buck, there came to my ears a crunching of gravel from the
opposite direction, and two deer appeared on the point at my left, [226]heading briskly
down into the bay. They passed between my outstretched feet and the water’s edge,
where the strip of shore was perhaps three yards wide; then they turned in my
direction, seeing or smelling nothing, went slowly up the bank and halted at the edge
of the woods to the right and a little behind me, so close that I dared not move even
my eyes to follow them. I measured the distance afterward, and found that from their
hoof-marks to the cedar root against which I rested was less than eight feet.
Imperceptibly I turned for another look, and saw both deer at attention, their heads
luckily pointed away from me. They were regarding the big buck intently, as if to
question him. They showed no alarm as yet; but they were plainly uneasy, searching
the forest on all sides and at times turning to look over my head upon the breathless
lake. Every nervous action said that they found something wrong in the air, some hint
or taint or warning which they could not define. So they moved alertly into the
woods, halting, listening, testing the air, using all their senses to locate a danger
which they had passed and left behind them.

From such experiences one might reasonably conclude that, like the brooding grouse
or the hidden fawn, a motionless man gives off so little scent that the keenest nose is
at fault until it [227]comes almost within touching distance. If any further proof is
needed, you may find it when you sleep in the open, and shy creatures draw near
without any fear of you. By daylight deer, bear and moose are extremely timid; they
rarely come within eyeshot of your camp, and they vanish at the first sniff which tells
them that you have invaded their feeding-grounds. But when you are well asleep the
same animals will pass boldly through your camp-yard; or they will awaken you, as
they have many times awakened me, when you are tenting or sleeping under the
stars by some outlying pond. If you lie quiet, content to listen, the invading animal
will move freely here or there without concern; but no sooner do you begin to stir,
however quietly, than he catches the warning scent, and a thudding of earth or a
smashing of brush tells the rest of the story.

I recall one night, cloudy and very still, when I slept under my canoe on a strip of
sand beside a wilderness lake. The movement of an animal near at hand awoke me.
In the black darkness I could see nothing; but somehow I knew he was big, and
aside from the crepitation of the sand, which I plainly heard, I seemed to feel the
brute near me. For a moment there was a pause, a dead silence; then came a thump,
a rattlety-bang; the canoe shook as something hit the lower end of [228]it, and the
creature moved away. There was nothing to be done without eyes, so I snuggled the
blanket closer and went to sleep again. In the morning there were the tracks of a
moose, a bull as I judged from the shape of his feet, to say that he had come down
the shore at a fast walk, halted, stepped over the stern of the canoe, and went on
without hastening his pace.

That was odd enough; but more surprising were some tracks on the other side,
between the bow of the canoe and the woods. Very faint and dainty tracks they were,
as if a soft pad had touched the sand here and there in an uneven line; but they told
of a fox who had come trotting along under the bank, and who had passed in the
night without awakening me. That neither he nor the moose had smelled the sleeping
man, or nothing alarming in him at least, is about as near to certainty as you will
come in interpreting animal action.

There is another and not wholly unreasonable hypothesis which may help to explain
such phenomena; namely, that it is not the scent of man but of excitement, anger,
blood-lust or some other abnormal quality which alarms a wild animal. It sounds
queer, I know, to say that anger can be smelled; but it is more than probable that
anger or fierce excitement of any kind distils in the body [229]a kind of poison which is
physical and sensible. Such excitement certainly weakens a man, clogging his system
with the ashes of its hot fires; and there is no reason why it should not smell to earth
as well as to high heaven.

You have but to open your eyes and expand your nostrils for some evidence of this
matter. Bees when angered give off a pungent odor, which is so different from the
ordinary smell of the hive that even your dull nose may detect the change of temper.
The same is true of even cold-blooded reptiles. When you find a rattler or a black-
snake squirming in the sun, you can smell him faintly at a few yards’ distance. Now
stir him up with a pole, or pin him to the earth by pressing a forked stick with short
prongs over his neck. As the snake becomes enraged he pours off a rank odor, very
different from the musky smell that first attracted your notice, and it travels much
wider, and clings to your clothes for an hour afterward. It is not only possible but very
likely, therefore, that strong emotions affect the bodies of all creatures in a way
perceptible to senses other than sight. If so, one man who is peaceable and another
who is angry or highly excited may give off such different odors that a brute with
sensitive nostrils may be merely curious about the one and properly afraid of the
other. [230]

That wild animals instinctively fear the scent of humanity, as such, is probably not
true. The notion arises, I think, from judging the natural animal by those we have
made unnatural by abuse or persecution. Whenever man penetrates a wild region for
the first time he finds, as a rule, that the animals have little fear of him, the tameness
of wild game having been noted with surprise by almost every explorer. It has been
noted also, but without surprise, by saints and ascetics who “for the greater glory of
God” have adopted a life of solitude and meditation, and who have often found the
birds or beasts about their hermitage to be quite fearless of them, and receptive of
their kindness. Not till the abundant flocks and herds of a new region have been
harried and decimated by senseless slaughter do the survivors begin to be fearful and
unapproachable, as we unfortunately know them. Yet even now, no sooner do we
drop our persecution and assume a rational or humane attitude than the wild ducks
come to the boat landing of a winter hotel, deer feed at our haystacks, and bears
come in broad daylight to comfort themselves at our garbage-cans. Such things could
hardly be if the fear of man were an age-old or instinctive inheritance.

Nearer home, on any farm bordering the wilderness, you may see wild deer feeding
quite tamely [231]about the edges of the cleared fields all summer. I recall one such
farm in Maine, where the owner had fifteen acres of green oats waving over virgin
soil—a glorious crop for me, but for him an occasion of lamentation. You could go
through that field at any hour before six in the morning or after six at night and find a
dozen deer with a moose or two making themselves at home. The owner’s cattle
were kept out by a rail fence; but the moose simply leaned against the fence and
went through, while the nimble deer sailed over the obstruction like grasshoppers. On
all such farms the deer have the scent of man almost constantly in their nostrils, and
they are simply watchful, running when you approach too near, but turning after a
short flight to have a look at you. At times you may see them feeding when the scent
of laborers or fishermen blows fairly over them. But when October comes, and the
law is “off,” and wild-eyed hunters appear with guns in their hands and death in their
thoughts, then the same deer quickly become as other and wilder creatures, rushing
off in alarm at the first sniff of an enemy. The fact and the changed action are
evident enough; the only interesting question is, To what extent does the smell of
man change when he changes his peaceable ways?

Two or three times I have had opportunity to [232]test the effect of the human scent
in another way, the first time being when I had the good luck to see a natural child
and a natural animal together. The child, a baby girl just beginning to toddle, was
making a journey by means of a comfortable Indian paukee on my back, and I had
left her in an opening beside a portage trail while I went back to my canoe for a thing
I had forgotten. While I was gone, three deer sauntered into the opening. They saw
the baby, and were instantly as curious about her as so many gossips, a little spotted
fawn especially. The baby saw them, and began creeping eagerly forward, calling or
“crowing” as she went. The deer saw and heard and smelled her every moment; yet
they walked around her with springy steps, now on this side, now on that, showing a
world of curiosity in their bright eyes, but never a sign of fear.

From a distance I watched the lovely scene, kindling at the beauty of it, or feeling a
bit anxious when I saw the sharp feet of the old doe a little too near the sunny head
or the outstretched hands. Then an eddy of wind from the mountain got behind me
and whirled over the deer. They caught the scent and were away with a wild alarm-
call, their white flags flying, and the baby waving by-by as they vanished in the
woods.

Quite naturally, therefore, when a sensitive [233]animal runs away from me, I find
myself thinking that perhaps it is not the smell of humanity but of some evil trait or
quality which frightens him. I first laid down this hypothesis after meeting a strange,
childlike man, who had a passion for roaming by himself in the fields or woods. White
men, after a puzzling acquaintance, would tap their heads or call him crazy; an Indian
would look once in his eyes and say, very softly, “The Great Spirit has touched him.”
He was all gentleness, without a thought or possibility of harm in his nature. He was
also without fear, and perhaps for this reason he inspired no fear in others. When he
appeared in the woods, singing to himself, the animals would watch him for a
moment, and then go their ways quietly, as if they understood him. What would
happen if a race of such men lived near the wood folk must be left to the
imagination.
[235]
My Pond: a Symphony of the Woods
[237]

[Contents]
X
The Trail
To reach my pond you must leave your canoe on the shore of Sungeegamook, the
home lake, and go eastward through the big woods. Yonder is the landing, that bank
of green topped by “everlasting” and blue asters, with a cleft like an arched doorway
in the forest behind it. A rugged jack-pine leans out over a bit of shingle, as if to
indicate a good place to beach your canoe, and there is something curiously alive,
almost sentient, in its attitude. The old tree seems to watch your approach; through
its leaves runs a low murmur of welcome as you step ashore.

Entering the woods (and because you are alone, and therefore natural, something in
their dim [238]aisles, their mysterious depths, their breathing silence, makes you go
gently) you find yourself in an old logging-road, once a garish symbol of man’s
destructiveness, but growing yearly more subdued, more beautiful, since Nature
began her work of healing. The earth beneath your feet, the restful earth which the
lumbermen left torn by iron tools or rent by dynamite, has again put on her soft-
colored garments. Feathery beds of fern push boldly into the road from shadowy
places; wild grasses fill all its sunny openings with their bloom and fragrance; and
winding down through shade or sunshine comes a trail made by the feet of deer and
moose. Already these timid animals have adopted the forgotten road as a runway;
you may meet them here when you return in the evening twilight.

Everywhere beside the trail are old marks of the destroyer. Noble maples or cedars
that were centuries growing have been slashed down, dismembered, thrust aside to
decay, and all because they stood in the way of a lumber-boss who thought only of
getting his cut of spruce down to the lake. To look upon such trees, dead and shorn
of their beauty, is to feel pity or indignation; but Nature does not share your feeling,
being too abundant of life and resource to waste any moment in regret. Already she
is upbuilding what man [239]has torn down. Glaring ax-wounds have all disappeared
under bandages of living moss; every fallen log has hidden its loss under a mantle of
lichen, soft and gray, which speaks not of death but of life renewed.

Where the sun touches these prostrate giants a blush of delicate color spreads over
them. See, it deepens as you look upon it curiously, and you examine it to find a
multitude of “fairy-cups” on slender stems, each lifting its scarlet chalice to the light.
Very soft and inviting seats they offer, yielding to your weight, sending up an odor as
of crushed herbs; but do not accept the invitation. If you must halt to rest or to enjoy
the stillness, sit not down on one of these mossy logs, but before it at a little
distance, and let its blended colors be to your eye what the wind in the pine is to
your ear, or the smell of hemlock to your nostrils. Then will all your senses delight in
harmony, their natural birthright, while you rest by the way.

Where the old road winds about the end of a ridge, avoiding every steep pitch, young
balsams are crowding thickly into it; where it turns downward to the lowlands, quick-
growing alders claim it as their own; and as you leave the lake far behind it begins to
divide interminably, each branch breaking into smaller branches, like the twigs of a
tree as you trace them outward. The [240]twig ends with a bud in clear space; but the
farther or landward end of a logging-road dwindles to a deer-path, the path to a
rabbit-run, and the run vanishes in some gloomy cedar swamp or trackless thicket
where is no outlook on any side.

It is in such places, while you puzzle over another man’s road instead of keeping your
own trail straight, that you are most apt to get lost. Coming back you need have no
fear of going astray, since all these trails lead to the main road, and thence downhill
to the lake; but going forward it is well to steer clear of all branch roads, which lead
nowhere and confuse the sense of direction.

Leaving the road behind, therefore, and heading still eastward, you cross a ridge
where the hardwoods stand, as their ancestors stood, untouched by the tools of men.
Immense trunks of beech or sugar-maple or yellow birch tower upward wide apart,
the moss of centuries upon them; far overhead is a delicate tracery of leaves, a dance
of light against the blue, and over all is the blessed silence.

Beyond the ridge the ground slopes downward to a uniform level. Soon the moss
grows deeper underfoot, with a coolness that speaks of perpetual moisture. The
forest becomes dense, almost bewildering; here a “black growth” of spruce or fir,
there a tangle of moosewood, yonder a swale [241]where impenetrable alder-thickets
make it impossible to hold a straight course. Because all this growth is useless to the
lumberman, there is no cutting to be seen; but because I have passed this way
before, instinctively following the same course like an animal, a faint winding trail
begins to appear, with a bent twig or a blazed tree at every turn to give direction.

As you move forward more confidently, learning the woodsman’s way of looking far
ahead to pick up the guiding signs before you come to them, the dim forest suddenly
brightens; a wave of light runs in, saying as it passes overhead that you are near an
opening. As if to confirm the message, the trail runs into a well-worn deer-path,
which looks as if the animals that used it knew well where they were going. Clumps
of delicate young larches spring up ahead; between them open filmy vistas, like
windows draped in lace, and across one vista stretches a ribbon of silver. A few more
steps and—there! my little pond is smiling at you, reflecting the blue deeps of heaven
or the white of passing clouds from its setting of pale-green larch-trees and crimson
mosses.

And now, if you are responsive, you shall have a new impression of this old world, the
wonderful impression which a wilderness lake gives at the moment of discovery, but
never again afterward. [242]As you emerge from cover of the woods, the pond seems
to awaken like a sleeper. See, it returns your gaze, and on its quiet face is a look of
surprise that you are here. Enjoy that first awakening look; for there is more of
wisdom and pleasure in it, believe me, than in hurrying forth blindly intent on making
a map or catching a trout, or doing something else that calls for sight to the neglect
of insight. All sciences, including chartography and angling, can easily be learned by
any man; but understanding is a gift of God, and it comes only to those who keep
their hearts open.

Your own nature is here your best guide, and it shows you a surprising thing: that
your old habitual impressions of the world have suddenly become novel and strange,
as if this smiling landscape were but just created, and you were the first to look with
seeing eyes upon the glory of it. It tells you, further, if you listen to its voice, that
creation is all like this, under necessity to be beautiful, and that the beauty is still as
delightful as when the evening and the morning were the first day. This dance of
water, this rain of light, this shimmer of air, this upspringing of trees, this blue heaven
bending over all—no artist ever painted such things; no poet ever sang or could sing
them. Like a mother’s infinite tenderness, they await your appreciation, your silence,
your [243]love; but they hide from your description in words or pigments.

Finally, in the lowest of whispers, your nature tells you that the most impressive and
still most natural thing in this quiet scene is the conscious life that broods silently
over it. As the little pond seems to awaken, to be alive and sentient, so also does that
noble tree yonder when you view it for the first time, or that delicate orchid wafting
its fragrance over the lonely bog. Each reflects something greater than itself, and it is
that greater “something” which appeals to you when you enter the solitude. Your
impressions here are those of the first man, a man who found many beautiful things
in a garden, and God walking among them in the cool of the day. Call the brooding
life God or the Infinite or the Unknown or the Great Spirit or the Great Mystery—what
you will; the simple fact is that you have an impression of a living Being, who first
speaks to you in terms of personality that you understand.

So much, and more, of eternal understanding you may have if you but tarry a
moment under these larches with an open mind. Then, when you have honored your
first impression, which will abide with you always, you may trace out the physical
features of my pond at leisure. Just here it is not very wide; your eye easily overlooks
it to rest [244]with pleasure on a great mound of moss, colored as no garden of
flowers was ever colored, swelling above the bog on the farther shore. On either
hand the water sparkles wider away, disappearing around a bend with an invitation to
come and see. To the left it ends in velvety shadow under a bank of evergreen; to the
right it seems to merge into the level shore, where shadow melts with substance in a
belt of blended colors. A few yards back from the shore groups of young larches lift
their misty-green foliage above the caribou moss; they seem not to be rooted deep in
the earth, but to be all standing on tiptoe, as if to look over the brim of my pond and
see their own reflections. Everywhere between these larch groups are shadowy
corridors; and in one of them your eye is caught by a spot of bright orange. The spot
moves, disappears, flashes out again from the misty green, and a deer steps forth to
complete the wilderness picture with the grace of life.

Such is my pond, hidden away in the heart of a caribou bog, which is itself well
hidden in dense forest. Before I found it the wild ducks had made it a summer home
from time immemorial; and now, since I disturb it no more, it is possessed in peace
by a family of beavers; yet I still think of it as mine, not by grace of any artificial law
or deed, but by the more ancient right of possession [245]and enjoyment. A hundred
lakes by which I have tented are greater or more splendid; but the first charm of any
wilderness scene is its solitude, and on these greater lakes the impression of solitude
may be broken by the flash of a paddle-blade in the sun, or the chuck of an ax under
the twilight, or the gleam of a camp-fire through the darkness. But here on my pond
you may know how Adam felt when he looked abroad: no raft has ever ruffled its
surface; no ax-stroke or moan of smitten tree has ever disturbed its quiet; no camp-
fire has ever gleamed on its waters. Its solitude is still that of the first day; and it has
no name, save for the Indian word that came unbidden at the moment of finding it,
like another Sleeping Beauty, in the woods.

Do you ask how I came to find my pond? Not by searching, but rather by the odd
chance of being myself lost. I had gone astray one afternoon, and was pushing
through some black growth when an alarm rose near at hand. A deer whistled loudly,
crying “Heu! heu! heu!” as he jumped away, and on the heels of his cry came a
quacking of flushed ducks.

Till that moment I thought I knew where I was; but the quacking brought doubt, and
then bewilderment. If a duck tells you anything in the woods, he tells you of water,
plenty of it; but the [246]map showed no body of water nearer than Big Pine Pond,
which I had fished that day, and which should be three or four miles behind me.
Turning in the direction of the alarm, I soon broke out of the cover upon a caribou
bog, a mysterious expanse never before suspected in that region, and before me was
the gleam of water in the sunshine. “A pond, a new one, and what a beauty!” I
thought with elation, as I caught its awakening look and feasted my eyes on its glory
of color. Then I gave it an Indian name and hurried away; for I was surely off my
course, and the hour was late for lingering in strange woods. Somewhere to the west
of me was the home lake; so westward I headed, making a return-compass of bent
twigs, till I set my feet in a branch of the old logging-road. And that chance trail is
the one I have ever since followed.

[247]

[Contents]
XI
Woodsy Impressions
Next morning I returned to explore my find at leisure. One part of that exploration
was to go completely around the bog, to learn its guiding landmarks and compass-
bearings; but an earlier and better part was to sit quietly beside my pond to hear
whatever it might have to say to me. If that last sounds fanciful, remember that
many things are voiceless in this world, but few are wholly dumb. Of the numberless
ponds that brighten the northern wilderness, some were made by beavers, others by
flood or glacier or earthquake, and no two of them tell the same story or make the
same impression. They are like so [248]many unspoiled Indians, whom we regard from
a distance as being mysteriously alike, but who have different traditions, ideals,
personalities, and even different languages.

I know not what the spell of any lonely place may be when you make yourself part of
it; I only know that it stirs one strangely, like the flute note of a wood-thrush or a
song without words. Though I never met with an adventure on my little pond, never
cast a fly to learn whether any trout lurked in its waters, never thought of firing a
shot at its abundant game, yet season after season I returned to it expectantly, and
went away satisfied. Such a pond has a charm of its own, a spell which our forebears
sought to express in terms of nymphs or puckwudgies or water-sprites. It grows a
better crop than trout, attracts a finer game than deer or water-fowl, and you can
seldom visit it without learning something new about your natural self or the wood
folk or the friendly universe.

Thus, it happens on a day when you are waiting beside your pond, or wending your
way to it, that a moose or a fox or a dainty grouse appears unexpectedly near you;
and instantly, without thought or motive, you “freeze” in your tracks or, if you are not
seen, shrink deeper into the shadow for concealment. The action is natural,
involuntary, instinctive, precisely like the action of a [249]young deer under similar
circumstances; but when it is over you understand it, and smile at finding yourself
becoming more and more like other natural creatures,—going softly, that is, making
yourself inconspicuous without trying or knowing how, and having no thought of
harm to any bird or beast, but only of watching him or gauging his course while
remaining yourself unseen. Only by some such method can you learn anything worth
knowing about a wild animal: books describe, naturalists classify and sportsmen kill
him; but to understand him you must be a sharer of his quiet ways.

Comes another day, a day when you are in love with solitude itself, when you learn
with surprise that a man is never lonely when alone in the woods; that ideals may be
quite as companionable as folks; and that around you in a goodly company are
beauty, peace, spacious freedom and harmonious thoughts, with a hint also, to some
minds, of angels and ministers of grace. The Attendant Spirit of “Comus,” the Ariel of
“The Tempest,” the good fairies of all folk,—these are never understood in the town,
nor in the woods unless you enter them alone.

At a later time, and with a thrill of great wonder, you may discover the meaning of
silence, and of the ancient myth of a lovely goddess of silence; not the dead silence
of a dungeon, which may roar [250]in a man’s ears till it deafens him or drives him
mad, but the exquisite living silence of nature, a silence which at any moment may
break into an elfin ringing of bells, or into a faintly echoing sound of melody, as if
stars or unseen beings were singing far away.

This impression of melody is often real, not illusory, and may be explained by the
impact of air-currents on resonant shells of wood, hundreds of which fall to humming
with the voice of ’cellos and wind-harps; but there is another experience of the
solitude, more subtle but none the less real, for which only the psychologist will
venture to give an accounting. Once in a season, perhaps, comes an hour when, no
matter what your plans or desires may be, your mind seems intent on some unrelated
affair of its own. As you hurry over the trail, you may be thinking of catching a trout
or stalking a buck or building a camp or getting to windward of a corporation;
meanwhile your subconscious mind, disdaining your will or your worry, is busily
making pictures of whatever attractive thing it sees,—radiant little pictures, sunshiny
or wind-swept, which shall be reproduced for your pleasure long after the important
matters which then occupied you are clean forgotten.

Here is the story of one such picture, a reflection, no doubt, of the primitive trait or
quality called [251]place-memory, which enables certain animals or savages to
recognize any spot on which their eyes have once rested.

One late afternoon, years after I had found my pond, I crossed the mountain from
distant Ragged Lake, heading for the home lake by a new route. There was no trail;
but near the foot of the western slope of the hills I picked up an old lumber road
which seemed to lead in the right direction. For a time all went well, and confidently;
but when the road dipped into an immense hollow, and there showed signs of
petering out, I followed it with increasing doubt, not knowing where I might come out
of the woods or be forced to spend the night. As I circled through a swale, having left
the road to avoid a press of alders that filled it, an ash-tree lifted its glossy head
above a thicket with a cheery “Well met again, pilgrim! Whither away now?”

It was a surprising hail in that wild place, suggestive of dreams or sleep-walking; but
under the illusion was a grain of reality which brought me to an instant halt. After
passing under thousands of silent trees all day, suddenly here was one speaking to
me. And not only that, but wearing a familiar look, like a face which smiles its
recognition of you while you try in vain to place it. Where, when had I seen that tree
before? No, [252]impossible! I had never before entered this part of the vast forest.
Yet I must have seen it somewhere, or it could not now stir a familiar memory.
Nonsense! just a trick of the imagination. I must hurry on. Thus my thoughts ran, like
a circling hare; and all the while the ash-tree seemed to be smiling at my perplexity.

The man who ignores such a hint has much to learn about woodcraft, which is largely
a subconscious art; so I sat down to smoke a council-pipe with myself and the ash-
tree over the matter. No sooner was the mind left to its own unhampered way than it
began to piece bits of a puzzle-picture deftly together; and when the picture was
complete I knew exactly where I was, and where I might quickly find a familiar trail.
Eight years before, in an idle hour when nothing stirred on my pond, I had explored a
mile or so beyond the bog to the south, only to find a swampy, desolate country
without a trail or conspicuous landmark of any kind. It was while I passed through
this waste, seeking nothing in particular and returning to my pond, that the mind
took its snapshot of a certain tree, and preserved the picture so carefully, so minutely,
that years later the original was instantly recognized. Many similar ash-trees grew on
that flat, each with its glossy crown and its gray shaft flecked by dark-green moss;
what [253]there was in this one to attract me, what outward grace or inward tree-
sprite, I have not yet found out.
His massive head thrust forward as he tried to penetrate the far
distance with his near-sighted eyes.

[253]

Another subconscious record seems to have been made for beauty alone, with its
consequent pleasure, rather than for utility. As I watched my pond one summer
morning, intent on learning what attracted so many deer to its shores, the mind
apparently chose its own moment for making a perfect picture, a masterpiece, which
should hang in its woodsy frame on my mental wall forever. The sky was wondrously
clear, the water dancing, the air laden with the fragrance of peat and sweet-scented
grass. Deer were slow in coming that morning, and meanwhile nothing of
consequence stirred on my pond; but there was still abundant satisfaction in the
brilliant dragon-flies that balanced on bending reeds, or in the brood of wild ducks
that came bobbing out like young mischief—makers from a hidden bogan, or even in
the face of the pond itself, as it brightened under a gleam of sunshine or frowned at a
passing cloud or broke into a laugh at the touch of a cat’s-paw wind. Suddenly all
these pleasant minor matters were brushed aside when a bush quivered and held still
on the farther shore.

All morning the bushes had been quivering, showing the silvery side of their leaves to
every [254]breeze; but now their motion spoke of life, and spoke truly, for out from
under the smitten bilberries came a bear to stand alert in the open. The fore part of
his body was lifted up as he planted his paws on a tussock; his massive head was
thrust forward as he tried to penetrate the far distance with his near-sighted eyes. He
was not suspicious, not a bit; his nose held steady as a pointing dog’s, instead of
rocking up and down, as it does when a bear tries to steal a message from the air. A
moment he poised there, a statue of ebony against the crimson moss; then he leaped
a bogan with surprising agility, and came at his easy, shuffling gait around a bend of
the shore. Opposite me he sat down to cock his nose at the sky, twisting his head as
he followed the motion of something above him, which I could not see,—a hornet,
perhaps, or a troublesome fly that persisted in buzzing about his ears. Twice he
struck quickly with a paw, apparently missing the lively thing overhead; for he
jumped up, rushed ahead violently and spun around on the pivot of his toes. Then he
settled soberly to his flat-footed shuffle once more, and disappeared in a clump of
larches, which seemed to open a door for him as he drew near.

For me that little comedy was never repeated, though I saw many another on dark
days or bright; [255]and the last time I visited my pond I beheld it sadly altered, its
beauty vanished, its shores flooded, its green trees stark and dead. Unknown to me,
however, the mind had made its photographic record, and always I see my pond, as
on that perfect day, in its setting of misty-green larches and crimson bog. Again its
quiet face changes, like a human face at pleasant thoughts, and over it comes to me
the odor of sweet-scented grass. The sunshine brightens it; the clouds shadow it;
brilliant dragon-flies play among its bending reeds; the same brood of ducklings
glides in or out from bogan to grassy bogan; and forever the bear, big and glossy
black, goes shuffling along the farther shore.
[256]

[Contents]
XII
Larch-trees and Deer
One of the subtler charms of my pond, a thing felt rather than seen, was a certain air
of secrecy which seldom left it. In every wilderness lake lurks a mystery of some kind,
which you cannot hope to penetrate,—a sense of measureless years, of primal far-off
things, of uncouth creatures dead and gone that haunted its banks before the infancy
of man; but on this little pond, with its sunny waters and open shore, the mystery
was always pleasant, and at times provoking, as if it might be the place where an end
of the rainbow rested.

Though small enough to give one a sense of possession (one can never feel that he
owns a big [257]lake, or anything else which gives an impression of grandeur or
sublimity), my pond had a mischievous way of hinting, when you were most
comfortable, that it was hiding a secret; that it might show you, if it would, a much
better scene than that you looked upon. It was shaped somewhat like an immense
pair of spectacles, having two lobes that were flashing bright, with a narrow band of
darker water between; and, what with its bending shores or intervening larches, you
could never see the whole of it from any one place. So, like eyes that hide their
subtlest lights of whim or fancy under glasses, it often seemed to be holding
something in reserve, something which it would not reveal unless you searched for it.
After watching awhile from one beautiful or restful spot, you began to feel or imagine
that some comedy was passing unseen on the other half of the pond; and though
you resisted the feeling at first, sooner or later you crept through the screen of
larches to know if it were true.

On every side of the pond save one, where a bank of evergreen made velvet shadows
intermingled with spots of heavenly blue, the shores were thickly spread with mosses,
which began to color gloriously in midsummer, the colors deepening as the season
waned, till the reflecting water appeared as the glimmering center of a gorgeous
[258]Oriental rug. Along the edges of this rug, as a ragged fringe, stood groups of
larches in irregular order,—little fairylike larches that bore their crown of leaves not as
other trees bear them, heavily, but as a floating mist or nebula of sage green. Like
New England ladies of a past age they seemed, each wearing a precious lace shawl
which gave an air of daintiness to their sterling worth. When the time came for the
leaves to fall, instead of rustling down to earth with a sound of winter, mournfully,
they would scamper away on a merry wind, mingling their fragrance with that of the
ripened grass; and then the twigs appeared plainly for the first time, with a little knot
or twist in every twig, like toil-worn fingers that the lace had concealed.
Here or there amid this delicate new growth towered the ruin of a mighty tamarack,
or ship-knee larch, such as men sought in the old clipper-ship days when they needed
timbers lighter than oak, and even tougher to resist the pressure of the gale or the
waves’ buffeting. Once, before the shipmen penetrated thus far into the wilderness,
the tamaracks stood here in noble array, their heads under clouds, beckoning hungry
caribou to feed from the lichens that streamed from their broad arms above the
drifted snow; now most of them are under the moss, which covered them
[259]tenderly when they fell. The few remaining ones stand as watch-towers for the
hawks and eagles; their broken branches make strange sepia drawings of dragon-
knots and hooked beaks on the blue sky. A tiny moth killed all these great larches;
the caribou moved northward, leaving the country, and the deer moved in to take
possession.

This and many other stories of the past my little pond told me, as I watched from its
shores or followed the game-trails that were spread like a net about its edges. Back
in the woods these trails wandered about in devious fashion, seeking good browse or
easy traveling; while here or there a faint outgoing branch offered to lead you, if your
eyes were keen, to the distant ridge where a big buck had his daily loafing-place. On
the bog the trails went more circumspectly, uniting at certain places in a single deep
path, a veritable path of ages, which was the only path that might safely be followed
by any creature with more weight than a fox. The moment you ventured away from it
the ground began to shiver, to quake alarmingly, to sink down beneath your feet.
Only a thin mat of roots kept you afloat; the roots might anywhere part and drop you
into black bottomless ooze, and close forever over your head. A queer place, one
might think, for heavy beasts to gather, and so it was; but the old caribou-trails
[260]or new deer-paths offered every one of them safe footing.

At first these game-trails puzzled me completely, being so many and so pointless.


That they were in constant use was evident from the footprints in them, which were
renewed almost every morning; yet I never once saw a deer approach the water to
drink or feed. Something else attracted them; a highway from one feeding-ground to
another, it might be, or the wider outlook which brings deer and caribou out of their
dim woods to sightly places; but there was no certainty in the matter until the
animals themselves revealed the secret. One day, when a young buck passed my
hiding-place as if he were going somewhere, I followed him to the upper or southern
end of the pond. There he joined four other deer, which were very busy about a
certain spot, half hidden by low bushes, a couple of hundred yards back from the
shore. And there they stayed, apparently eating or drinking, for a full half-hour or
more.
When the deer were gone away, I went over and found a huge spring, to which
converged a dozen deep trails. Like the hub of an immense wheel it seemed: the
radiating paths were the spokes, and somewhere beyond the horizon was the unseen
rim. From the depths of the spring came a surprising [261]volume of clear, coffee-
colored water, bubbling over joyously as it leaped from the dark earth into the light,
and then stealing quietly away under bending grasses to keep my pond brim full.
Around the spring the earth was pitted by the feet of deer, and everywhere about its
edges were holes lapped in the peat by eager tongues. Here, beyond a doubt, was
what called so many animals to my pond,—a mineral spring or salt-lick, such as we
read about in stories of pioneer days, when game was everywhere abundant, but
such as one now rarely finds.

After that happy discovery I shifted my blind to another larch with low-drooping
branches, beneath which one might rest comfortably and look out through a screen
of lace upon a gathering of the deer. They are creatures of habit as well as of
freedom; and one of their habits is to rest at regular intervals, the hours being hard
to forecast, since they vary not only with the season of lengthening or shortening
days, but also each month with the changes of the moon. Thus, when the moon fulls
and weather is clear, deer are abroad most of the night. At dawn they seek their day-
beds, instinctively removing far from where they have left their scent in feeding; and
during the day they are apt to remain hidden save for one brief hour, when they take
a comforting [262]bite here or there, giving the impression that they eat now from
habit rather than from hunger. As the moon wanes they change their hours to take
advantage of its shining; and on the “dark of the moon” they browse only in the early
part of the night, then rest many hours, and have two periods of feeding or roaming
the next day.

Such seems to be the rule in the North, with plenty of exceptions to keep one
guessing,—as in the November mating-season, when bucks are afoot at all hours; or
during a severe storm, which keeps deer and all other wild animals close in their
coverts.

Because of this regularity of habit at irregular hours, the only certainty about the salt-
lick was that the animals would come if one waited long enough. As I watched
expectantly from my larch bower, the morning shadows might creep up to me, halt,
and lengthen away on the other side, while not a deer showed himself in the open.
Then there would be a stir in the distant larches, a flash of bright color; a doe would
emerge from one of the game-trails, hastening her springy steps as she neared the
spring. As my eyes followed her, noting with pleasure her graceful poses, her
unwearied alertness, her frequent turning of the head to one distant spot in the
woods where she had left her fawn, there would come another [263]flash of color from
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!

ebookgate.com

You might also like