0% found this document useful (0 votes)
80 views

Chapter 5 Micropython

Uploaded by

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

Chapter 5 Micropython

Uploaded by

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

Chapter 5 MicroPython (5-1) to (5 24)

5.1 Introduction.. 5-2


5-2
5.2Difference between MicroPython and Python.
5.3 Installation of MicroPython on Hardware.. 5-2

5.3.1 MicroPython Hardware. ...5 -3

..5-3
5.3.1.1 The Pyboard..
5.3.1.2 ESP32... ..5 -3

5.3.1.3 BBC Micro Bit... .5-3

5.3.2 CircuitPython... . 5 -44

5.3.3 MicroPython Workflow.. 5-4

5.3.3.1 REPL.. ********** *** .5-4

5.3.3.2 Command-Line Tools. 5-5

5.3.3.3 Integrated Development Environments (IDEs). .5-5

..5 - 5
5.3.4 Installing MicroPython on Different Hardware .

5.3.5 Install the Anaconda Distribution of Python.. .5-7

5.4 MicroPython Libraries. 5-16

5.5 GPIO Programming on MicroPython Hardware. . 5 -17


5.6 Sensor Programming using MicroPython... 5-22

Solved Model (M-1) to (M -2)


Question Paper

JENIL THAKKAR
5 MicroPython

Syllabus between MicroPython and Python, Installation of


MicroPython: Introduction, main difference
MicroPythonm on Hardware, MicroPython libraries, GPIO programming on MicroPython
Hardware, Sensor Programming using MicroPytho

Contents
5.1 Introduction
52 Diference between MicroPython and Python
5.3 Installation of MicroPython on Hardware
54 MicroPython Libraries
6.5 GPIO Programming on MicroPython Hardware
5.6 Sensor Programming
using MicroPython

(5- 1)
JENIL THAKKAR
Python Programming 5-2
icroPython
5.1 Introduction
MicroPython includes the standard Python interpreter that runs on small embedded
development boards. With MicroPython, you can write Python scripts to control
hardware. For example, you can make LEDs
blink, communicate with a temperature
sensor, control motors and publish a sensor
reading on the Internet. It is worth noting
that the firmware for such embedded devices is
generally coded in Assembly, C or C++,
but using
MicroPython you can achieve almost the same results as with high level
Python
5.2 Difference between MicroPython and Python
Unlike the desktop version of Python, MicroPython is a
stripped down version for
microcontrollers; therefore, it doesn't support all the
Python libraries and functionalities.
In the world of
microcontrollers, the firmware is directly burned to the ROM (also known
as
program memory), and there is no file system.
MicroPython implements a minimal
type of file system directly on the Flash memory of the microcontrollers. If the device has
1 MB or more of
storage, then it will be set up (upon first boot) to contain a file
This file system.
system uses the FAT format and is stored in
the Flash memory by the
MicroPython firmware. This gives users the benefit of
being able to access, read and write
files within the main Python
program for flexible storage operations.
5.3 Installation of MicroPython on Hardware
MicroPython is a compact implementation of the Python 3
programming
designed to work with microcorntrollers. Initially announced back language
in 2013 as part ot a
Kickstarter project created by Damien George,
MicroPython eventually became one ot the
preferred firmware options for microcontroller programmers and enthusiasts
Damien ended up created his own line of
alike
hardware that comes equipped wiu
MicroPython right off the bat. However, the firmware can also be installed on a wiae
range of other boards.
If you're interested in
making a career out of hardware programming or simpiy want
to do it as a hobby, you'l have a lot to
gain by learning how to work with MicroPython
with MicroByu
In this beginner's guide, we're going to teach re
you the basics about compatible haraw
and workflow, as well as show you a couple of practical examples or w

microcontroller can be programmed with the help of MicroPython. Without further a


let's jump right into it.

TECHNICAL PUBLICATIONS An up thrust

JENIL THAKKAR
for knowledge
5-3
PpthonProgramming

MicroPython
631MicroPython Hardware

a d y to give MicroPython a chance, ie's time to start looking into some


f you're
options.
options. Plenty
hardware
ot boards
of out there are compatible with the
programming
hint as it's often the case with these types of things, some products are a bit
language, but
an others. And, of course, some are much more expensive than others. Picking
etter
he right board for your project is very important, so let's take a look at a few of the most
available on the market right now.
solid options

S831.1 The Pyboard


The Pyboard was developed and optimized by Damien George and some of the other
developers that contributed to the MicroPython project. As such, it's arguably the best
opton if you're looking for a specialized board to work with MicroPython. If you head
over to the MicroPython store, you'll find various Pyboards to choose from along with
housings, skins, adapters, and peripherals.
yboards are based on the STM32 series of microcontrollers and come equipped with a
CortexM4F CPU and 128 K of RAM or more, depending on the model. Other highlights
mciude a micro USB connector, micro SD card slot, and an accelerometer, among other
features.

