A guidebook for doing IoT with MicroPython easily to the last minute

This article is the second day of Python Part 2 Advent Calendar 2019. The first day was @ ssh-22's advanced string replacement using re.sub.


With the birth of Arduino and Raspberry Pi, the ecosystem is rapidly being set up in the IoT area, but although Raspberry Pi can be implemented in Python, Arduino is overwhelmingly easier to use for a little electronic control. However, some people may want to write in the familiar Python instead of the Arduino language (like C / C ++). In this article, I would like to write a guide to easily start development using MicroPython, which is an embedded Python, in a financial sense as well.

What to prepare

--Arduino …… not ESP32 development board --San Hayato New Breadboard SAD-101

The working environment is macOS + Python3.

ESP32 development board

In the recent Arduino area, the same development environment as Arduino can be used, and ESP32 that can use Wifi / Bluetooth has become the mainstream (it is not exactly Arduino, but it can be used in almost the same way). ESP32-DevKit C and compatibles, which are generally more sophisticated than the standard Arduion UNO but cheaper, are often used.

If you are in a hurry, Akizuki Denshi ESP32-DevKitC for 1,480 yen or Switch Science ESPr Developer 32 for 2,200 yen -science.com/catalog/3210/) Let's procure.

However, I personally recommend overseas mail order such as aliexpress. This time, we raised here for 436 yen. The price is 1/3. However, it took about 3 weeks to arrive. If you can buy it for about 1,500 yen, you can buy it in Japan, but electronic work breaks parts and it is troublesome to reuse it if you use it to make something, so if you do not hurry, the price is 1/3 It is recommended to buy three at. For those who do not want to pay by credit card by overseas mail order, there are other sites such as banggood where paypal can be used, but since the price difference is small with domestic purchase, it may be better to buy it in Japan. Still, it's less than half the price of a Raspberry Pi.

(Addition) If you think about it, you can buy it cheaply on Amazon. 2 pieces for 1,680 yen, so I think this is all right.

Sanhayato New Breadboard SAD-101

The ESP32-DevKitC has a slightly wider width between the pin rows, and a breadboard with 5 holes on each side, which is sold cheaply, will not have insertion holes. The new breadboard series is easy to use because it has 6 holes on each side. This time, I prepared the simplest SAD-101. It's a little expensive breadboard, so it's 518 yen on Amazon.

MicroPython installation

After that, let's set up MicroPython on the ESP32 according to Documents translated into Japanese.

Normally, when you purchase ESP32-DevKitC, Arduino compatible firmware called Arduino Core is already written. As it is, it can be implemented only in Arduino language, so rewrite the MicroPython firmware.

Firmware download

Firmware for ESP32 boards

In MicroPython for ESP32, you have to select either "a farm that can use Wifi but not Bluetooth" or "a farm that can use Bluetooth but cannot use Wifi". This time, I will choose a stable build of "a farm that can use Wifi".

image.png

Driver installation

Install the Silicon Labs driver for a USB connection to the ESP32-DevKitC.

CP210x USB --UART Bridge VCP Driver

This time I installed the driver for macOS. If you connect the ESP32 via USB, you should probably see the ESP32 in /dev/cu.SLAB_USBtoUART.

Initialization of written firmware

$ pip install esptool
$ esptool.py --port /dev/cu.SLAB_USBtoUART erase_flash

If you run it, you will get the following result.

$ esptool.py --port /dev/cu.SLAB_USBtoUART erase_flash
esptool.py v2.8
Serial port /dev/cu.SLAB_USBtoUART
Connecting........_
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz
MAC: XX:XX:XX:XX:XX:XX
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 8.4s
Hard resetting via RTS pin...

Write firmware

$ esptool.py --chip esp32 --port /dev/cu.SLAB_USBtoUART write_flash -z 0x1000 esp32-idf3-20190529-v1.11.bin

If you run it, you will get the following result.

