4. MicroPython
• a lean and efficient implementation of the Python 3 programming
language
• that includes a small subset of the Python standard library and
• is optimised to run on microcontrollers and in constrained
environments.
http://micropython.org/
14. Blink LED
• 測試外接LED (LED 正極接在 pin D2), 底下的程式碼能讓LED閃爍十
遍
import machine
import time
ledD2 = machine.Pin(4, machine.Pin.OUT)
for i in range(10):
ledD2.high()
time.sleep(0.5)
ledD2.low()
time.sleep(0.5)
15. 數位輸入-Button
import machine
button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
while True:
if not button.value():
print('Button pressed!')
16. 數位輸入-Button
import machine
import time
ledD2 = machine.Pin(4, machine.Pin.OUT)
button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
while True:
first = button.value()
time.sleep(0.01)
second = button.value()
if first and not second:
print('Button pressed!')
ledD2.high()
elif not first and second:
print('Button released!')
ledD2.low()
20. 類比輸出-調控燈光亮度
• On the ESP8266 the pins 0, 2, 4, 5, 12, 13, 14 and 15 all support PWM.
The limitation is that they must all be at the same frequency, and the
frequency must be between 1Hz and 1kHz.
import time
import machine
pwm = machine.PWM(machine.Pin(4))
pwm.freq(60)
while True:
for i in range(0,1024,5):
pwm.duty(i)
time.sleep(0.005)
for i in range(1023, -1, -5):
pwm.duty(i)
time.sleep(0.005)
22. Load File & Run Code
• 如果開發板有1MB以上的Flash, MicroPython 啟動後會配置一個內
部的 filesystem
• 可以將程式碼存入, 當ESP8266啟動時可以自行載入程式執行
(就像是 Arduino 執行 Arduino sketch一樣)
• Start up scripts
• boot.py : is executed first (if it exists)
• main.py : is executed after boot.py completes
23. ampy
• https://github.com/adafruit/ampy
• With ampy you can
• send files from your computer to a MicroPython board's file system,
• download files from a board to your computer,
• and even send a Python script to a board to be executed.
$ pip install adafruit-ampy
$ ampy --port COM15 ls
$ ampy --port COM15 run blink10times.py
$ ampy --port COM15 put blink10times.py main.py
$ ampy --port COM15 rm main.py