53.12 ESP32
ESP32 is a high-performance, low-cost series of microcontrollers that come with a wide
variety
of features, including built-in Wi-Fi and Bluetooth capabilities. The specs include
520 KSRAM
and a CPU clocked at either 160 or 240 MHz, depending on the model. The
ESP32 DOards are quite powerful for their size and feature lots of extras like power
magement modules, antenna switches, power amplifiers, filters, and more.
Though the price of the chip itself is quite affordable, you may have to purchase the
avarious modules separately and there are many to choose from. Not necessarily the best
choice
ginners,but
ib done. if you know what you're doing, the ESP32 can definitely get the
If
you'
mayrewant
eatures, you1ay looking for cheaper option
a and don't mind out on some
missing
to check out ESP32's predecessor, the ESP8266 series.

5313 BBC Micro:Bn


Micro : Bit isan open-source Arm-based microcontroller designed primarily
for
eucz onal
pOSes. The compact device is quite popular in the U.K., where it was
Tely dist purposes.
ely com
distributed
to over
Snal size, theedto
A over 1 million Brit and students back in 2016. Despite
teachers
its

impressive array of features, including


an
4Comes equipped with an

TECHNICAL PUBLICATIONs- An up thrust for knowledge

JENIL THAKKAR
Python Programming 5-4
AicroPython
accelerometer, Bluetooth connectivity, microUSB, two programmable buttons. ed
connector, and more. The Micro : Bit is aimed at children between the ages of 7 and dge
but you
14
can
definitely made good use of the board even if you're a lot older.

5.3.2 CircuitPython
CircuitPython is a project that's quite similar to MicroPython in the sense that it was
also designed to make hardware
programming as simple and as accessible as possible.
CircuitPython is fully compatible with the Pyboard, as well as a wide variety of other
microcontrollers, including a number of boards developed by
open-sOurce hardware
company Adafruit. The company's flagship board goes by the name of
Circuit
Playground Express and comes equipped with all of the features a beginner needs to
started with hardware get
programming. A few of the highlights include motion sensor,
temperature sensor, mini speaker with class D amplifier, infrared receiver, RGB
USB port, and more. LEDs,

5.3.3 MicroPython Workflow


Getting
started with hardware
programming may
but working with
seem
intimidating at first glance, ,
MicroPython is actually pretty straightforward. That's because
MicroPython comes with a handful of tools that greatly simplify the whole process.
5.3.3.1 REPL
REPL (Read-Eval-Print Loop) is an interactive programming environment that takes
user inputs and returns results after
evaluating them. Depending on the type of hardware
you're working with, you may have MicroPython along with REPL already installed on
your device. If not, you can start up a REPL session in
one of two
is to use the WebREPL on the ways. The simplest way
official
with your microcontroller. MicroPython website and establish a connecuion
However, this only works with boards
The second method involves that support Wi-t1.
using serial terminal connection. Linux users uld
a
probably be most familiar with this process. w
However, you can start a serial REPL S
regardless of your operating system. If you're using
Linux, simply open the termina and
type the command below to get a list of active
serial connections.
$ ls /dev/tty.*
Take a look at the list and make note of your add
device's name and hen,
baud rate. 1ne
them both at the end of the command mentioned i're
earlier. If you're on MacOS and
using the Screen application as your terminal, the command will look something likey this:

$ screen /dev/tty.wchusbserial1430 115200

TECHNICAL PUBLICATIONS An up thrust for knowledge


JENIL THAKKAR
5-5
athanogIamning MicroPython
Windows, on the other hand, a bunch of terminal emulators are
available
Myou'e

mder, Terminus,
o t r y ,i n c h u d i n g C m d e Xshell, and of course, PuTTY, which is the
go-to
users.
most

for
Ogram
EPL connectionis established, you can enter and execute commands
CnceyourR E
using
oneactivempt. MicroPython's REPL was designed with accessibility in mind and
prompt. Mica
the
interact

a8
S u c hi n c h u d
some very useful features like tab completion, paste mode, history, auto-
i n d e n t ,a n d m o r e .

332Command-Line Tools

vboard.py is a
standalone
one tool that lets you run Python scripts or commands on a
Dthon device and inc
levice and includes a few other neat features. While the tool was designed
MicroPython

ith
w
the Pyboard, it's also compatible with other microcontrollers that support
towork

ow REPL. This includes the ESP32 and ESP8266 series, which we mentioned in
ion 5.3.1.2. A few other useful command-line tools you may want to try are RShell,
section
Upvdev, and Ampy.

6833 Integrated Development Environments (IDEs)


Abunch of plugins let you add MicroPython support to your interactive development
environunent. f you're working with PyCharm, which is available on Windows, Linux,
and macOS, you can go directly to the marketplace to find a plugin known simply as
MicroPython. Mu Editor and uPyCraft are a couple of other good options you may want
o look into. Regardless of which plugin you use, you'll need to connect to your device
LSing the serial port. If everything goes well, you'll be able to interact with the

MicroPython REPL from IDE.

34 Installing MicroPython on Different Hardware


