Whymicropython

Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

Why we will use microPython

Rapid prototyping with microPython devices

Marco Zennaro, ICTP


April 30, 2018
Why micropython?
python

1
python ecosystem

2
micropython

MicroPython is a lean and fast implementation of the Python 3


programming language that is optimised to run on a microcontroller.
MicroPython was successfully funded via a Kickstarter campaign and the
software is now available to the public under the MIT open source license.
It ensures that the memory size/microcontroller performance is optimised
and fit for purpose for the application it serves. Many sensor reading and
reporting applications do not require a PC based processor as this would
make the total application over priced and under-efficient.

Credit pycom.io 3
micropython options

4
pyboard

The MicroPython pyboard is a compact electronic circuit board that runs


MicroPython on the bare metal, giving you a low-level Python operating
system that can be used to control all kinds of electronic projects.
MicroPython is packed full of advanced features such as an interactive
prompt, arbitrary precision integers, closures, list comprehension,
generators, exception handling and more. Yet it is compact enough to fit
and run within just 256k of code space and 16k of RAM.
MicroPython aims to be as compatible with normal Python as possible to
allow you to transfer code with ease from the desktop to a
microcontroller or embedded system.

Credit micropython.org 5
pyboard

6
pyboard

7
pyboard

8
pyboard

9
pyboard

10
ESP8266: low cost

11
ESP8266: characteristics

• 802.11 b/g/n
• Built-in TCP / IP protocol stack
• Built-in PLL, voltage regulator and power management components
• 802.11b mode + 19.5dBm output power
• Built-in temperature sensor
• off leakage current is less than 10uA
• Built-in low-power 32-bit CPU: can double as an application
processor
• SDIO 2.0, SPI, UART
• standby power consumption of less than 1.0mW

12
BBC Micro:bit

13
BBC Micro:bit

The Micro Bit is an ARM-based embedded system designed by the BBC


for use in computer education in the UK.
The board has an ARM Cortex-M0 processor, accelerometer and
magnetometer sensors, Bluetooth and USB connectivity, a display
consisting of 25 LEDs, two programmable buttons, and can be powered
by either USB or an external battery pack. The device inputs and
outputs are through five ring connectors that are part of the 23-pin edge
connector.

14
Digi

15
Trinket

16
M5stack

17
pycom: WiPy

18
pycom: WiPy

• Espressif ESP32 chipset


• Dual processor + WiFi radio system on chip
• consuming 25uA
• 2 x UART, 2 x sPI, I2C, I2S, micro SD card
• Analog channels: 8×12 bit ADCs
• Hash/Encryption: SHA, MD5, DES, AES
• Bluetooth
• Memory, RAM: 512KB, External flash: 4MB
• Hardware floating point acceleration

19
pycom: LoPy

20
pycom: SiPy

21
pycom: LoPy4

• Espressif ESP32 chipset


• Quadruple network MicroPython enabled development board (LoRa,
Sigfox, WiFi, Bluetooth)
• RAM: 4MB (vs 512KB)
• External flash: 8MB (vs 4MB)

22
pycom: Expansion Board

23
pycom: PySense

24
pycom: PySense

• Ambient light sensor


• Barometric pressure sensor
• Humidity sensor
• 3 axis 12-bit accelerometer
• Temperature sensor
• USB port with serial access
• LiPo battery charger
• MicroSD card compatibility
• Ultra low power operation ( 1uA in deep sleep)

25
pycom: PyTrack

26
pycom: PyTrack

• GNSS + Glonass GPS


• 3 axis 12-bit accelerometer
• USB port with serial access
• LiPo battery charger
• MicroSD ard compatibility
• Ultra low power operation ( 1uA in deep sleep)

27
Our Lab equipment

• Pycom LoPy4
• PySense
• PyTrack
• microUSB cable

28
Plan of the week
plan for the week

During the lab sessions we will cover:

1. Pycom workflow
2. Hello World for IoT: LED switching
3. Saving data to internal flash
4. Reading sensors using the PySense
5. Connecting to WiFi, measuring signal strength and setting the clock
6. Reading position using the PyTrack
7. Using external Grove sensors
8. Saving data to InfluxDB and visualizing them using Grafana
9. Using MQTT
10. Using LoRaWAN