$ esptool.py --chip esp32 --port /dev/cu.SLAB_USBtoUART write_flash -z 0x1000 esp32-idf3-20190529-v1.11.bin
esptool.py v2.8
Serial port /dev/cu.SLAB_USBtoUART
Connecting........____
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz
MAC: XX:XX:XX:XX:XX:XX
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 1146864 bytes to 717504...
Wrote 1146864 bytes (717504 compressed) at 0x00001000 in 63.5 seconds (effective 144.4 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

You have now set up MicroPython. I'm going to run it with Python right away.

Python execution

Using MicroPython REPL

First, try accessing the REPL prompt.

$ screen /dev/tty.SLAB_USBtoUART 115200

If you type help () [enter] and the output is as follows, it is successful.

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
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')
>>>

It also returns print ().

>>> print("hello")
hello

The screen command will prompt you to confirm the end with ctrl + a + k, so exit with y.

Source code transfer

Writing code in the REPL is painful, so I will make it possible to transfer the source code file. First, install the tools.

$ pip install adafruit-ampy

Check the transferred files.

$ ampy -p /dev/tty.SLAB_USBtoUART ls
/boot.py

You can see that only boot.py is being transferred.

I will also check the contents.

$ $ ampy -p /dev/tty.SLAB_USBtoUART get /boot.py
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()

You can see that all lines are commented out and that what is written in boot.py is executed only the first time when the board is reset. After executing boot.py, main.py will be executed as the main process (if it exists). Transfer the following code as main.py and try L-Chika.

import machine
import time

pin13 = machine.Pin(13, machine.Pin.OUT)

while True:
  pin13.on()
  time.sleep_ms(500)
  pin13.off()
  time.sleep_ms(500)

Use the following command to transfer.

$ ampy -p /dev/tty.SLAB_USBtoUART put main.py

If the LED connected to the D13 pin lights up at intervals of 500ms, it is successful.

Summary

When I first learned about MicroPython, it seemed that the threshold was high, such as the need to rewrite the firmware, but when I actually tried it, although there were some aspects of using tools that I was not used to, it was not so difficult and I realized the transfer and execution of Python code. It's done. If you are familiar with Python, using ESP32 with MicroPython is a pretty ant option because you only need to transfer the source code once you have done this procedure. I haven't done this this time, but it seems that you can easily connect to the Wifi AP using the communication function of ESP32 as follows, so your dreams will expand.

import network
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

And if you make something interesting, I think you should definitely announce it at IoTLT.

By the way, as I wrote at the beginning, if you can wait until it arrives, you can play this much for 436 yen. Isn't it the best to say the least?


Tomorrow is @ TsuMakoto's Introduction to Amazon Personalize with Python SDK.

Recommended Posts

A guidebook for doing IoT with MicroPython easily to the last minute
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
A simple workaround for bots to try to post tweets with the same content
Save the object to a file with pickle
Calculate the optimal solution to set a world record for decathlon with scipy.optimize
[Introduction to Python] How to get the index of data with a for statement
How to create a submenu with the [Blender] plugin
Transit to the update screen with the Django a tag
Library "apywrapper" to easily develop a wrapper for RESTful API
Finding a solution to the N-Queen problem with a genetic algorithm (2)
Probably the easiest way to create a pdf with Python3
Experiment to make a self-catering PDF for Kindle with Python
Create a Twitter BOT with the GoogleAppEngine SDK for Python
How to get the last (last) value in a list in Python
A story about how to deal with the CORS problem
How to create a SAS token for Azure IoT Hub
The usual way to add a Kernel with Jupyter Notebook
[Python] The first step to making a game with Pyxel
Finding a solution to the N-Queen problem with a genetic algorithm (1)
I want to create a Dockerfile for the time being.
Try to generate a death metal jacket image with DCGAN + scrape the metal database site for that
[Django Learned with the Devil's Blade] How to get a query set for forward / reverse reference
I tried to unlock the entrance 2 lock sesame with a single push of the AWS IoT button
[Short sentence] easygui for those who want to use a simple GUI with Python very easily
Easily cProfile with a decorator
I made a library to easily read config files with Python
Create an alias for Route53 to CloudFront with the AWS API
Create a color picker for the color wheel with Python + Qt (PySide)
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
How to make a command to read the configuration file with pyramid
Switch the package to be installed for each environment with poetry
The story of making a standard driver for db with python.
How to create a label (mask) for segmentation with labelme (semantic segmentation mask)
[Introduction to Python] How to use the in operator in a for statement?
Change the bash prompt to a simple color for easy viewing
Series to think about "IoT front-end development" ④ IoT prototyping with MicroPython Part 1
I tried to register a station on the IoT platform "Rimotte"
I wanted to solve the ABC164 A ~ D problem with Python
Theano A trick for amateurs to do their best with PyMC3
Write a script to calculate the distance with Elasticsearch 5 system painless
A command to easily check the speed of the network on the console
For the time being, I want to convert files with ffmpeg !!
I tried to make a strange quote for Jojo with LSTM
How to send a request to the DMM (FANZA) API with python
Create a REST API to operate dynamodb with the Django REST Framework