yOu Te going with something like the Pyboard, you won't have to worry about this
stepcaise those
types of boards come pre-installed with MicroPython by default.
Meanwhiele, other
other board
boards, especially those developed by Adafruit, will likely feature
if
rouitPython instead, which is also avery good choice for hardware programming. But
your rocontroller doesn't already have MicroPython on it, need to worry
there's no
because youcan install the firmware yourself.

JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Python Programming 5- 6

Probably the easiest way to get MicroPython on your board is to use the MicroPython
You can potentially get a two-for-one deal here because the Craft Tm
uPyCraft IDE.
application can also be
1scod
to program boards,
though ie's primarily optimized for ESP32 and ESP8266 ised
variants Tu
steps for installing MicroPython using uPyCraft are as follows: The
1. Start by installing the software on your computer and then
go to the oficial
MicroPython website to download the correct firmware for
Connect your microcontroller to your particular board,
2.
your computer and
proceed to the next step.
Open uPyCraft and go to Tools -> Boards. Select the
example, if you're using an ESP32-based board,appropriate option from the
list. For
options labeled as "esp32". If your board is you should see one of the
list, make sure your USB connected but don't you see it on
drivers are the
3. Access the Tools menu up-to-date.
again, but this time select the
new window will
appear where you can customize the
option "BurnFirmware". A
an ESP32
microcontroller, you'll want to choose the installation. If you're using
board: esp32 following options:
burn_addr: Ox1000
erase flash: yes
com: COM5

Some of these
options may differ depending on
documentation if you're your board, so make sure to
using a different check tne
4 Your next order
of business is
microcontroller.
to
choose the firmware
"Firmware Choose," select you want to install.
the "Users"
Navigate to the Downloads folder option and then click the "Choose" Dnuc
downloaded earlier. to find and buttol
select the
5.5. Hold down the yo MicroPython file you

BOOT button
microcontroller and, at the (name may differ depending onn your board)boara) on your
window. Once the same time, your
The firmware installation click the "OK" button in the uy at
installation process starts, you can release the BOOT button.
good to start should only take a few Do
Example of Installing programming your board. seconds, after whichyou shouldbe
you s
MicroPython is MicroPython
port of the a
inexpensive microcontrollers. Python
on an In this programming
ESP8266-based you will learnlanguage
ng language that runs on small,
the section, that
ESP8266 NodeMCU microcontroller such as the how
insia to install MicroPython
sections, you will using Adafruit SP8266 a
uzzah ESP826 and
learn how to Python and a Feather Huzza
control an LED package
and
called
espresptool. In subseqi
uent

read a sensor
Python
sensor usingMicroPython. The
TECHNICAL
PUBLICATIONS- thrust An up
for
knowledge
JENIL THAKKAR
5-7
t h o nP r o g r a n m m u i n g

MicroPython
following ardware
hardware is needed to install
MicroPython on an ESP8266-based
microcontroller:

or desktop computer Install micropython on the microcontroller


Alaptop

Huzzah ESP8266 Microcontroller running micropython


Adafruit Feather
Micro USB cable Connect the microcontroller to
computer
The following software is used to install MicroPython on an ESP8266-based
microcontroller:
Anaconda distribution of Python Run esptool that installs MicroPython
Anaconda Prompt Install esptool package with pip
Esptool A pip installable package used to install

MicroPython
firmware .bin file Version of MicroPython run on the
microcontroller

Summary of Steps
Install the Anaconda distribution of Python
Create a new conda environment and pip install esptool
Download the latest MicroPython .bin firmware file
nstall the SiLabs driver for the Adafruit Feather Huzzah ESP8266
5. C
Loninect the ESP8266-based microcontroller board to the laptop using a micro USB
cable
6. Determine v
Eermine which serial port the microcontroller is connected to
. Run the esptoo microcontroller
8.
neesptool to upload the .bin firmware file to the
Download and install PuTTY, serial monitor a
9.
and commands at the
se PuTTY to connect to the microcontroller run

MicroPython REPL.
3.5 Install the Anaconda Distribution of Python
you ont
don't have
have the Anaconda distribution of Python installed already, go to
Anac
naconda.com/down to download and install the latest
version.

JENIL THAKKAR
TECHNICAL PUBLICATIONSAn up
thrust for knowledge
Python Programming 5- 8
icroPython
1. Create a new conda environment and install esptool
To install MicroPython on the ESP8266-based microcontroller, we will start by creatinng
a virtual environment. A virtual environment is arn isolated
Python interpreter and a set
of packages that are
separate from the base version of Python running on your computer
We'll create a new virtual environment with the Anaconda
Prompt and the conda
command line tool.
Open theAnaconda Prompt and create a new virtual
environment named
micropython. Activate the environment with the command conda activate. After
activating the virtual environment, you should see the virtual environment name
(micropython) before the> Prompt. Once inside the virtual environment, use pip to install
esptool. esptool will be used to upload the MicroPython .bin firmware file onto
the
ESP8266-based microcontroller. Confirm that
esptool is installed in the (micropython)
virtual environment
by running the command conda list. The list of commands below
also creates a new
directory in the Documents folder called micropython
to store all the
project files.
>conda create -n
micropython python=3.6
>conda activate micropython
(micropython) > pip install esptool
(micropython) > conda list
(micropython)> cd Documents
(micropython)> mkdir micropthon
(micropython) > cd micropython