You will have simple code snippets and will develop more complex code
as exercise.
29
workflow: Atom

Please install Atom from

www.atom.io
30
workflow: install the pymakr package

Preferences -> Settings -> Install -> search Pymakr

31
workflow: update packages if necessary

32
workflow: connect board via USB

Make sure the LED and the microUSB are on the same side!
33
workflow: get serial port

34
workflow: global settings

35
workflow: insert correct device address

36
workflow: connect!

37
workflow: REPL

38
REPL console

REPL stands for Read Print Eval Loop. Simply put, it takes user
inputs, evaluates them and returns the result to the user.
You have a complete python console!
Try to enter 2+2 and press Enter.
Now enter:
print(”Hi! I am a python shell!”)

39
executing code

There are three ways to execute code on a Pycom device:

1. Via the REPL shell. Useful for single commands and for testing.
2. Using the Run button. Code in the Atom editor will be executed,
but will not be stored in the device. If you reboot, the code will not
be executed again.
3. Synching the device with the Project folder in Atom. In this way,
the code is stored in the Pycom device and will be executed again if
you reboot the device.

40
workflow: Run

41
workflow: add Project folder

42
workflow: ONE Project folder

It is easier if you only have one Project folder. Make sure you
Remove any other Project folders and keep only the one you want
to use.
43
workflow: Project folder

The Project folder should contain all the files to be synched with the
device.
You should always have two files: boot.py (executed at boot time) and
main.py (containing the main code).
The folder can also include libraries and other python source code.

44
workflow: example of Project folder

45
workflow: upload Project

46
workflow: boot.py

The boot.py file should always start with following code, so we can run
our Python scripts over Serial or Telnet.

from machine import UART


import o s
u a r t = UART( 0 , 1 1 5 2 0 0 )
o s . dupterm ( u a r t )

47
LED
LED

In this example, we will create and deploy the proverbial 1st app, “Hello,
world!” to a Pycom device.
The LoPy module has one LED (big, white LED on the same side as the
microUSB).

48
code: LED

Check the LED folder and sync the two files to your active project folder.
Exercise:
Try to send an SOS message using the LED. The SOS is
line-line-line-dot-dot-dot-line-line-line in morse code, where a line is three
times longer than a dot.

49
Writing data on Flash memory
Flash

In this example, we will learn how to:

1. access and operate the device file system;


2. create and write a file in the /flash folder;

50
Folder structure

Connect to a Lopy via the Atom console and import the basic operating
system module (os): import os.
Once imported:
to know you current working directory: os.getcwd() (most probably the
/flash folder);
to list folders and files in your current working directory: os.listdir();
to create a new folder/directory named ”log”: os.mkdir('log');

51
Writing and reading

In the simplest case, to create and write a new file:

os . l i s t d i r ( ’ / f l a s h ’ )

# c r e a t e / open , w r i t e , c l o s e a f i l e
f = open ( ’ l o g /my\ _ f i r s t \ _ f i l e . l o g ’ , ’w ’ )
f . w r i t e ( ’ Testing ␣ w r i t e ␣ o p e r a t i o n s ␣ i n ␣a␣ f i l e . ’ )
f . close ()

# open , r e a d , c l o s e an e x i s t i n g f i l e
f = open ( ’ l o g /my\ _ f i r s t \ _ f i l e . l o g ’ , ’ r ’ )
f . readall ()
f . close ()

52
workflow: download file from flash

53
workflow: download file from flash

54
Connect via WiFi

• Connect to the WiFi network produced by your LoPy. Find out the
name using More –> Get WiFi AP SSID. The password is
www.pycom.io
• Using your browser, ftp://192.168.4.1 with username micro and
password python.
• Download the file.

55
Exercise

Write a script writing a file named ”log.csv” in /flash/log/ folder so that:


it writes ”start”, writes a string for ten times, writes ”finish” and repeats
this for five times.

56
PySense
PySense high-level modules

In this lab, we will provide a series of examples:


- accelerometer in src/pysense/acceloremeter
- measuring ambient light in src/pysense/ambient-light
- measuring temperature and atmospheric pressure in
src/pysense/temp-bar
- measuring temperature and humidity in src/pysense/temp-hum
Pycom provides a library abstracting the implementation details of sensor
chips. This library is already included in labs source code under the lib
folder of each example.

