chakokuのブログ(rev4)

テック・コミック・DTM・・・ごくまれにチャリ

M5 ATOM MatrixにMicroPythonを入れてNeoPixcelを光らせる

小さくてかわいいMatrixを買った。

MicroPythonが動くようなので入れてみる。
FirmはMicroPythonのDLサイトから入手できる
MicroPython - Python for microcontrollers

MicroPythonのサイトでは転送レートが460800bpsになっているのだが、これだと自分の場合はエラーになった。
115200に変更する。以下のコマンドでFirmを焼いた

export PORT=/dev/ttyS19
export FIRM=M5STACK_ATOM-20230426-v1.20.0.bin
esptool.py --chip esp32 --port $PORT  erase_flash
esptool.py --chip esp32 --port $PORT --baud 115200 write_flash -z 0x1000 $FIRM

起動すると以下のような感じ

MicroPython v1.20.0 on 2023-04-26; M5Stack ATOM with ESP32-PICO-D4
Type "help()" for more information.
>>> help('modules')
__main__          framebuf          uasyncio/stream   upysh
_boot             gc                ubinascii         urandom
_onewire          inisetup          ubluetooth        ure
_thread           math              ucollections      urequests
_uasyncio         micropython       ucryptolib        uselect
_webrepl          mip/__init__      uctypes           usocket
apa106            neopixel          uerrno            ussl
atom              network           uhashlib          ustruct
btree             ntptime           uheapq            usys
builtins          onewire           uio               utime
cmath             uarray            ujson             utimeq
dht               uasyncio/__init__ umachine          uwebsocket
ds18x20           uasyncio/core     umqtt/robust      uzlib
esp               uasyncio/event    umqtt/simple      webrepl
esp32             uasyncio/funcs    uos               webrepl_setup
flashbdev         uasyncio/lock     uplatform
Plus any modules on the filesystem
>>> gc.mem_free()
108800

Git等のソースを見ないと詳細分からないが、ATOM用にモジュールが追加されている。Matixを手抜きで楽に光らせたい。

>>> import atom
>>> dir(atom)
['__class__', '__name__', 'const', '__dict__', '__file__', 'Pin', 'neopixel', 'ATOM', 'Lite', 'Matrix', 'WS2812_PIN', 'BUTTON_PIN', 'IR_PIN', 'I2C0_SCL_PIN', 'I2C0_SDA_PIN', 'GROVE_PORT_PIN']

Gitのソースは以下
micropython/atom.py at master · micropython/micropython · GitHub
Matrixの定義は以下

class Matrix(ATOM):
    # WS2812 number: 25
    def __init__(self):
        super(Matrix, self).__init__(np_n=25)

25というのは、NeoPixelの数だろう。5x5なので
superに投げて初期化してるようだ。上位クラスがATOMで下位クラスがMatrixになっている。素性の違うオブジェクトを上下の関係にしていいのか??*1

    def set_pixel_color(self, num, r, g, b):
        if num <= self._np.n:
            self._np[num] = [r, g, b]
            self._np.write()

細かいことはおいといて、、Gitのソースを読むと、上記のように関数が定義されており、set_pixcel_colorを呼べば光らせられるはず。
以下のコードをREPLから打ち込む

from atom import Matrix
m = Matrix()
m.set_pixel_color(12,0xf,0xf,0xf)

NeoPixcelで構成されるMatrixの中央が光った。(3,3)の位置(行列は1スタートで書いています)

まとめ
ファームを焼く時にエラーになったり、Matrix光らせるのに調べたりと多少手間取ったが、少しの時間でMicroPythonを焼いてNeoPixcelを光らせることができた。コンパイルエラーも起きないし、MicroPythonは楽ちんですばらしい。

*1:これは自分の勘違いで、上位クラスは素のAtom、下位クラスは2つ存在して、下位クラス(1)は、Atom_Lite、下位クラス(2)はAtom_Matrixであった。だからMatrixというクラスは表示用デバイスのMatrixではなく、商品名としてのMatrixなのであった