2. Download the latest MicroPython firmware .bin


file
Go to GitHub.com and
download the latest bin firmware file at
micropython.org/download#esp8266. Move the .bin firmware file to a new
micropytno266
directory. The .bin firmware file is the version of
microcontroller. Straight from the MicroPython that runs on the Eoro
does not have
manufacturer, the ESP8266 microcontroller prooa
MicroPyton installed, so we need to install After
installing the MicroPython ourselves
Micropython .bin firmware file onto the board, we will be able to bring
the MicroPython REPL "
prompt, type commands into the Micropython REPL run

Micropython -py scripts on the board. an

TECHNICAL PUBLICATIONS- An
JENIL THAKKARknowledge up thrust for
Python Programming 5- 9
********
..
**nnsmennnens..
***********************"
**************************************** *t **
MicroPython
***************************** *****
*****""**********************************************************

iceother-Python i x
-

***** ***********
*****

**************************************** ... .. .....

**** ****'**************

mcFoDython.0g iad/*asD6
..... ************
a..................
****** **********

Firmware for ESP8266 boards


The tollowing fies are stable fmware tor the ESP8266. Program ycur board usirg the
esptooi py prcgram as described the tutora.

esp&26-0171101- 3 D (ef, Fmas} (atest)


esp2E8-231 70822-YiS.2.b (ai, 1map}

sp26-20170526.1 9 5in ief. Map


es266-2017010R-YI6.7. n (ef, maz
The following are daity builos of the ESPe266 frmware. They have the latest features and
ug fixes, webREPL is not automatically stareo, and debugging is enabled by de'aut.
s26-2:)120218-v-31- GDO0. n (ei, map) (atest)
esp&z66-20133717.19.331860C6b880.D (ef, RaP)
spe266-20180215y 93-315-q731d20h bi (ef, Fiap)
**********************-***************************************
**********************************************************************************************************************************************************************

.Install the SiLabs driver for the ESP8266-based microcontroller


eLOre we
connect the ESP8266-based microcontroller such as an Adafruit Feather
Huzza ESP8266 or ESP8266 NodeMCU to the computer, a specific driver needs to be
lled. For
ver
Windows 10 laptop to see the board, the CP210x USB to UART Bridge VCP
needs to be downloaded from SiLabs and installed. The driver download and
installation
n sis quick and *****~*****-*****
easy
.***********************
but does require administrator privileges.
***********************************************a***** *****************-*******************************************************************.***************neco.

*****************.********** ****************** ************************************************************************************************.***.** ************-****ssternen*norasn

S
SILICGN LA8
.

Download for Windows 10 Universal (v10.1.1)


sshuare Aeiease Notes
.
. : i

JENIL THAKKAR
TECHNICAL PUBLICATIONS®- An up thrust for knowledge
5- 10
Python Programming MicroPython
4. Connect the ESP8266-based microcontroller to the computer

Use a microUSB cable (the same kind of cable that charges many mobile phones) to
connect the ESP8266-based microcontroller to the computer. Make sure the microUSB
cable is a full USB data cable and not just a power only cable. If you have trouble getting
the microcontroller to work, one reason might be the micoUSB cable you are using is only
a charging cable and can not transfer data.

5. Determine which serial port the ESP8266-based microcontroller is connected to

Use the Windows Device Manager to determine which serial port the ESP8266-based
mirocontroller is connected to. The serial port is one of the parameters which needs to be
defined when the .bin firmware file is upload on the board.
Look for something like Silicon Labs CP210x USB to UART Bridge (COM4) in the
Ports (COM & LPT) menu of the Windows Device Manager. TCP210x USB to UART
Bridge refers to the chip that handles serial communication on the board, not the ESP8266
chip itself. Make a note of the number after (COM). The serial port number often comes
up as (COM4) but it may be different on your computer.
Fiters s

Best natch

DeEe Aanager

Search suggestions

sevice manager Ar2 uet: soiits

SGevice managen

JENIL THAKKAR
TECHNICAL PUBLICATIONS An up
thrust for knowledge
5-11
MicroPython

/1oe
Anager
STesy Help

www.***** ****

DESA
TOP 10YNOC
cutputs

inpUs
end
Audhe

Roltenes

Fivetecth
Compute
Dst de

D s l a ya 5 d e p t e r s

eICEs
H u m e nIntefoce Devn

Aeboards devices
pointing
cther
end
Mice
T Monitos

Netvcrk sdapters

Ports (COM& LPT


(LPT1
ECP
PrinterPert Technolog
$OL (COM3)
Managerment
inte Active COM
US6;A0 UARTPridge
SiliconLabsCPZIK
Print qveues

Precessots

S Dhost edepters

Software devices
controliers
vadec 2n5 game
Scund,
Storage controliers

System devices
controllers
Seriel Bus
Universl
****************-******* **
******************** **********************************
********** ******************.*

ESP8266-based microcontroller
the .bin file to the
&Runesptool to upload Start Menu and cd(change directory)
Open the Anaconda Prompt with the Windows
to see
directory which contains the .bin file. Use the dir command
ito the micropython
contents. Make sure the .bin firmware
file is in the directory.
he micropython directory
like esp8266-20171101-v1.9.3.bin. Activate the
The bin firmware file is named something
command conda activate micropython. Run
mixopython virtual environment with the
Note there is no .py extension after
sptool-help to ensure esptool is installed properly.
command esptool.py may
ool. On Windows, the command esptool works, but the
on the MicroPython docs).
D [Note this behavior is different than the commands shown
y y to run esptool and you are not in the (micropython) virtual
environment, an
eor is returned.
od Documents
od mictopython
pwd
oouments/micropythona
> dir

9ODda activate micropython


opyhon) > esptool --help

TECHNICAL PUBLICATIONS- An up thrust for knowledge


JENIL THAKKAR
5- 12
Python Programming MicroPython

Cmicropython) C:\Users Php 1DocumentsImicnropython>esptool-help


usage: esptool [-h] -chip tauto,esp8266,esp32)] port PORT -baud B
AUD before (default reset,no resetl]
after thard reset, soft reset,noreseth, L*no-stub]
trace
load ram,dump_mem,read mem,write mem,write flash,run, imag
info,make imege, elf2image,read mac,chipid, flash id,read.flash status,w
ite flash status,read Fiash verify flash er ase lash eraseregion,versio

Before uploading the .bin firmware file to the ESP8266-based microcontoller, it is best
practice to first erase the flash memory on the board using the command esptool
erase flash. Make sure to specify the -port. The argument after -port is the COM port
assigned to the ESP8266 board shown in the Windows Device Manager. This port oftern
comes up as cOM4.
(micropython) > esptool --post cOM4 erase_lash

after 1herd resetso


ostu arcbi Oninak to RC
be avaiabia,
traces
or coerasfiash
(micropython) C:sera Ph yhonesptoo

the
Now you can finally write the .bin firmware file to the flash memory
microcontroller using the esptool write_flash command. Make sure to use ot
set
to
needs
nrmware file name you see sitting micropython directory. The port
in the
is the
---baut
COresponding to the port you found in the Windows Device Manager. ecify
baud rate or upload worked, but you couda
speed. I found that -baud 460800 baud

-baud 115200 which is slower. The upload time was a matter of seconds witn c the
rate. The 0 after -flash_size = dectect means the firmware is written at tne
file
firmware
flash memory (the 0th position) on the board. Again, make ssure the .bin
u r e the .bin n

name is correct. The long file is easy to


name
mistype.
(micropython)> esptool -port COM4 --baud 115200 write_flash \
-flash_size=detect0 esp8266-20171101-v1.9.3.bin

TECHNICAL PUBLICATIONS- An up thrust for knowledge


JENIL THAKKAR
5-13
MicroPython

C:
. Users\ PhP \Documents
Users opythonesptool -port COWA-baud 460800
thon-flash_size=detect e espë266-20171181-v1.9.3.bin
enogpy
i t e _
FIash

install PuTTY, a serial monitor


loadand
Download.

that
MicroPython is installed on the ESP8266-based microcontroller, we can
Now

with our board


with our board over
over aa serial connection. However, Windows doesn't have a
mmunicate
monitor (like screen on Mac and Linux). Therefore, if you are using th
serial
buil-in

need to download and install a serial communication


Windows
operating system, you
tol
i k ePuTTY.

PuTTY
lightweight seria and SSH client for Windows. PuTTY provides an
is a

communicate with the ESP8266-based microcontroller. Putty is pretty small,


intertace
to

dowmload and
installation are quick.
and the
X
**********************************-***--*..
. ***** . * .. .................... ..... .... .... ... .. ..... . ... .. .. .... ..... ..-.

Download PuTTY
****

w**
PuTTY IS an SSH and teinet client, ceveloped originaily by Simon Tatham for
....,
.
the Windows piatform. PuTTY is open source seftware that is avaliabie with
source code and is deveioged and supported by a group of volunteers.

You can downioad PuTTY a .


wwww** * * * *

ss*******************************************************************'**********************************************************************"|

.* * * * * * * * * * * * * * * * * * * * * ** * *
** ** **** **
***

8. Connect to the ESP 266-based Microcontroller with PuTTY


Ensure the ESP8266-based microcontroller is connected to the computer with a USB
Cable and ensure the board is visible in the Windows Device Manager. Then use PuTTY to
coninect to the board over serial. Make sure to specify the correct serial port in the Serial
une box and set 115200 baud in the Speed box. Micropython is set to run at 115200 baud,
Make to select the
Daud rates will lead to junk characters in the serial monitor.
sure

radio button below the header Connection type : Near the top of the PulTY
window. Overlooking this detail is easy.

TECHNICAL PUBLICATIONS- An up thrust for knowledge


JENIL THAKKAR
5- 14
Python Programming croPython

OneNote 2015
QOutook 2016

Puine2 0
People

PPowertont 2

Pageant

New

PatTY Man
PuTTY Web Site
PutYgen
ew

TypeType here tO Searcin

TECHNICAL PUBLICATIONS- An up thrust for knowledge

JENIL THAKKAR
AARonP r o g a m m i n g
5-15
*** ARAA*AAMamNARAAAMAnAN

**AaAAMAAASNaAAAAANAAAnMAAAAAAtmAMAAAAA***AAAA***
MicroPython
PuTTY Configuration

Cxegory *** *****

Session Basic options for your PulTY *AAANAAi*****

wwwwwwwwwwwwwww. session
Loggng Specty the destirnation yoi wart to connect
Teninat to
Senal ine
Keyboard ****** ***wwwwwwwwww
Speed
CON
Be ************************************* 115200
Features Cornectior? type:
Window Ra OIeinetRilognOSSH Segal
****

Appearancee
Load. save or deiete a stored ses9io
Behaviour
Translation
Selection
*********** ******wwwwww.ww.wwwwww ***********wwwwwv

Coiours *********************
Lefaut Setngs
** ***********************************

Cornectior esp&26S ***************************-**

Data
aye
Proxy
Telnet
Riogin *******************************.**

Sers
ose window an ext
Aways ever Only on clear ext
****************

******************

**

Hpout * ***************************************

**********************w*
*wwww.wr w**********************************

********rvr**rvo*********ereo.

you see >>» the MicroPython REPL (the MicroPython prompt), MicroPython is

SSTuly installed on your ESP8266-based microcontroler.

Sometimes, you ma
nay need to type [Enter]
or Ctrl-D to bring up the > > REPL orompt.
i the PuTTY window, try to close PuTTY,
AL
Prompt is not displayed in your
unplug then replug the board and open PuTTY again.
Most ESP8266-based

micro rollers also have a tinv little black RESET


button that can be pressed to restart
the board. ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * " * * * * * **
****
****
****
****
****
****
****
** **
** **
****
****
****
*.* * * * * * *.
****
. ***************"*************

**

************** ****************************** X
CO4- PuTTY
SETT et ask{40109130, 3, 3fff831c, 4)
ETror Errno 23ENOENT
module with ESP8266

croPython
ype () v1.9,3-8
Eor 9,3-8-g63826acsc
on
2017-11-01:
ESP

OTE information.

An up thrust for knowledge


JENIL THAKKAR
PUBLICATIONS-
TECHNICAL
5- 16
Python Programming MicroPythor
At the >>> MicroPython REPL prompt try the following commands:
>>> print(Problem Solving with MicroPython!')
Problem Solving witlh MicroPytlhon!

>>> import sys


sys.platform
esp8266'
******* ****** *********************************************** * ************************ ********* * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * a * * * * * * * * * * * * * * * * a * * * * * * * * * * * o s * ** a p n t s s s s p s o n s s r s 1 p s n n p . . s o . . m . . s o n
* *********************************

COM4 - PuTTY
x
ets taski40100130, 3, 3fft837C
OSError: [Errho 2} ENOENT

MicroPython vi.93-8-g63826acse on 2o17 11-01 SP odule sith ESP8266


TYEe e l p ( ) * for more infermaion
imorE ys
sys.plátform
esp826E

5.4 MicroPython Libraries


Python supports a variety of libraries on desktop computers, but porting them directly
to a microcontroller is not an easy task as they are not optimised for running on machines
with less RAM. Instead of making existing useful Python libraries available in

MicroPython, they are stripped in order to be better optimised to run on constrainea


hardware. The current libraries supported by MicroPython are named with the initial u

which stands for the Micro Library implementation:


ucollections collection and container types
uhashlib hashing algorithm
-

uheapq- heap queue algorithm


uio- input/output streams
ujson - JSON encoding and decodingg
uos basic 'operating system' services
ure
-regular expressions
usocket socket module
ustruct pack and
unpack primitive data types
utime time related functions
uzlib zlib decompression.
MicroPython-specific libraries
Functionality specific to the MicroPython implementation is available in the to

libraries.

TECHNICAL PUBLICATIONS- An up thrust


for knowledge
JENIL THAKKAR
5-17 MicroPython
onP r o g r a m m i n g

-
For functic
related to the board
machine

micropython
To access and control MicroPython internals
network configuration
.
network-For
uctypes-
To access binary data in a structured way.

to pyboard
Loraries specific
libraries are specific to pyboard:
Thefollowing related to the board
pyb-for functions
Time related functions

Reset related functions


Interrupt related functions.

Hardware
55 GPIO Programming on MicroPython can be used to perform
A GPIO is a integrated circuit or board that
signal pin on an
and can be used
functions. By design it has no predefined purpose
igital input output
or
the functions they choose. Typical
or software developer to perform
ye nardware switches and controlling
various types of
Ppications include controlling LEDs, reading
ensors.
GPIO connector that
have a 40-pin
tmodels of Raspberry Pi, for example,
PTOVides access to about 25 GPIO ines.

wwwrmit

JENIL THAKKAR
for
PUBLICATIONS- An up thrust knowledge
TECHNICAL
5-18
Python Programming MicroPython
The most common functions of GPIO pins include:
Being configurable in software to be input or output

Being enabled or disabled


Setting the value of a digital output
Reading the value of a digital output
Generating an interrupt when the input changes value.
The board features a USB connector for programming, a connector for an optional
lithium backup battery enabling autonomous operation, and an array of "pins" (electrical
connections) on either side of the board.
Power is supplied to the board either through the USB connector, an attached battery,
an external 5 V supply connected between VUSB and GND, or a 3.3 V supply tied to the
3.3 V pin. In the latter caseEN 3.3 V low to disable the on-board voltage regulator.
pull
VUSB and 3.3 V can also function as supplies for connected peripherals when power is
supplied though another means (e.g. USB).

Standard Digital Output


All pins A0... A21 except A2, A3, A4 can be used for digital output.
frommachineimport Pin
p Pin(id, mode =Pin.OUT)
p0)
p(1)
Steps of coding:
1. Import pin library
2. Declare the pin no with given ID
3. Pin P driven low
4 Pin driven high
fromboardimportA0
frommachineimportPin
p-Pin(A0,mode=Pin.OUT)
Note: The above Code is done in
PYTHON.
Fig. 5.5.1 shows a simplified diagram of the circuit for a used

in the microcontroller. It standard digital outpu


consists of two switches,
S, and S. The switches are aactually
transistors, but the difference is not relevant for this
logic 1 closes switch S, thus connecting the explanation. Setting the ou 3.3
output pin
Similarly, programming the output to 0 opens S and closes S,, thus supply,
Dto the e ot to
connecting
ground.

JENIL THAKKAR
TECHNICAL PUBLICATIONS An up thrust
for knowledge
Python Programming 5-19
MicroPython
3.3V
1

oD out

S2

Fig. 5.5.1 Circuit diagram for a standard digital output


Open Drain Output
When configured as open drain, the corresponding pin is pulled low (i.e. tied to GND)
when set to 0, and open circuited (i.e. not connected) when set to 1.
frommachineimportPin
p=Pin(id.mode =Pin.OPEN_DRAIN)
p0)# pin driven to OV
p(1) # pin open (not driven)

id is the name of the


pin, e.g. A0

Analog Input (ADC)


The ESP-32 contains two 12-bit
analog-to-digital converter (ADCs). In the Huzzah32
board, one of these converters is available to the user.
Vn equals the ADC output code.

Dout Round|2x Vi
Vrei)
Wnere B is the number of bits of the ADC, e.g. 12 for the ESP32.
ne
attn(arg) function is used to set the reference voltage V to one of the values
Table 5.5.1.
Configuration parameter
ADC.ATTN ODB 1.1 V

ADC.ATTN25DB 1.3 V

ADC ATTN 6DB 1.8 V

ADC.ATTN 11DB 3.2 V

Table 5.5.1 ADC full scale range

JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Python Programming 5-20

ample 5.5.1 Set ADC full seale range to 1.1 V (with "Loboris MicroPython"
MicroPython
adcO.rend
returnsthe ADC input in milli-Volts)
Solution
fromboardimportADCO0
frommachineimportPin, ADC

adc0=ADCPin(ADCO))

#set full-scale range


adco.atten(ADC.ATTN ODB)
#perform conversion
d_out adc0.read()
ESP32 ADCO code vs Vin

4000 . **** ************ **********


: **********
wwwwow
***********************
po I OIIOOD
AiRaRNNLRAtrANN88
**************"**********************************"

3000 ************"********""********2*9a***2*M** *****A************************

2000 *************************sow*gn*or****w*

O dB
1000 ****************** ************ ********************************vwwv** ******************:***
w2.5 dB
w**wwww 6 dB

**** 11 dB

0.0 0.5 1.0 1.5 2.0 2.5 3.0


Vin [

Fig.5.5.2 ADC output code versus


input voltage

TECHNICAL
JENILPUBLICATIONS-An
THAKKAR for knowledge up thrust
Python Programming 5- 21

MicroPython
ESP32 ADCO offset: Code vs
Vin near zero
30 ***w*ww*wwvwww
. 0 dB3
*******Vv***ww**ww*www******owwwwww.wwwweewte**nn
25
wwwww

2.5dB *****************
* ** *********************************************
www.ww 6 dB

20 .11 dB *******************
*********?**************
*********************************
*********************
*****************************************
***************************************************************** * * * * * * **
** * * *

10
*********************
******************************* ****************

*** *************************

*******
****************************************** ********

www.
******o000o ww ***********************
0 20 40 60 80 100 120 140 160
Vin M

Fig. 5.5.3 ADC offset

ESP32 ADCO INL for 6 dB

wwwwwoits9namwwwww wwwwwwwww. wwwwwwwwwwwww wwwA WA w

* ****** ***

-10 *"**************** AAAA*AAAAARAAAAAAAAAA

**********wwwww www wwww


www

-20 *********** *""*** ** ********

************ ***************

25 ******* ****

7*** ***** ** * wwwwww

-30 **ww******* ********* **** www.w. Vwwwwww

0.25 0.50 0.75 1.00 1.25 1.50 1.75


Vin M

Fig. 5.5.4 ADC INL for 6 dB attenuation

JENIL THAKKAR
TECHNICAL PUBLICATIONS -An up thrust for knowledge
Python Programming 5-22

5.6 Sensor Programming using MicroPython AicroPython


Hardware used
Let's start withoverview of the available hardware and the
an

twittered a table showing the m ain hardware differences differences. Amins


between the ESP8266 and o
ESP32-WROOM which are expected to coexist in the market, with the
lower cost
ESP8266 used in #ho
segment (only WiFi support), and ESP32 in
applications requiring
Bluetooth. WiFi and

Sr. No. Specifications


ESP8266 ESP32
MCU Xtensa®Single Core32-bit L106 Xtensa@Dual Core 32-bit
LX6600 DMIPS
802.11 b/gn WiFi Yes, HT20 Yes, HT40
Bhuetoo None
Bluetooth 4.2 and below
Typical Frequer 80 MHz 160MHIz
SRAM
160 kBytes 2kBy
Flash SPI Flash up to 16 MBytes SPU Flash, up to 16 MBytes
GPIO
17
Hardware software
PWM
None/8 channels 1/16channels
SPII2C12S/UART 2/1/2/2
10 4/2/2/2
ADC
10-bit 12-bit
11 CAN 820329900029

None
12
Ethernet MAC
Interface
None
Touch Sensor
14
None es
Temperature Sensor
15 None Yes
Workin8 Temperature
-40 °C-125 °C 4 0 °C 125 °C

Table 5.6.1
MemoryError issues
You can usually get the following error
using MicroPython
Memory

allocation failed,
allocating xxxx bytes. The MemoryErcially
RAM is very limited,
yError:
the

especa
JENIL
TECHNICAL THAKKAR
PUBLICATIONS An up thrust
-

for knowledge
Python Programming 5 23
nd some
ESP&266 and sometimes on the ESP32-VWROOM. MicroPython
If you run into this issue, you can cross-
Compile the python files that you want load to the board to reduce the RAM
Tadothat, you need to use Linux (Sorry Windows use.
users) and clone the
WiPy: pycom/pycom-micropython-sigfox repositories
ESP32/ESP8266: micropython/esp32
Then, go to the folder mpy-cross
using a terminal, and type make.
seconds/minutes. Then, you can compile the python files Wait a couple of
to get the mpy files. using /mpy-cross <filename.py>
Then, load only the .mpy files not the
.py files! Otherwise, the board tries
py and you get the same error to load the
again.
For the Code of Sensor
Code Visit
https://github.com/lemariva/uPySersors
because it may use so
many files so it is not
possible to show in book.
But for
your understanding I have given one example on Sensor
Temperature Sensor
There are
many temperature the market. One
sensors on
the MCP9808 breakout board from well-documented sensor is
Adafruit. Like our light sensor, it uses the
Communication. To use the sensor, IC2 bus for
.
Power and ground can
you need four connections
:Ground, power, SDA, and
be connected to the
EACDOard or power and ground lines of
you can
directly to the associated
pins on the ESP8266. For
the SDA and SCL
your
either connect them pins,
nes) through the
directly to the ESP8266 or daisy-chain them
Lux sensor. Assuming (connect in
your you already have the TSL2591 sensor
ESP8266,
here are the connections you will need wired to

Signal Name Location of Source


GND
Location of Destination
Bottom row of MCP9808 board
breadboard pin #2 from left
3V
op row
MCP9808 board
of breadboard
ping #1 from left
SDA TSL2591 board MCP9808 board
pin 5 from left pin #4 from left
SCL TSL2591 board MCP9808 board
pin #6 from left pin #3 from left

JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
5-24
Python Programming MicroPython
ThingFlow for MicroPython has a sensor class for the MCP9808 cated
in
micropython/sensors/mcp9808.py. Here is an example MicroPython REPL session th
re
we sample both the lux and temperature sensors using ThingFlow:
>>>fromts12591 importTs12591
>>>frommcp9808importMcp9808
>>>lux=Ts12591()
>>>temperature =Mcp9808()
Read manufacturer ID: 0054
Read device ID: 040o
>>>sched=Scheduler)
>>>sched.schedule_sensor(lux, 10,Output())
<closure >

>>>sched.schedule_sensor(temperature,10,Output())
<closure>

>>>sched.run forever()
(ts12591, 108, 162.221)
(mcp9808, 108, 26.1875)
(ts12591, 117, 162.221)
(mcp9808', 117, 26.1875)
(ts12591, 126, 1.5096)
('mcp9808, 126, 26.1875)

JENIL THAKKAR
TECHNICAL
PUBLICATIONS- An up thrust
for knowledge

You might also like