57
Exercises

• Change the color of the LED based on accelerometer measurements


(green, orange, red if the values of acceleration are small, medium or
large)
• Find where is the temperature sensor and where is the light sensor
• Log the measurements of temperature every 10 seconds and the
measurements of humidity every 30 seconds into the /flash/log
folder (while LED blinking green)
• Build a pendulum, measure its acceleration and visualize the result.
See https://en.wikipedia.org/wiki/Pendulum

58
WiFi
WiFi

In this lab, we will provide a series of examples:


- connecting to a WiFi network using WPA authentication (in
src/WiFi/WPA)
- measuring signal strength (in src/WiFi/RSSI)
- synchronizing the internal clock using a webserver (in
src/WiFi/Sync-no-NTP)

59
Connecting to WiFi using WPA

Modify the following lines to reflect your Access’s Point name and
password:
s s i d = ’MyAP ’
p a s s w o r d = ’ MyPassword ’

Scan for all networks and check if there is any network with the name of
your Access Point:
n e t s = wlan . s c a n ( )
for net in nets :
i f n e t . s s i d == s s i d :
p r i n t ( ’ Network ␣ f o u n d ! ’ )

Connect!
wlan . c o n n e c t ( n e t . s s i d , a u t h =( n e t . s e c , pas swo rd , t i m e o u t =50

60
Measuring signal strength

RSSI stands for Received Signal Strength Indicator and reflects the
received signal level. Don’t forget it’s a negative value (and -70 indicates
a stronger signal than -80).
Scan for all networks:

n e t s = wlan . s c a n ( )

and print the RSSI value of each network:

w h i l e True :
for net in nets :
print ( net . ssid , net . r s s i )

61
Synchronizing the clock with a server

In this example we will be using a WiFi connection to connect to the


SODAQ time server in order to retrieve the current date and time stamp
and update the internal RTC.
The example code first connects to the WiFi Access Point, then connects
to the time.sodaq.net sever on port 80 and gets a string as an output. It
splits the output and take the row which corresponds to the seconds (the
seventh row). It finally sets the local time to this value in seconds and
visualizes the new time.

62
Exercises

• Try to move around the lab and check the RSSI values. How far can
you go while still receiving the APs? Use the LED color to show the
RSSI value.
• Log and plot the RSSI values over time. How much does the RSSI
fluctuate?
• Synchronize the clock and use the correct time to timestamp
temperature and humidity measurements. Log time, T and H in a
file in the internal flash. You now have a data logger!

63
PyTrack
GPS

In this lab, we will use a Lopy on a Pytrack board to access the position
given by the internal GPS.
To get a GPS fix (which means to get the exact position) you must have
an unobstructed view of the sky. It will not work in the lab! You must
use the Pytack outdoors.

64
PyTrack

Pycom provides a library (a set of Python modules) abstracting the


implementation details of the GPS. This library is already included in labs
source code.
Enable the GPS:

py = P y t r a c k ( )
gp s = L76GNSS ( py , t i m e o u t =30)

get the measurements and print them:

( l a t , l o n , a l t , hdop ) = gp s . p o s i t i o n ( )
p r i n t ( ”%s ␣%s ␣%s ␣%s ” %( l a t , l o n , a l t , hdop ) )

65
Exercises

• Go out to get a GPS fix! Use the LED to make sure you have a fix.
Save the positions provided by the Pytrack in a file (call it log.cvs)
and download it on your computer using the ”Download” button in
Atom. Visualize the places you have visited using the instructions
provided here: http:
//www.cartagram.com/5648/from-excel-to-google-maps/ or
use this online tool: http://www.gpsvisualizer.com/
• Design a ”WiFi counter” that measures how many WiFi networks
are available in a certain place. Log the GPS position and the
number of WiFi networks in a file. Visualize the results around the
ICTP campus!

66
Grove shield
Grove sensors

www.seeedstudio.com/category/Sensor-for-Grove-c-24.html
67
Grove sensors

68
Grove shield

69
Grove - OLED Display 0.96”

70
Grove - Sunlight Sensor

71
Grove - Moisture Sensor

72
Grove - Temperature and Humidity Sensor DHT11

73

You might also like