M5StackをMicroPythonで遊ぼう

 M5StackをMicroPythonで遊ぼう

2018 PyCon mini Osaka

7af33601b7d5788de7c255a556d7063a?s=128

mitszo

May 19, 2018
Tweet

Transcript

  1. 7.
  2. 11.

    M5Stack M5Stack ͷಛ௃ ▸ ແઢ-"/ʢ()[ʣ ▸ #MVF5PPUI ▸ Y-$% ▸

    όοςϦʔ ▸ Ϙλϯ ▸ εϐʔΧʔ ▸ *4 ▸ NJDSP4% ▸ (307&ʢ*$ʣ ▸ 41*
  3. 16.

    MicroPython MicroPython ▸ IUUQNJDSPQZUIPOPSH ▸ ϚΠίϯ޲͚ͷ1ZUIPOॲཧܥ ▸ ίϯύΠϥɺϥϯλΠϜɺ3&1-ΛؚΉ ▸ ϥΠϒϥϦ

    ▸ IUUQEPDTNJDSPQZUIPOPSHFOMBUFTUQZCPBSEMJCSBSZJOEFYIUNM ▸ ඪ४ϥΠϒϥϦʢ$1ZUIPOʣͷαϒηοτ ▸ lVzϥΠϒϥϦ ▸ .JDSP1ZUIPOϥΠϒϥϦ ▸ ର৅ϋʔυ΢ΣΞ༻ϥΠϒϥϦ
  4. 19.

    MicroPython CPythonͱͷҧ͍ - γϯλοΫε ▸ ਺஋ϦςϥϧͱΩʔϫʔυͷؒʹεϖʔε͕ඞਢ >>> print(1or 0) 1

    >>> print(1or 0) Traceback (most recent call last): File "<stdin>", line 1 SyntaxError: invalid syntax for integer with base 10 MicroPython ʢM5Stack൛ʣ Python 3.6.4
  5. 20.

    MicroPython CPythonͱͷҧ͍ - γϯλοΫε ▸ 6OJDPEFOBNFFTDBQF͕࢖͑ͳ͍ >>> print('\N{LATIN SMALL LETTER

    A}') a >>> print('\N{LATIN SMALL LETTER A}') NotImplementedError: unicode name escapes MicroPython ʢM5Stack൛ʣ Python 3.6.4
  6. 22.

    >> try: ... try: ... a = {}['a'] ... except

    KeyError as e1: ... raise ValueError() from e1 ... except ValueError as e2: ... print(type(e2.__cause__)) ... <class ‘KeyError'> MicroPython CPythonͱͷҧ͍ - ྫ֎νΣΠϯ Python 3.6.4
  7. 23.

    >>> try: ... try: ... a = {}['a'] ... except

    KeyError as e1: ... raise ValueError() from e1 ... except ValueError as e2: ... print(type(e2.__cause__)) ... Warning: exception chaining not supported Traceback (most recent call last): File "<stdin>", line 7, in <module> File "<stdin>", line 7, in <module> AttributeError: 'ValueError' object has no attribute '__cause__' >>> e = Exception() >>> dir(e) ['__class__', 'args'] MicroPython CPythonͱͷҧ͍ - ྫ֎νΣΠϯ MicroPython ʢM5Stack൛ʣ
  8. 25.

    >>> try: ... try: ... a = {}['a'] ... except

    KeyError as e1: ... e1.user_attribute = 'abc' ... raise e1 ... except Exception as e2: ... print(e2.user_attribute) ... abc MicroPython CPythonͱͷҧ͍ - ྫ֎ͷϢʔβʔଐੑ Python 3.6.4
  9. 26.

    >>> try: ... try: ... a = {}['a'] ... except

    KeyError as e1: ... e1.user_attribute = 'abc' ... raise e1 ... except Exception as e2: ... print(e2.user_attribute) ... Traceback (most recent call last): File "<stdin>", line 8, in <module> File "<stdin>", line 8, in <module> AttributeError: 'AttributeError' object has no attribute 'user_attribute' MicroPython CPythonͱͷҧ͍ - ྫ֎ͷϢʔβʔଐੑ MicroPython ʢM5Stack൛ʣ
  10. 28.

    MicroPython CPythonͱͷҧ͍ - จࣈྻ ▸ TUSFOETXJUIͰΠϯσοΫεࢦఆ͕࢖͑ͳ͍ ▸ TUSGPSNBUͰଐੑࢦఆ͕࢖͑ͳ͍ >>> 'abc'.endswith('c',

    2) Traceback (most recent call last): File "<stdin>", line 1, in <module> NotImplementedError: start/end indices >>> '{a[0]}'.format(a=[1, 2]) Traceback (most recent call last): File "<stdin>", line 1, in <module> NotImplementedError: attributes not supported yet
  11. 29.

    MicroPython CPythonͱͷҧ͍ - จࣈྻ ▸ TUSؔ਺ͰΩʔϫʔυҾ਺ࢦఆ͕Ͱ͖ͳ͍ >>> print(str(b'abc', encoding='utf-8')) Traceback

    (most recent call last): File "<stdin>", line 1, in <module> NotImplementedError: keyword argument(s) not yet implemented - use normal args instead >>> print(str(b'abc', 'utf-8')) abc
  12. 31.

    MicroPython CPythonͱͷҧ͍ - εϥΠε ▸ CZUFBSSBZͰࠨลʹεϥΠεΛࢦఆͨ͠୅ೖ͕Ͱ͖ͳ͍ ▸ CZUFT จࣈྻͷεϥΠεͰTUFQࢦఆ͕Ͱ͖ͳ͍ ▸

    MJTUͷ࡟আͰTUFQࢦఆ͕Ͱ͖ͳ͍ ▸ MJTUͷεϥΠε୅ೖͰ࢖͑Δͷ͸MJTU͔UVQMF >>> ba[0:1] = [1, 2] >>> print(b’123’[0:3:2]) >>> del lst[0:4:2] >>> lst[0:1] = range(4)
  13. 33.

    MicroPython CPythonͱͷҧ͍ - jsonϞδϡʔϧ >>> import json >>> data =

    bytes(range(10)) >>> print(json.dumps(data)) Traceback (most recent call last): … TypeError: Object of type 'bytes' is not JSON serializable Python 3.6.4
  14. 34.

    MicroPython CPythonͱͷҧ͍ - Ϟδϡʔϧ >>> import json >>> data =

    bytes(range(10)) >>> print(json.dumps(data)) "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\t" MicroPython ʢM5Stack൛ʣ
  15. 36.

    MicroPython OSͷࢧԉ͕ͳ͍ ▸ ωοτϫʔΫ ▸ ωοτϫʔΫʹ઀ଓ͢Δͱ͜Ζ͔Β࢝·Δ ▸ ূ໌ॻ ▸ ূ໌ॻετΞ͕ͳ͍

    ▸ ࣌ࠁ ▸ ݱࡏ࣌ࠁΛ΋ͬͯͳ͍ ▸ ϑΝΠϧγεςϜ ▸ Ϛ΢ϯτ͢Δͱ͜Ζ͔Β࢝·Δ
  16. 46.

    ։ൃ؀ڥ M5Stackͷ։ൃ؀ڥ - MicroPython Usage: ampy [OPTIONS] COMMAND [ARGS]... ampy

    - Adafruit MicroPython Tool Ampy is a tool to control MicroPython boards over a serial connection. Using ampy you can manipulate files on the board's internal filesystem and even run scripts. Options: -p, --port PORT Name of serial port for connected board. [required] -b, --baud BAUD Baud rate for the serial connection. (default 115200) --help Show this message and exit. Commands: get Retrieve a file from the board. ls List contents of a directory on the board. put Put a file on the board. rm Remove a file from the board. run Run a script and print its output.
  17. 48.

    ։ൃ؀ڥ M5Stackͷ։ൃ؀ڥ - MicroPython $ sudo cu -s 115200 -l

    /dev/tty.SLAB_USBtoUART Connected. >>> from m5stack import lcd >>> lcd.print('Python!') >>> ΋ͪΖΜ3&1-΋࢖͑·͢ .4UBDLΛ64#έʔϒϧͰ઀ଓͯ͠ɺ
  18. 55.

    M5Stackϓϩάϥϛϯά M5Cloud/examples/DigitalClock/clock.py from m5stack import * import time, _thread, machine

    def clock(): rtc = machine.RTC() print("Synchronize time from NTP server ...") lcd.println("Synchronize time from NTP server ...") rtc.ntp_sync(server="cn.ntp.org.cn") lcd.clear() lcd.setBrightness(200) lcd.font(lcd.FONT_7seg, fixedwidth=True, dist=16, width=2) while True: d = time.strftime("%Y-%m-%d", time.localtime()) t = time.strftime("%H:%M:%S", time.localtime()) lcd.print(d, lcd.CENTER, 50, lcd.ORANGE) lcd.print(t, lcd.CENTER, 130, lcd.ORANGE) time.sleep(1) _thread.start_new_thread('Clock', clock, ())
  19. 57.

    M5Stackϓϩάϥϛϯά Wi-Fi ʹ઀ଓ͢Δ ‣ ઀ଓˠCPPUQZ ‣ ֬ೝ import network wlan

    = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid, pwd) if wlan.isconnected(): …
  20. 58.

    M5Stackϓϩάϥϛϯά Wi-Fi AP ΛεΩϟϯ ‣ εΩϟϯྫ ‣ >>> import network

    >>> wlan = network.WLAN(network.STA_IF) >>> for ap in wlan.scan(): ... print(ap) ... (b'ssid', b’\x10101010', 4, -84, 4, 'WPA_WPA2_PSK', False)
  21. 59.

    M5Stackϓϩάϥϛϯά time(utime)Ϟδϡʔϧ >>> import time >>> time.localtime() (2018, 5, 12,

    21, 36, 42, 7, 132) >>> time.gmtime() (2018, 5, 12, 13, 36, 47, 7, 132) >>> time.strftime("%Y-%m-%d %H:%M:%S%z") '2018-05-12 13:37:13+0800’ >>> time.strftime("%Y-%m-%d %H:%M:%S%z", time.gmtime()) '2018-05-12 13:37:21+0000’ >>> time.strftime("%Y-%m-%d %H:%M:%S%z", time.localtime()) '2018-05-12 21:37:25+0000'
  22. 61.

    +45Ͱऔಘ M5Stackϓϩάϥϛϯά NTP >>> import time >>> time.localtime() (2018, 5,

    12, 23, 8, 31, 7, 132) >>> time.gmtime() (2018, 5, 12, 14, 8, 36, 7, 132) >>> time.strftime('%Y-%m-%d %H:%M:%S%z') '2018-05-12 14:08:50+0900' >>> time.strftime('%Y-%m-%d %H:%M:%S%z', time.gmtime()) '2018-05-12 14:08:57+0000' >>> time.strftime('%Y-%m-%d %H:%M:%S%z', time.localtime()) '2018-05-12 23:09:01+0000'
  23. 64.

    M5Stackϓϩάϥϛϯά HTTP ΫϥΠΞϯτ - urequests ‣ (&5 >>> res =

    urequests.get('https://unkobtn.com/') >>> print(res.status_code) 200
  24. 65.

    M5Stackϓϩάϥϛϯά HTTP ΫϥΠΞϯτ - urequests ‣ 1045 URL = ‘https://maker.ifttt.com/trigger/ev/with/key/..’

    r = urequests.post(URL, json={'value1': 'M5Stack'}, headers={'Content-Type': 'application/json'}, ) lcd.println(r.text)
  25. 67.

    M5Stackϓϩάϥϛϯά HTTP ΫϥΠΞϯτ - urequests ‣ $1ZUIPOͷSFRVFTUTͷ৔߹ >>> requests.get('https://192.168.11.6:4433/hello') Traceback

    (most recent call last): ... requests.exceptions.SSLError: HTTPSConnectionPool(host='localhost', port=4433): Max retries exceeded with url: /hello (Caused by SSLError(SSLError(1, '[SSL: CER TIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c: 777)'),))
  26. 68.

    M5Stackϓϩάϥϛϯά HTTP ΫϥΠΞϯτ - urequests ‣ $1ZUIPOͷSFRVFTUTͰWFSJGZ'BMTFΛࢦఆͨ͠৔߹ >>> requests.get('https://192.168.11.6:4433/hello', verify=False)

    /Users/mitszo/.virtualenvs/py3w/lib/python3.6/site- packages/urllib3/connectionpo ol.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Addin g certificate verification is strongly advised. See: https://urllib3.readthedocs .io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) <Response [200]>
  27. 69.

    M5Stackϓϩάϥϛϯά HTTP ΫϥΠΞϯτ - urequests ‣ .JDSP1ZUIPOͷ৔߹ >>> import urequests

    >>> urequests.get('https://192.168.11.6:4433/hello') <Response object at 3ffcb9e0> >>> _.text 'Hello!\n'
  28. 70.

    M5Stackϓϩάϥϛϯά HTTP ΫϥΠΞϯτ - urequests ‣ ࢀߟ"SEVJOP*%&ͷ৔߹ʢূ໌ॻͷࢦఆ͕ඞཁʣ const char* root_ca

    = \ "-----BEGIN CERTIFICATE-----\n" “MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMA...” void PostMessage() { http.begin(URL, root_ca); http.addHeader("Content-Type", "application/json; charset=utf-8"); String reqBody = "{\"value1\": \"M5Stack\"}"; int status_code = http.POST(reqBody); String body = http.getString() ...
  29. 72.

    M5Stackϓϩάϥϛϯά Թ࣪౓ɾؾѹηϯαʔΛ࢖͏ def main(): ntpsync() i2c = I2C(scl=Pin(22), sda=Pin(21)) bme

    = bme280.BME280(i2c=i2c) while True: lcd.font(lcd.FONT_DejaVu18) lcd.text(30, 30, utime.strftime( ‘%Y-%m-%d %H:%M:%S', utime.localtime())) lcd.font(lcd.FONT_DejaVu24) values = bme.values lcd.print(values[0], lcd.RIGHT, 80) lcd.print(values[1], lcd.RIGHT, 110) lcd.print(values[2], lcd.RIGHT, 140) utime.sleep(1)