Página sobre o processo de instalação do MicroPython numa placa ESP32-PICO-KIT assim como o uso do Visual Studio Code para edição do código.
Nota: Os passos em seguida descritos devem ser efetuados tal como é explicado caso contrário será comprometida a realização dos passos seguintes.
Python + Node + VSCode
Começar por instalar o Python 3.8 (neste caso usei o Windows x86-64 executable installer para a versão 3.8.1: python-3.8.1-amd64.exe). Segui a sugestão da instalação ser realizada na pasta: C:\Users\<user>\AppData\Local\Programs\Python\Python38 e ativei a opção de “Add Python 3.8 to PATH”.
Instalar depois o NodeJS (6.9.5 ou superior) no meu caso instalei o Windows Installer (.msi): node-v12.15.0-x64.msi. Segui a sugestão da instalação ser realizada na pasta: C:\Program Files\nodejs\
Por fim, instalei o Visual Studio Code, mais concretamente o VSCodeUserSetup-x64-1.42.0.exe. A instalação foi feita em C:\Users\<user>\AppData\Local\Programs\Microsoft VS Code e segui a sugestão de “Add to Path (requires shell restart)”.
Abrindo uma nova janela de comando (cmd) é possível verificar que todos os programas foram instalados e as respetivas versões:
C:\Users\Helio>python -V Python 3.8.1 C:\Users\Helio>node -v v12.15.0 C:\Users\Helio>code -v 1.42.0 ae08d5460b5a45169385ff3fd44208f431992451 x64
Nota: Se algum dos comandos não for reconhecido é porque muito provavelmente não ativou as opção “Add to PATH” referidas anteriormente ou não está a usar uma NOVA janela de comando (cmd).
Segue-se a instalação da ferramenta esptool para programação do firmware do ESP32. Para tal, executar o seguinte comando numa janela de comando cmd:
C:\Users\Helio>pip install esptool Collecting esptool Collecting ecdsa (from esptool) Using cached https://files.pythonhosted.org/packages/b8/11/4b4d30e4746584684c758d8f1ddc1fa5ab1470b6bf70bce4d9b235965e99/ecdsa-0.15-py2.py3-none-any.whl Collecting pyaes (from esptool) Collecting pyserial>=3.0 (from esptool) Using cached https://files.pythonhosted.org/packages/0d/e4/2a744dd9e3be04a0c0907414e2a01a7c88bb3915cbe3c8cc06e209f59c30/pyserial-3.4-py2.py3-none-any.whl Collecting six>=1.9.0 (from ecdsa->esptool) Using cached https://files.pythonhosted.org/packages/65/eb/1f97cb97bfc2390a276969c6fae16075da282f5058082d4cb10c6c5c1dba/six-1.14.0-py2.py3-none-any.whl Installing collected packages: six, ecdsa, pyaes, pyserial, esptool Successfully installed ecdsa-0.15 esptool-2.8 pyaes-1.6.1 pyserial-3.4 six-1.14.0 WARNING: You are using pip version 19.2.3, however version 20.0.2 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command.
A verificação de que o esptool ficou bem instalado pode ser feita correndo o comando:
C:\Users\Helio>esptool esptool.py v2.8 usage: esptool [-h] [--chip {auto,esp8266,esp32}] [--port PORT] [--baud BAUD] [--before {default_reset,no_reset,no_reset_no_sync}] [--after {hard_reset,soft_reset,no_reset}] [--no-stub] [--trace] [--override-vddsdio [{1.8V,1.9V,OFF}]] {load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,chip_id,flash_id,read_flash_status,write_flash_status,read_flash,verify_flash,erase_flash,erase_region,version} ... esptool.py v2.8 - ESP8266 ROM Bootloader Utility positional arguments: {load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,chip_id,flash_id,read_flash_status,write_flash_status,read_flash,verify_flash,erase_flash,erase_region,version} Run esptool {command} -h for additional help load_ram Download an image to RAM and execute dump_mem Dump arbitrary memory to disk read_mem Read arbitrary memory location write_mem Read-modify-write to arbitrary memory location write_flash Write a binary blob to flash run Run application code in flash image_info Dump headers from an application image make_image Create an application image from binary files elf2image Create an application image from ELF file read_mac Read MAC address from OTP ROM chip_id Read Chip ID from OTP ROM flash_id Read SPI flash manufacturer and device ID read_flash_status Read SPI flash status register write_flash_status Write SPI flash status register read_flash Read SPI flash content verify_flash Verify a binary blob against flash erase_flash Perform Chip Erase on SPI flash erase_region Erase a region of the flash version Print esptool version optional arguments: -h, --help show this help message and exit --chip {auto,esp8266,esp32}, -c {auto,esp8266,esp32} Target chip type --port PORT, -p PORT Serial port device --baud BAUD, -b BAUD Serial port baud rate used when flashing/reading --before {default_reset,no_reset,no_reset_no_sync} What to do before connecting to the chip --after {hard_reset,soft_reset,no_reset}, -a {hard_reset,soft_reset,no_reset} What to do after esptool.py is finished --no-stub Disable launching the flasher stub, only talk to ROM bootloader. Some features will not be available. --trace, -t Enable trace-level output of esptool.py interactions. --override-vddsdio [{1.8V,1.9V,OFF}] Override ESP32 VDDSDIO internal voltage regulator (use with care)
Nota: Caso o comando esptool não seja reconhecido use antes esptool.py
Começar por ligar a placa ESP32-PICO-KIT ao computador por cabo USB e ver no “Gestor de Dispositivos” qual a porta COM atribuída.
Caso a placa não surja como uma porta virtual COMx instale os respetivos drivers. No caso do Windows 10 eles vêm no CP210x_Universal_Windows_Driver.zip bastando executar o programa CP210xVCPInstaller_x64.exe no caso da versão de 64 bits).
Começa-se por limpar a memória de programa (flash) do ESP32, usando a porta COM adequada (nestes exemplos será a COM6):
C:\Users\Helio>esptool --chip esp32 --port COM6 erase_flash esptool.py v2.8 Serial port COM6 Connecting........__ Chip is ESP32-PICO-D4 (revision 1) Features: WiFi, BT, Dual Core, 240MHz, Embedded Flash, VRef calibration in efuse, Coding Scheme None Crystal is 40MHz MAC: d8:a0:1d:6a:0b:1c Uploading stub... Running stub... Stub running... Erasing flash (this may take a while)... Chip erase completed successfully in 4.5s Hard resetting via RTS pin...
Segue-se a instalação do firmware MicroPython esp32-idf4-20191220-v1.12.bin no ESP32:
Segue-se
C:\Users\Helio>esptool --chip esp32 --port COM6 --baud 460800 write_flash -z 0x1000 Downloads\esp32-idf4-20191220-v1.12.bin esptool.py v2.8 Serial port COM6 Connecting.... Chip is ESP32-PICO-D4 (revision 1) Features: WiFi, BT, Dual Core, 240MHz, Embedded Flash, VRef calibration in efuse, Coding Scheme None Crystal is 40MHz MAC: d8:a0:1d:6a:0b:1c Uploading stub... Running stub... Stub running... Changing baud rate to 460800 Changed. Configuring flash size... Auto-detected Flash size: 4MB Compressed 1408512 bytes to 894711... Wrote 1408512 bytes (894711 compressed) at 0x00001000 in 20.5 seconds (effective 550.4 kbit/s)... Hash of data verified. Leaving... Hard resetting via RTS pin...
micropy-cli
Segue-se este processo de integração do micropy-cli (GitHub) no VSCode, há que fazer o seguinte numa janela de commando:
C:\Users\Helio>pip install --upgrade micropy-cli Collecting micropy-cli Using cached micropy_cli-3.3.0-py3-none-any.whl (127 kB) Processing c:\users\helio\appdata\local\pip\cache\wheels\12\d2\88\6e706d3b6874a2948967d0838eb0e0224a8a43b4eb273cf3f3\requirements_parser-0.2.0-py3-none-any.whl Collecting requests<3.0,>=2.22 Using cached requests-2.23.0-py2.py3-none-any.whl (58 kB) Collecting tqdm<5.0,>=4.39 Using cached tqdm-4.43.0-py2.py3-none-any.whl (59 kB) Collecting Jinja2<3.0,>=2.10 Using cached Jinja2-2.11.1-py2.py3-none-any.whl (126 kB) Collecting click<8.0,>=7.0 Using cached Click-7.0-py2.py3-none-any.whl (81 kB) Collecting cachier<2.0,>=1.2 Using cached cachier-1.4.1-py2.py3-none-any.whl (13 kB) Processing c:\users\helio\appdata\local\pip\cache\wheels\62\70\49\400c325d1db02901ad862338304643ea65e8a68c84e36d9125\dpath-1.5.0-py3-none-any.whl Collecting questionary<2.0,>=1.4 Using cached questionary-1.5.1-py3-none-any.whl (25 kB) Collecting boltons<20.0,>=19.3 Using cached boltons-19.3.0-py2.py3-none-any.whl (166 kB) Collecting jsonschema==3.2.0 Using cached jsonschema-3.2.0-py2.py3-none-any.whl (56 kB) Collecting packaging<20.0,>=19.2 Using cached packaging-19.2-py2.py3-none-any.whl (30 kB) Collecting colorama<0.5.0,>=0.4.3; sys_platform == "win32" Using cached colorama-0.4.3-py2.py3-none-any.whl (15 kB) Collecting chardet<4,>=3.0.2 Using cached chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting idna<3,>=2.5 Using cached idna-2.9-py2.py3-none-any.whl (58 kB) Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 Using cached urllib3-1.25.8-py2.py3-none-any.whl (125 kB) Collecting certifi>=2017.4.17 Using cached certifi-2019.11.28-py2.py3-none-any.whl (156 kB) Collecting MarkupSafe>=0.23 Downloading MarkupSafe-1.1.1-cp38-cp38-win_amd64.whl (16 kB) Processing c:\users\helio\appdata\local\pip\cache\wheels\4c\8e\7e\72fbc243e1aeecae64a96875432e70d4e92f3d2d18123be004\pathtools-0.1.2-py3-none-any.whl Processing c:\users\helio\appdata\local\pip\cache\wheels\4e\14\01\1676612f5b23c641868de61d36ac2d5be12f4eec6c087fbd62\watchdog-0.10.2-py3-none-any.whl Collecting portalocker Using cached portalocker-1.5.2-py2.py3-none-any.whl (14 kB) Collecting prompt-toolkit<4.0,>=2.0 Using cached prompt_toolkit-3.0.3-py3-none-any.whl (348 kB) Requirement already satisfied, skipping upgrade: six>=1.11.0 in c:\users\helio\appdata\local\programs\python\python38\lib\site-packages (from jsonschema==3.2.0->micropy-cli) (1.14.0) Collecting attrs>=17.4.0 Using cached attrs-19.3.0-py2.py3-none-any.whl (39 kB) Requirement already satisfied, skipping upgrade: setuptools in c:\users\helio\appdata\local\programs\python\python38\lib\site-packages (from jsonschema==3.2.0->micropy-cli) (41.2.0) Collecting pyrsistent>=0.14.0 Using cached pyrsistent-0.15.7.tar.gz (107 kB) Collecting pyparsing>=2.0.2 Using cached pyparsing-2.4.6-py2.py3-none-any.whl (67 kB) Collecting pywin32!=226; platform_system == "Windows" Downloading pywin32-227-cp38-cp38-win_amd64.whl (9.1 MB) |████████████████████████████████| 9.1 MB 3.3 MB/s Collecting wcwidth Using cached wcwidth-0.1.8-py2.py3-none-any.whl (17 kB) Installing collected packages: requirements-parser, chardet, idna, urllib3, certifi, requests, tqdm, MarkupSafe, Jinja2, click, pathtools, watchdog, pywin32, portalocker, cachier, dpath, wcwidth, prompt-toolkit, questionary, boltons, attrs, pyrsistent, jsonschema, pyparsing, packaging, colorama, micropy-cli Running setup.py install for pyrsistent ... done Successfully installed Jinja2-2.11.1 MarkupSafe-1.1.1 attrs-19.3.0 boltons-19.3.0 cachier-1.4.1 certifi-2019.11.28 chardet-3.0.4 click-7.0 colorama-0.4.3 dpath-1.5.0 idna-2.9 jsonschema-3.2.0 micropy-cli-3.3.0 packaging-19.2 pathtools-0.1.2 portalocker-1.5.2 prompt-toolkit-3.0.3 pyparsing-2.4.6 pyrsistent-0.15.7 pywin32-227 questionary-1.5.1 requests-2.23.0 requirements-parser-0.2.0 tqdm-4.43.0 urllib3-1.25.8 watchdog-0.10.2 wcwidth-0.1.8
Em seguida procurar os “stubs” para placas ESP32:
C:\Users\Helio>micropy stubs search esp32 MicroPy Searching Stub Repositories... MicroPy Results for esp32: MicroPy esp32-micropython-1.10.0 MicroPy esp32-micropython-1.11.0 MicroPy esp32-micropython-1.12.0 MicroPy esp32-micropython-1.9.4 MicroPy esp32-pycopy-1.11.0 MicroPy esp32-pycopy-2.11.0.1 MicroPy esp32-pycopy-2.11.0.5 MicroPy esp32-pycopy-3.0.0 MicroPy esp32_LoBo MicroPy esp32_LoBo-esp32_LoBo-3.2.24
Neste caso interessa a esp32-micropython-1.12.0 pelo que a instalamos de seguida:
C:\Users\Helio>micropy stubs add esp32-micropython-1.12.0 MicroPy Adding esp32-micropython-1.12.0 to stubs MicroPy Resolving stub... MicroPy esp32-micropython-1.12.0: 100%|█████████████████████████████████████████████████████████| [9.83k/9.83k @ ?B/s] MicroPy Detected Firmware: micropython MicroPy Firmware not found locally, attempting to install it... MicroPy Resolving stub... MicroPy micropython: 100%|██████████████████████████████████████████████████████████████████| [43.4k/43.4k @ 44.6MB/s] MicroPy <img draggable="false" data-mce-resize="false" data-mce-placeholder="1" data-wp-emoji="1" class="emoji" alt="✔" src="https://s.w.org/images/core/emoji/11/svg/2714.svg"> micropython firmware added! MicroPy <img draggable="false" data-mce-resize="false" data-mce-placeholder="1" data-wp-emoji="1" class="emoji" alt="✔" src="https://s.w.org/images/core/emoji/11/svg/2714.svg"> esp32-micropython-1.12.0 added!
Segue-se a instalação da extensão Pymakr no VSCode, algo que também pode ser feito da linha de comando, assim:
C:\Users\Helio>code --install-extension pycom.pymakr Installing extensions... Installing extension 'pycom.pymakr' v1.1.5... Extension 'pycom.pymakr' v1.1.5 was successfully installed.
Segue-se a instalação da extensão Python no VSCode, algo que também pode ser feito da linha de comando, assim:
C:\Users\Helio>code --install-extension ms-python.python Installing extensions... Installing extension 'ms-python.python' v2020.2.64397... Extension 'ms-python.python' v2020.2.64397 was successfully installed.
No VSCode deveremos abrir o ficheiro de configurações global Pymakr (pymakr.json) indo ao rodapé e escolhendo “All Commands” e depois Pymakr > Global setting, e alterá-lo com a seguinte informação:
"open_on_start": false, ... "auto_connect": false,
Após o que gravamos as alterações através do menu File > Save ou com o atalho Ctrl+S.
Criar projeto
Na pasta do workspace executar numa janela de comando (por exemplo no VSCode terminal):
Microsoft Windows [Version 10.0.18362.657] (c) 2019 Microsoft Corporation. Todos os direitos reservados. D:\workspace>micropy init test
Podemos começar por selecionar todos os templates (algo que pode ser feito através da tecla i seguindo de enter:
MicroPy Creating New Project ? Choose any Templates to Generate (Use arrow keys to move, <space> to select, <a> to toggle, <i> to invert) » ○ VSCode Settings for Autocompletion/Intellisense ○ Pymakr Configuration ○ Pylint MicroPython Settings ○ Git Ignore Template ○ main.py & boot.py files
Escolhe-se depois o “stub” (neste caso o esp32-micropython-1.12.0) carregando em space seguido de enter:
MicroPy Creating New Project ? Choose any Templates to Generate done (5 selections) ? Which stubs would you like to use? (Use arrow keys to move, <space> to select, <a> to toggle, <i> to invert) » ○ esp32-micropython-1.12.0
No final é criada a pasta test:
MicroPy Initiating test MicroPy Stubs: esp32-micropython-1.12.0 MicroPy Rendering Templates MicroPy Populating Stub Info... MicroPy Vscode File Generated! MicroPy Pylint File Generated! MicroPy Vsextensions File Generated! MicroPy Pymakr File Generated! MicroPy Main File Generated! MicroPy Boot File Generated! MicroPy Gitignore File Generated! MicroPy ✔ Stubs Injected! MicroPy ✔ Project Created! MicroPy Created test at ./test
Esta pasta pode ser agora aberta no VSCode (File > Open Folder…). Aí é preciso editar o ficheiro pymakr.conf, onde devemos editar a porta COM para o valor adequado, por exemplo:
"address": "COM6",
Após o que gravamos as alterações (File > Save ou Ctrl+S).
Carregando no botão de Reset da placa ESP32-PICO-KIT (o mais perto da antena WiFi) é possível ver o arranque do MicroPython:
>>> ets Jun 8 2016 00:22:57 rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 188777542, 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:4988 load:0x40078000,len:10404 load:0x40080400,len:5680 entry 0x400806bc I (520) cpu_start: Pro cpu up. I (520) cpu_start: Application information: I (520) cpu_start: Compile time: Dec 20 2019 07:56:38 I (523) cpu_start: ELF file SHA256: 0000000000000000... I (529) cpu_start: ESP-IDF: v4.0-beta1 I (534) cpu_start: Starting app cpu, entry point is 0x40083014 I (0) cpu_start: App cpu up. I (545) heap_init: Initializing. RAM available for dynamic allocation: I (552) heap_init: At 3FFAFF10 len 000000F0 (0 KiB): DRAM I (558) heap_init: At 3FFB6388 len 00001C78 (7 KiB): DRAM I (564) heap_init: At 3FFB9A20 len 00004108 (16 KiB): DRAM I (570) heap_init: At 3FFBDB5C len 00000004 (0 KiB): DRAM I (576) heap_init: At 3FFCC8A0 len 00013760 (77 KiB): DRAM I (582) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM I (589) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM I (595) heap_init: At 40099FB8 len 00006048 (24 KiB): IRAM I (601) cpu_start: Pro cpu start user code I (620) spi_flash: detected chip: generic I (620) spi_flash: flash io: dio I (620) cpu_start: Chip Revision: 1 W (622) cpu_start: Chip revision is higher than the one configured in menuconfig. Suggest to upgrade it. I (633) cpu_start: Starting scheduler on PRO CPU. I (0) cpu_start: Starting scheduler on APP CPU. MicroPython v1.12 on 2019-12-20; ESP32 module with ESP32 Type "help()" for more information. >>>
É agora possível ver a linha de REPL do MicroPython onde podemos executar o tradicional “Hello World”:
Connecting to COM6... >>> print("Hello World") Hello World >>>
Como sugerido podemos executar a função help():
>>> help() 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')
Assim que o VSCode deteta a presença de ficheiros .py recomenda a instalação de certas extensões (This workspace has extension recomendations) pelo que deveremos carregar no botão “Show Recommendations” e instalar a “Visual Studio IntelliCode” (processo que pode demorar alguns minutos, podendo ser acompanhado no rodapé do VSCode).
Abrindo a pasta src do projeto é possível ver os ficheiros boot.py e main.py.
Editando este último com o seguinte código:
from machine import Pin from time import sleep led = Pin(21, Pin.OUT) while True: led.value(not led.value()) sleep(.5)
Depois de gravado (Ctrl+S) podemos fazer o upload das alterações após o que a placa reinicia correndo o programa que faz piscar um LED ligado no pino 21.
A execução do programa pode ser interrompida carregando em Ctrl+C.
To be continued…
No Python interpreter is selected.
Select Python Interpreter
Fazer piscar um LED a 1Hz:
from machine import Pin from time import sleep led = Pin(21, Pin.OUT) while True: led.value(not led.value()) sleep(.5)
Controlar um LED com um botão:
from machine import Pin from time import sleep led = Pin(21, Pin.OUT) button = Pin(22, Pin.IN, Pin.PULL_UP) while True: led.value(not button.value()) sleep(.1)
Application of uasyncio to hardware interfaces
Instalação do uasyncio:
import network wlan = network.WLAN(network.STA_IF) # create station interface wlan.active(True) # activate the interface wlan.connect('ssid', 'password') # connect to an AP while not wlan.isconnected(): pass import upip upip.install('micropython-uasyncio') upip.install('micropython-uasyncio.synchro') upip.install('micropython-uasyncio.queues')
main.py:
from machine import Pin import uasyncio as asyncio from led_async import LED_async async def killer(): button = Pin(22, Pin.IN, Pin.PULL_UP) while button.value(): await asyncio.sleep_ms(100) led = LED_async(21) led.flash(1) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
led_async.py:
from machine import Pin import uasyncio as asyncio class LED_async: def __init__(self, led_no): self.led = Pin(led_no, Pin.OUT) self.rate = 0 loop = asyncio.get_event_loop() loop.create_task(self.run()) async def run(self): while True: if self.rate <= 0: await asyncio.sleep_ms(200) else: self.led.value(not self.led.value()) await asyncio.sleep_ms(int(500 / self.rate)) def flash(self, rate): self.rate = rate def on(self): self.led.on() self.rate = 0 def off(self): self.led.off() self.rate = 0
Misc
# main.py from time import sleep import network wlan = network.WLAN(network.STA_IF) # create station interface wlan.active(True) # activate the interface wlan.scan() # scan for access points wlan.isconnected() # check if the station is connected to an AP wlan.connect('ssid', 'password') # connect to an AP while not wlan.isconnected(): pass print(wlan.config('mac')) # get the interface's MAC address print(wlan.ifconfig()) # get the interface's IP/netmask/gw/DNS addresses print(wlan.status('rssi'), 'dB') while True: sleep(.1) #---------------------------------------- from machine import Pin, ADC, PWM # led = Pin(21, Pin.OUT) button = Pin(22, Pin.IN, Pin.PULL_UP) pot = ADC(Pin(32)) pot.atten(ADC.ATTN_11DB) pwm = PWM(Pin(21)) pwm.freq(1000) pwm.duty(2048) while True: pwm.duty(pot.read() >> 2) sleep(.1) while True: pot_value = pot.read() print(pot_value) led.value(not button.value()) sleep(.1) n = 1 while True: print('hello', n) sleep(1) n += 1 led.value(not led.value())
Página sobre o uso do MicroPython com o Visual Studio Code numa placa com o ESP32 Pico Kit.
Python
Começar por instalar o Python 3.7 (neste caso usei o Windows x86-64 executable installer para a versão 3.7.5). Segui a sugestão da instalação ser realizada na pasta: C:\Users\Helio\AppData\Local\Programs\Python\Python37 E ativei a opção de “Add Python 3.7 to PATH”.
esptool
Depois instalar a ferramenta esptool para programação do firmware no ESP32:
pip install esptool
Foi-me sugerido que atualizasse o pip da versão 19.2.3 para a 19.3.1, executando o seguinte comando:
python -m pip install --upgrade pip
MicroPython
Começar por ligar a placa ESP32-PICO-KIT ao computador por cabo USB e ver no “Gestor de Dispositivos” qual a porta COM atribuída. Instalar o firmware MicroPython esp32-idf4-20191220-v1.12.bin no ESP32, substituindo o COMx pela porta adequada:
esptool.py --chip esp32 --port COM7 erase_flash esptool.py v2.8 Serial port COM7 Connecting.... Chip is ESP32-PICO-D4 (revision 1) Features: WiFi, BT, Dual Core, 240MHz, Embedded Flash, VRef calibration in efuse, Coding Scheme None Crystal is 40MHz MAC: d8:a0:1d:6a:03:b4 Uploading stub... Running stub... Stub running... Erasing flash (this may take a while)... Chip erase completed successfully in 3.1s Hard resetting via RTS pin... esptool.py --chip esp32 --port COM7 --baud 460800 write_flash -z 0x1000 .\esp32-idf4-20191220-v1.12.bin esptool.py v2.8 Serial port COM7 Connecting........____ Chip is ESP32-PICO-D4 (revision 1) Features: WiFi, BT, Dual Core, 240MHz, Embedded Flash, VRef calibration in efuse, Coding Scheme None Crystal is 40MHz MAC: d8:a0:1d:6a:03:b4 Uploading stub... Running stub... Stub running... Changing baud rate to 460800 Changed. Configuring flash size... Auto-detected Flash size: 4MB Compressed 1146864 bytes to 717504... Wrote 1146864 bytes (717504 compressed) at 0x00001000 in 16.8 seconds (effective 546.7 kbit/s)... Hash of data verified. Leaving... Hard resetting via RTS pin...
VSCode
Instalei o VSCode (VSCodeUserSetup-x64-1.40.2.exe). Segui a sugestão da instalação ser realizada na pasta: C:\Users\Helio\AppData\Local\Programs\Microsoft VS Code
Selecionei todas as opções na janela “Select Additional Tasks”, incluindo a “Add to PATH”.
Pymakr
Começar por instalar o NodeJS (6.9.5 ou superior) no meu caso instalei a node-v12.13.1-x64.msi. Segui a sugestão da instalação ser realizada na pasta: C:\Program Files\nodejs\ Reiniciar o VSCode e instalar nele a extensão Pymakr (neste caso a v1.1.5). No final é aberto o ficheiro pymakr.json com as suas configurações globais (algo que também é possível aceder com o comando Pymakr > Global Settings), onde devemos editar o seguinte:
"open_on_start": false, "auto_connect": false,
Alterar também as configurações do Pymakr > Project Settings:
"address": "COM3",
micropy-cli
Seguindo este processo de integração do micropy-cli (GitHub) no VSCode, há que fazer o seguinte numa Windows PowerShell fazer:
pip install --upgrade micropy-cli
Em seguida procurar os “stubs” para placas ESP32:
PS C:\Users\Helio> micropy stubs search esp32 MicroPy Searching Stub Repositories... MicroPy Results for esp32: MicroPy esp32-micropython-1.10.0 MicroPy esp32-micropython-1.11.0 MicroPy esp32-micropython-1.9.4 MicroPy esp32-pycopy-1.11.0 MicroPy esp32-pycopy-2.11.0.1 MicroPy esp32-pycopy-2.11.0.5 MicroPy esp32_LoBo MicroPy esp32_LoBo-esp32_LoBo-3.2.24
Nest caso interessa a esp32-micropython-1.11.0 pelo que a instalamos de seguida:
PS C:\Users\Helio> micropy stubs add esp32-micropython-1.11.0 MicroPy Adding esp32-micropython-1.11.0 to stubs MicroPy Resolving stub... MicroPy esp32-micropython-1.11.0: 100%|█████████████████████████████████████████████████████████| [14.4k/14.4k @ ?B/s] MicroPy Detected Firmware: micropython MicroPy Firmware not found locally, attempting to install it... MicroPy Resolving stub... MicroPy micropython: 100%|██████████████████████████████████████████████████████████████████| [41.5k/41.5k @ 42.0MB/s] MicroPy ✔ micropython firmware added! MicroPy ✔ esp32-micropython-1.11.0 added!
Segue-se a instalação da extensão ms-python.python no VSCode, algo que também pode ser feito da linha de comando, assim:
PS C:\Users\Helio> code --install-extension ms-python.python Installing extensions... Installing extension 'ms-python.python' v2019.11.50794... (node:8340) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. (node:8340) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. Extension 'ms-python.python' v2019.11.50794 was successfully installed.
Neste caso instalou a versão v2019.11.50794.
Criar projeto
Na pasta do workspace executar no Windows PowerShell (ou num terminal do VSCode: Terminal > New Terminal: Ctrl + Shift + ç):
micropy init testproj
E escolher os seguintes “templates”:
? Choose any Templates to Generate (Use arrow keys to move, <space> to select, <a> to toggle, <i> to invert) » ● VSCode Settings for Autocompletion/Intellisense ● Pymakr Configuration ○ Pylint MicroPython Settings ○ Git Ignore Template ○ main.py & boot.py files
E depois o “stub”:
? Which stubs would you like to use? (Use arrow keys to move, <space> to select, <a> to toggle, <i> to invert) » ● esp32-micropython-1.11.0
No final é possível abrir a pasta criada (testproj) no VSCode. Aí é preciso editar o ficheiro pymakr.conf (algo que também é possível aceder com o comando Pymakr > Project Settings), onde devemos editar a porta COM para o valor adequado, por exemplo:
"address": "COM7",
e apagar a seguinte linha:
"sync_folder": "src",
Na janela Terminal do VSCode surgirá a linha REPL do MicroPython:
MicroPython v1.11 on 2019-05-29; ESP32 module with ESP32 Type "help()" for more information. >>>
Se necessário carregar no botão de reset da placa (o mais perto da antena WiFi).
Primeiros passos
Aqui podemos começar por verificar que o único ficheiro .py presente no sistema de ficheiros é o boot.py:
>>> import os >>> os.listdir() ['boot.py']
Criar o ficheiro test.py mas isto faz aparecer o erro: Linter pylint is not installed. Source: Python (Extension) Install; Select Linter; Do not show again Escolher Install e ir a File > Preferences > Settings > Search Settings: Pylint Path, e alterar a configuração: Python › Linting: Pylint Path Path to Pylint, you can use a custom version of pylint by modifying this setting to include the full path. De pylint para C:\Users\Helio\AppData\Roaming\Python\Python37\Scripts\pylint.exe
Tutoriais
Ver estes videos sobre MicroPython no YouTube. Artigos:
- #MicroPython: VSCode IntelliSense, Autocompletion & Linting capabilities
- #MicroPython: Visual Studio Code as IDE
- pymakr
Erros
Está constantemente a aparecer a indicação de que: Linter pylint is not installed. Source: Python (Extension) Install; Select Linter; Do not show again Escolhendo Install acontece o seguinte:
D:\vscode\mymicropython>C:/Users/Helio/.platformio/penv/Scripts/activate.bat (penv) D:\vscode\mymicropython>C:/Users/Helio/.platformio/penv/Scripts/python.exe -m pip install -U pylint --user Collecting pylint Using cached https://files.pythonhosted.org/packages/e9/59/43fc36c5ee316bb9aeb7cf5329cdbdca89e5749c34d5602753827c0aa2dc/pylint-2.4.4-py3-none-any.whl Collecting isort<5,>=4.2.5 Using cached https://files.pythonhosted.org/packages/e5/b0/c121fd1fa3419ea9bfd55c7f9c4fedfec5143208d8c7ad3ce3db6c623c21/isort-4.3.21-py2.py3-none-any.whl Collecting mccabe<0.7,>=0.6 Using cached https://files.pythonhosted.org/packages/87/89/479dc97e18549e21354893e4ee4ef36db1d237534982482c3681ee6e7b57/mccabe-0.6.1-py2.py3-none-any.whl Collecting astroid<2.4,>=2.3.0 Using cached https://files.pythonhosted.org/packages/ad/ae/86734823047962e7b8c8529186a1ac4a7ca19aaf1aa0c7713c022ef593fd/astroid-2.3.3-py3-none-any.whl Requirement already satisfied, skipping upgrade: colorama; sys_platform == "win32" in c:\users\helio\.platformio\penv\lib\site-packages (from pylint) (0.4.1) Collecting six~=1.12 Using cached https://files.pythonhosted.org/packages/65/26/32b8464df2a97e6dd1b656ed26b2c194606c16fe163c695a992b36c11cdf/six-1.13.0-py2.py3-none-any.whl Processing c:\users\helio\appdata\local\pip\cache\wheels\d7\de\2e\efa132238792efb6459a96e85916ef8597fcb3d2ae51590dfd\wrapt-1.11.2-cp37-none-any.whl Collecting lazy-object-proxy==1.4.* Using cached https://files.pythonhosted.org/packages/59/5b/b72328980e6681df90c933c11adbb434a48f27b6a5770109d6cce4abdc56/lazy_object_proxy-1.4.3-cp37-cp37m-win_amd64.whl Collecting typed-ast<1.5,>=1.4.0; implementation_name == "cpython" and python_version < "3.8" Using cached https://files.pythonhosted.org/packages/47/a1/7a24868c15d84ed7446106d6c3d73807f58232a695452c0a29679e5a1523/typed_ast-1.4.0-cp37-cp37m-win_amd64.whl Installing collected packages: isort, mccabe, six, wrapt, lazy-object-proxy, typed-ast, astroid, pylint WARNING: The script isort.exe is installed in 'C:\Users\Helio\AppData\Roaming\Python\Python37\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The scripts epylint.exe, pylint.exe, pyreverse.exe and symilar.exe are installed in 'C:\Users\Helio\AppData\Roaming\Python\Python37\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed astroid-2.3.3 isort-4.3.21 lazy-object-proxy-1.4.3 mccabe-0.6.1 pylint-2.4.4 six-1.13.0 typed-ast-1.4.0 wrapt-1.11.2
Tenho escolhido Install mas isso não impede de o aviso surgir posteriormente! File > Preferences > Settings > Search Settings: Pylint Path Python › Linting: Pylint Path Path to Pylint, you can use a custom version of pylint by modifying this setting to include the full path. C:\Users\Helio\AppData\Roaming\Python\Python37\Scripts\pylint.exe
Projeto rotary
O projeto rotary serve de exemplo ao uso de:
- comunicação serial
- led
- button
- scheduler/tasks
- ssd1306
- menu
Facts and myths about Python names and values
Misc:
- Get back “Open command window here” context menu option in Windows 10
- Visual Studio Code, how to switch from powershell.exe to cmd.exe