CircuitPython

2021年2月 7日 (日)

MicroPython/CircuitPython Performance Test

2021/2/7

MicroPython CircuitPython Performace Test (v2)

MicroPython CircuitPython Performace Test (v2)

概要

MicroPython/CircuitPython Performance Test この記事は「 MicroPython Performance Test 」を見直して新たな結果を追加した第2版にあたる。

pyborad/STM32用MicroPythonスクリプト

PerformaceTest.py

# Peformace Test import pyb def performanceTest(): millis = pyb.millis endTime = millis() + 10000 count = 0 while millis() < endTime: count += 1 print("Count: ", count) performanceTest()

ESP32/ESP8266用MicroPythonスクリプト

PerformaceTestESP32.py

# Peformace Test for ESP32 from machine import RTC rtc = RTC() rtc.datetime((2020, 2, 9, 1, 12, 48, 0, 0)) # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) def performanceTest(): secs = rtc.datetime()[6] endTime = secs + 10 count = 0 while rtc.datetime()[6] < endTime: count += 1 print("Count: ", count) performanceTest()

PC/BareMetal-RpiZeo/Linux-Rpizero/Maixduino用スクリプト

PerformanceRpiZero.py

# Peformace Test RpiZero import time def performanceTest(): msec = time.ticks_ms endTime = msec() + 10000 count = 0 while msec() < endTime: count += 1 print("Count: ", count) performanceTest()

CC3200用MicroPythonスクリプト

PerformanceTestCC3200.py

# Peformace Test for CC3200 from machine import RTC rtc = RTC(datetime=(2020, 2, 9, 10, 11, 0, 0, None)) def performanceTest(): secs = rtc.now()[5] endTime = secs + 10 count = 0 while rtc.now()[5] < endTime: count += 1 print("Count: ", count) performanceTest()

CircuitPython/Python3用スクリプト

performanceTestCPY.py

# Peformace Test CircuitPython from time import monotonic_ns def performanceTest(): endTime = monotonic_ns() + 10000000000 # 10 sec count = 0 while monotonic_ns() < endTime: count += 1 print("Count: ", count) performanceTest()

XIAO CircuitPython用スクリプト

PerformanceCircuitPython_XIAO.py

# Peformace Test XIAO CircuitPython from time import monotonic def performanceTest(): endTime = monotonic() + 10.0 # 10 sec count = 0 while monotonic() < endTime: count += 1 print("Count: ", count) performanceTest()

実行例

# pyboard/STM32の場合 $ ./pyboard.py --device /dev/ttyACM0 PerformanceTest.py Count: 2825625 # ESP32/ESP866の場合 $ ./pyboard.py --device /dev/ttyUSB0 PerformanceTestESP32.py Count: 39187

結果

ボード名 M/C/P Count
F767ZI M 5,676,566
F446RE M 2,825,625
F4Disco M 2,882,769
Maixduino M 2,218,879
Pico-MP M 1,507,516
F401RE M 1,362,752
L476RG M 1,089,347
PyPortal C 474,734
Grand-Central-M4-Express C 445,404
Feather-M4-Express C 438,444
Teensy4.0 C 432,413
Pico-CPY C 341,033
XIAO C 174,388
Circuit-Playground-Express C 121,800
ESP8266 M 64,049
ESP32 M 39,187
CC3200 M 5,529
BareMetal-RpiZero M 680,525
Linux-RpiZero P 6,370,022
PC(linux) P 161,265,687
micropython-Rpi4 M 16,117,283
python3-Rpi4 P 11,359,199


M/C/Pは、pythonの種類を表し、
M:MicroPython、
C:CircuitPython、
P:Python3
を表す。

コメント

・Pico-MPは、RPI_Picoボードの MicroPython、Pico-CPYは、RPI_PicoボードのCircuitPythonを意味する。

・BareMetal-RpiZeroは、RpiZeroでのBareMetalのmicropython、 Linux-RpiZeroは、linux上でのmicropython、 PC(Linux)は、PCのLinux上でのmicropythonを意味する。

・MaixduinoはMaixduinoのmicropythonであるMaixPyを意味する。

・Teensy4.0はTeensy4.0のCircuitPythonを意味する。

・python3-Rpi4は「python3 performanceCircuitPython.py」の数字、 micropython-Rpi4は「micropython performanceCircuitPython.py」の数字を意味する。

なお、PC(linux)のCPUは、「Intel® Core™ i7-3520M CPU @ 2.90GHz × 4 )」である。

・STM32系(F7xx/F4xx/L4xx)がESP32/ESP8266に比べてダントツに速いようだ。

・Linux-RpiZeroとBareMetal-RpiZeroの数字の違いはCPUキャッシュの有効/無効の差と思われる。

・CC3200は、他のMicroPythonボードに比べて極端に遅い結果だが、省電優先設計のせいだと思われる。

・Teensy4.0のCircuitPythonはmonotonic_ns()のオーバーヘッドが大きい気がする。

・XIAOとCircuit-Playground-Expressは、同じプロセッサATSAMD21(Cortex-M0+,48MHz)にもかかわらず、性能差が出ているのは実装の違いで、XIAOのほうは、floatで動いているのに対して、Circuit-Playground-Expressのほうは、long_intで動いていることによる差が出ていると考えている。

・Pico-MP,Pico-CPYはCortex-M0であるがクロックが他のM0より高いこと(最大133Mz)と浮動小数点ライブラリが最適化されていることでM4並みの性能が出ているようだ。MP,CPYの性能差は最適化が進んでいるかどうかの差と思われる。

参照情報

PicoボードにMicropython/CircuitPythonをインストールする

RaspberryPiのpython3でCircuitPythonのAPIを使用する

XIAOにCircuitPythonをインストールする

Circuit-Playground-ExpressにCircuitPythonをインストールする

Teensy4.0にCurcuitPythonをインストールする

BareMetalのMicropythonをRaspberryPi_Zeroにインストールしてみる

NUCLEO-F767ZIにMicropythonをインストールする(v2)
Nucleo-L476RGにMicroPythonをインストールする
Nucleo-F401REにMicroPythonをインストールする
STM32F4-Discovery」にMicroPythonをインストールする
NUCLEO-F446REにMicropythonをインストールする(v2)
NUCLEO F446RE MicroPython インストール方法

CC3200 MicroPython インストール

ESP32のMicroPythonのインストール方法
ESP-WROOM-02 MicroPython インストール方法

MicroPythonのツールとしてpyboad.pyを使う
The pyboard.py tool

ESP32-DevKitC ESP-WROOM-32開発ボード
MicroPython - Quick reference for the ESP32

ampyを用いたMicroPythonのファイル操作とプログラム実行

以上

続きを読む "MicroPython/CircuitPython Performance Test"

| | コメント (0)

2021年2月 3日 (水)

PicoボードにMicropython/CircuitPythonをインストールする

2021/2/3

rpi Pico MicroPython/CircuitPython Install

rpi Pico MicroPython/CircuitPython Install

概要

以下のPicoボードにMicropython/CircuitPythonをインストールする方法について記載する。
(ホストPCとしてはubuntuを想定している)

Raspberry Pi Pico

MicroPytho PreBuild

プリビルドしたファームウェアを使う場合
以下を手順でファームウェアをダウンロードする:

cd ~/Downloads wget https://www.raspberrypi.org/documentation/pico/getting-started/static/5d8e777377e8dbe23cf36360d6efc727/pico_micropython_20210121.uf2

このファームウェアを「ビルドしたファームウェアの書き込み」の手順で書き込む。

ソースからビルドする場合、以降の手順でビルドする。

事前準備

以下の手順でツールをインストールする:

sudo apt update sudo apt install gcc-arm-none-eabi build-essential # ビルド時にエラーになったのでcmake最新版をインストールする # 古いcmakeを削除する sudo apt remove cmake mkdir ~/cmake_latest cd ~/cmake_latest wget https://github.com/Kitware/CMake/releases/download/v3.17.1/cmake-3.17.1.tar.gz tar zxvf cmake-3.17.1.tar.gz cd cmake-3.17.1/ ./bootstrap make sudo make install

該当ツールのインストール

以下の手順でインストールする:

# pico SDK のダウンロード mkdir ~/pico git clone -b master https://github.com/raspberrypi/pico-sdk.git cd pico-sdk git submodule update --init # picotoolのインストール cd ~/pico git clone https://github.com/raspberrypi/picotool.git cd picotool mkdir build cd build export PICO_SDK_PATH=../../pico-sdk cmake .. make sudo cp picotool /usr/local/bin/ # elf2uf2のインストール cd ~/pico cd pico-sdk/tools/elf2uf2 mkdir build cd build export PICO_SDK_PATH=../../../../pico-sdk cmake .. make sudo cp elf2uf2 /usr/local/bin/ # pioasmのインストール cd ~/pico cd pico-sdk/tools/pioasm mkdir build cd build export PICO_SDK_PATH=../../../../pico-sdk cmake .. make sudo cp pioasm /usr/local/bin/

MicroPython Build

以下の手順でビルドする:

cd ~/pico git clone -b pico https://github.com/raspberrypi/micropython.git cd micropython git submodule update --init -- lib/pico-sdk cd lib/pico-sdk git submodule update --init cd ../.. make -C mpy-cross cd ports/rp2 make clean make ls build CMakeCache.txt elf2uf2 firmware.elf.map frozen_mpy CMakeFiles firmware.bin firmware.hex generated Makefile firmware.dis firmware.uf2 genhdr cmake_install.cmake firmware.elf frozen_content.c pico_sdk

この時点でfirmware.*がビルドされる。 実際にPicoボードで書き込むのは、firmware.uf2になる。

ビルドしたファームウェアの確認

以下のやり方でファームウェアの内容を確認できる:

$ picotool info firmware.uf2 File firmware.uf2: Program Information name: MicroPython version: de1239b6a features: USB REPL thread support frozen modules: _boot, rp2, ds18x20, onewire, uasyncio, uasyncio/core, uasyncio/event, uasyncio/funcs, uasyncio/lock, uasyncio/stream

ビルドしたファームウェアの書き込み

以下の手順で書き込む:

# BOOTSELボタンを押しながらPicoボードをホストPCにUSB接続する。 # 接続後、BOOTSELボタンを離す。 cd build sudo cp firmwre.uf2 /media/<USER>/RPI-RP2

以上でfirmwareがボードに書き込まれる。
(<USER>の部分はホストの環境に合わせる)

動作確認(REPL)

picocomを使いボードとシリアルで通信する。
以下、通信例:

$ picocom /dev/ttyACM0 -b115200 MPY: soft reboot MicroPython de1239b6a on 2021-01-24; Raspberry Pi Pico with RP2040 Type "help()" for more information. >>> import os >>> os.uname() (sysname='rp2', nodename='rp2', release='1.13.0', version='de1239b6a on 2021-01-24 (GNU 6.3.1 MinSizeRel)', machine='Raspberry Pi Pico with RP2040') >>> >>> import gc >>> gc.collect() >>> gc.mem_free() 187904

オンライン・ヘルプ表示:

>>> help() Welcome to MicroPython! For online help please visit https://micropython.org/help/. For access to the hardware use the 'machine' module. RP2 specific commands are in the 'rp2' module. Quick overview of some objects: machine.Pin(pin) -- get a pin, eg machine.Pin(0) machine.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p methods: init(..), value([v]), high(), low(), irq(handler) machine.ADC(pin) -- make an analog object from a pin methods: read_u16() machine.PWM(pin) -- make a PWM object from a pin methods: deinit(), freq([f]), duty_u16([d]), duty_ns([d]) machine.I2C(id) -- create an I2C object (id=0,1) methods: readfrom(addr, buf, stop=True), writeto(addr, buf, stop=True) readfrom_mem(addr, memaddr, arg), writeto_mem(addr, memaddr, arg) machine.SPI(id, baudrate=1000000) -- create an SPI object (id=0,1) methods: read(nbytes, write=0x00), write(buf), write_readinto(wr_buf, rd_buf) machine.Timer(freq, callback) -- create a software timer object eg: machine.Timer(freq=1, callback=lambda t:print(t)) Pins are numbered 0-29, and 26-29 have ADC capabilities Pin IO modes are: Pin.IN, Pin.OUT, Pin.ALT Pin pull modes are: Pin.PULL_UP, Pin.PULL_DOWN Useful control commands: 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') >>> help('modules') __main__ framebuf uasyncio/__init__ uio _boot gc uasyncio/core uos _onewire machine uasyncio/event urandom _rp2 math uasyncio/funcs uselect _thread micropython uasyncio/lock ustruct _uasyncio onewire uasyncio/stream usys builtins rp2 ubinascii utime ds18x20 uarray ucollections Plus any modules on the filesystem >>> >>> >>>

MicroPython demo scripts

blink.py

from time import sleep from machine import Pin led = Pin(25, Pin.OUT) while True: led.value(1) sleep(0.1) led.value(0) sleep(0.1)

neopixel_ring.py

# Example using PIO to drive a set of WS2812 LEDs. import array, time from machine import Pin import rp2 # Configure the number of WS2812 LEDs. NUM_LEDS = 24 #16 PIN_NUM = 6 brightness = 0.2 @rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24) def ws2812(): T1 = 2 T2 = 5 T3 = 3 wrap_target() label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] wrap() # Create the StateMachine with the ws2812 program, outputting on pin sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM)) # Start the StateMachine, it will wait for data on its FIFO. sm.active(1) # Display a pattern on the LEDs via an array of LED RGB values. ar = array.array("I", [0 for _ in range(NUM_LEDS)]) ########################################################################## def pixels_show(): dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)]) for i,c in enumerate(ar): r = int(((c >> 8) & 0xFF) * brightness) g = int(((c >> 16) & 0xFF) * brightness) b = int((c & 0xFF) * brightness) dimmer_ar[i] = (g<<16) + (r<<8) + b sm.put(dimmer_ar, 8) time.sleep_ms(10) def pixels_set(i, color): ar[i] = (color[1]<<16) + (color[0]<<8) + color[2] def pixels_fill(color): for i in range(len(ar)): pixels_set(i, color) def color_chase(color, wait): for i in range(NUM_LEDS): pixels_set(i, color) time.sleep(wait) pixels_show() time.sleep(0.2) def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: return (0, 0, 0) if pos < 85: return (255 - pos * 3, pos * 3, 0) if pos < 170: pos -= 85 return (0, 255 - pos * 3, pos * 3) pos -= 170 return (pos * 3, 0, 255 - pos * 3) def rainbow_cycle(wait): for j in range(255): for i in range(NUM_LEDS): rc_index = (i * 256 // NUM_LEDS) + j pixels_set(i, wheel(rc_index & 255)) pixels_show() time.sleep(wait) BLACK = (0, 0, 0) RED = (255, 0, 0) YELLOW = (255, 150, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) WHITE = (255, 255, 255) COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE) print("fills") for color in COLORS: pixels_fill(color) pixels_show() time.sleep(0.2) print("chases") for color in COLORS: color_chase(color, 0.01) print("rainbow") rainbow_cycle(0)

pioで正確なタイミングを作っているせいか 今までのやり方のものよりも、安定して光る印象がある。

pio_blink.py

import time from rp2 import PIO, asm_pio from machine import Pin # Define the blink program. It has one GPIO to bind to on the set instruction, which is an output pin. # Use lots of delays to make the blinking visible by eye. @asm_pio(set_init=rp2.PIO.OUT_LOW) def blink(): wrap_target() set(pins, 1) [31] nop() [31] nop() [31] nop() [31] nop() [31] set(pins, 0) [31] nop() [31] nop() [31] nop() [31] nop() [31] wrap() # Instantiate a state machine with the blink program, at 1000Hz, with set bound to Pin(25) (LED on the rp2 board) sm = rp2.StateMachine(0, blink, freq=1000, set_base=Pin(25)) # Run the state machine for 3 seconds. The LED should blink. sm.active(1) #time.sleep(3) time.sleep(10) sm.active(0)

pio実装によるblinkになる。

pwn_fade.py

# Example using PWM to fade an LED. import time from machine import Pin, PWM # Construct PWM object, with LED on Pin(25). pwm = PWM(Pin(25)) # Set the PWM frequency. pwm.freq(1000) # Fade the LED in and out a few times. duty = 0 direction = 1 while True: for _ in range(8 * 256): duty += direction if duty > 255: duty = 255 direction = -1 elif duty < 0: duty = 0 direction = 1 pwm.duty_u16(duty * duty) time.sleep(0.001)

Performance Test for MicroPython

# Peformace Test import time def performanceTest(): msec = time.ticks_ms endTime = msec() + 10000 count = 0 while msec() < endTime: count += 1 print("Count: ", count) performanceTest()

以下が出力される:
Count: 1507516

thonny(pyhton用エディタ)

言うまでもなく、通常のエディタを使ってプログラムすることが可能だが、ここでは専用のエディタをインストールして使用してみる。

以下の手順でインストールする:

bash <(curl -s https://thonny.org/installer-for-linux) # ディスクトップにアイコンができる

起動/設定:

# 起動 # thonnyアイコンをクリックする # 設定 (1)実行後、picoボードをPCにUSB接続する (2)Tools/Options/Interpreterを選択する [Which interpreter or device should Thonny use for running your code?] のプルダウンメニューから以下を選ぶ: 「MicroPyton(Raspberry Pi Pico」 (3)「Port」のプルダウンメニューから実際に接続しているポート(/dev/ttyACM0など)を選択する

CircuitPythonダウンロード&書き込み

以下を手順でファームウェアをダウンロードする:

cd ~/Downloads wget https://downloads.circuitpython.org/bin/raspberry_pi_pico/en_US/adafruit-circuitpython-raspberry_pi_pico-en_US-6.2.0-beta.1.uf2

このファームウェアを「ビルドしたファームウェアの書き込み」の手順で書き込む。

REPL(CircuitPython)

Press any key to enter the REPL. Use CTRL-D to reload. Adafruit CircuitPython 6.2.0-beta.1 on 2021-01-27; Raspberry Pi Pico with rp2040 >>> soft reboot Auto-reload is on. Simply save files over USB to run them or enter REPL to disable. code.py output: Hello World! Code done running. Press any key to enter the REPL. Use CTRL-D to reload. Adafruit CircuitPython 6.2.0-beta.1 on 2021-01-27; Raspberry Pi Pico with rp2040 >>> import os >>> os.uname() (sysname='rp2040', nodename='rp2040', release='6.2.0', version='6.2.0-beta.1 on 2021-01-27', machine='Raspberry Pi Pico with rp2040') >>> list(5 * x + y for x in range(10) for y in [4, 2, 1]) [4, 2, 1, 9, 7, 6, 14, 12, 11, 19, 17, 16, 24, 22, 21, 29, 27, 26, 34, 32, 31, 39, 37, 36, 44, 42, 41, 49, 47, 46] >>> import gc >>> gc.collect() >>> gc.mem_free() 220640 >>> >>> import board >>> dir(board) ['__class__', 'A0', 'A1', 'A2', 'GP0', 'GP1', 'GP10', 'GP11', 'GP12', 'GP13', 'GP14', 'GP15', 'GP16', 'GP17', 'GP18', 'GP19', 'GP2', 'GP20', 'GP21', 'GP22', 'GP25', 'GP26', 'GP26_A0', 'GP27', 'GP27_A1', 'GP28', 'GP28_A2', 'GP3', 'GP4', 'GP5', 'GP6', 'GP7', 'GP8', 'GP9', 'LED']
>>> help() Welcome to Adafruit CircuitPython 6.2.0-beta.1! Please visit learn.adafruit.com/category/circuitpython for project guides. To list built-in modules please do `help("modules")`. >>> help("modules") __main__ collections microcontroller storage _bleio digitalio micropython struct _pixelbuf displayio msgpack supervisor adafruit_bus_device errno neopixel_write sys analogio fontio os terminalio array framebufferio pwmio time binascii gamepad random touchio bitbangio gc re ulab board io rp2pio usb_hid builtins json sdcardio usb_midi busio math sharpdisplay vectorio Plus any modules on the filesystem >>>

CircuitPython demo scripts

blink.py

# blink for CircuitPython from time import sleep import board import digitalio led = digitalio.DigitalInOut(board.LED) led.direction = digitalio.Direction.OUTPUT while True: led.value = True sleep(0.1) led.value = False sleep(0.1)

Performance Test for CircuitPython

# Peformace Test CircuitPython from time import monotonic_ns def performanceTest(): endTime = monotonic_ns() + 10000000000 # 10 sec count = 0 while monotonic_ns() < endTime: count += 1 print("Count: ", count) performanceTest()

以下が出力される:
Count: 341033

参照情報

Raspberry Pi Picoスタートガイド C/C++
Pico C/C++ SDK
Pico SDK docs

Pico Python SDK

Pico Pinout

Ubuntu 18.04 に Cmake の Latest Release をインストールする

NUCLEO-F767ZIにMicropythonをインストールする(v2)

MicroPython Performance Test

以上

続きを読む "PicoボードにMicropython/CircuitPythonをインストールする"

| | コメント (0)

2020年7月 2日 (木)

XIAOでMPL3115A2(気圧・高度・気温センサ)を使用する(CircuitPython版)

2020/7/2

CPY XIAO MPL115A2

CPY XIAO MPL115A2

概要

XIAOで以下のMPL3115A2(気圧・高度・気温センサ)を使用する(CircuitPython版)。 CircuitPythonのインストールについては「XIAOにCircuitPythonをインストールする」を参照のこと。 (ホストPCとしてはubuntuを想定している)

MPL115A2 - I2C Barometric Pressure/Temperature Sensor

接続

以下の接続でボードを接続する:

XIAO MPL3115A2
3V3 Vin
GND GND
SDA(D4) SDA
SCL(D5) SCL

The default I2C address is 0x60

外部ライブラリのインストール方法

adafruitのアーカイブから以下のものを CIRCUITPY/libにコピーする: adafruit_mpl3115a2.mpy adafruit_bus_device(ディレクトリ)

デモ・プログラム

testmpl3115a2.py

# Simple demo of the MPL3115A2 sensor. # Will read the pressure and temperature and print them out every second. # Author: Tony DiCola import time import board import busio import adafruit_mpl3115a2 # Initialize the I2C bus. i2c = busio.I2C(board.SCL, board.SDA) # Initialize the MPL3115A2. sensor = adafruit_mpl3115a2.MPL3115A2(i2c) # Alternatively you can specify a different I2C address for the device: # sensor = adafruit_mpl3115a2.MPL3115A2(i2c, address=0x10) # You can configure the pressure at sealevel to get better altitude estimates. # This value has to be looked up from your local weather forecast or meteorlogical # reports. It will change day by day and even hour by hour with weather # changes. Remember altitude estimation from barometric pressure is not exact! # Set this to a value in pascals: sensor.sealevel_pressure = 102250 # Main loop to read the sensor values and print them every second. while True: pressure = sensor.pressure print("Pressure: {0:0.3f} hPa".format(pressure/100)) altitude = sensor.altitude print("Altitude: {0:0.3f} meters".format(altitude)) temperature = sensor.temperature print("Temperature: {0:0.3f} degrees Celsius".format(temperature)) print(""); time.sleep(1.0)

出力例

picocom /dev/ttyACM0 -b115200 ... <省略> ... Press any key to enter the REPL. Use CTRL-D to reload. Adafruit CircuitPython 5.3.0 on 2020-04-29; Seeeduino XIAO with samd21g18 >>> import testmpl3115a2 Pressure: 1001.597 hPa Altitude: 173.003 meters Temperature: 30.187 degrees Celsius Pressure: 1001.575 hPa Altitude: 172.753 meters Temperature: 30.187 degrees Celsius Pressure: 1001.632 hPa Altitude: 172.753 meters Temperature: 30.187 degrees Celsius Pressure: 1001.580 hPa Altitude: 173.128 meters Temperature: 30.187 degrees Celsius ...

参考情報

Seeeduino XIAO

XIAO Schematic
XIAO Pinout

Seeeduino XIAO Get Started By Nanase
コインサイズ Arduino互換機 Seeeduino XIAO を使ってみた

以上

続きを読む "XIAOでMPL3115A2(気圧・高度・気温センサ)を使用する(CircuitPython版)"

| | コメント (0)

XIAOでMCP9808(温度センサ)を使用する(CircuitPython版)

2020/7/2

CPY XIAO MCP9808

CPY XIAO MCP9808

概要

XIAOで以下のMCP9808(温度センサ)を使用する(CircuitPython版)。 CircuitPythonのインストールについては「XIAOにCircuitPythonをインストールする」を参照のこと。 (ホストPCとしてはubuntuを想定している)

Adafruit MCP9808 Precision I2C Temperature Sensor Guide

接続

以下の接続でボードを接続する:

XIAO MCP9808
3V3 Vdd
GND GND
SDA(D4) SDA
SCL(D5) SCL

The default I2C address is 0x18

外部ライブラリのインストール方法

adafruitのアーカイブから以下のものを CIRCUITPY/libにコピーする: adafruit_mcp9808.mpy adafruit_bus_device(ディレクトリ)

デモ・プログラム

testmcp9808.py

import time import board import busio import adafruit_mcp9808 i2c_bus = busio.I2C(board.SCL, board.SDA) # To initialise using the default address: mcp = adafruit_mcp9808.MCP9808(i2c_bus) # To initialise using a specified address: # Necessary when, for example, connecting A0 to VDD to make address=0x19 # mcp = adafruit_mcp9808.MCP9808(i2c_bus, address=0x19) while True: tempC = mcp.temperature tempF = tempC * 9 / 5 + 32 print("Temperature: {} C {} F ".format(tempC, tempF)) time.sleep(2)

出力例

picocom /dev/ttyACM0 -b115200 ... <省略> ... Press any key to enter the REPL. Use CTRL-D to reload. Adafruit CircuitPython 5.3.0 on 2020-04-29; Seeeduino XIAO with samd21g18 >>> import testmcp9808 Temperature: 31.5 C 88.7 F Temperature: 31.4375 C 88.5875 F Temperature: 31.5 C 88.7 F Temperature: 31.5 C 88.7 F Temperature: 31.5 C 88.7 F Temperature: 31.5625 C 88.8125 F Temperature: 31.5 C 88.7 F ... ...

参考情報

Seeeduino XIAO

XIAO Schematic
XIAO Pinout

Seeeduino XIAO Get Started By Nanase
コインサイズ Arduino互換機 Seeeduino XIAO を使ってみた

以上

続きを読む "XIAOでMCP9808(温度センサ)を使用する(CircuitPython版)"

| | コメント (0)

2020年6月 9日 (火)

XIAOにCircuitPythonをインストールする

2020/6/9

XIAO CircuitPython Install

XIAO CircuitPython Install

概要

以下のXIAOにCircuitPythonをインストールする方法について記載する。 (ホストPCとしてはubuntuを想定している)

Seeeduino XIAO

事前準備

(1)picocomのインストール

sudo apt-get install picocom

bootloader mode

XIAにfirmwareを書き込めるモードを「bootloader mode」といい、このモードでは、USBストレージとしてarduinoディレクトリが現れる。 RSTピンを2度(GNDと)ショートすることで、このモードに入る。

CircuitPythonの書き込み

以下の手順でCircuitPythonを書き込む:

wget https://downloads.circuitpython.org/bin/seeeduino_xiao/en_US/adafruit-circuitpython-seeeduino_xiao-en_US-5.3.0.uf2 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp adafruit-circuitpython-seeeduino_xiao-en_US-5.3.0.uf2 /media/USER_NAME/Arduino/ # ファームウェアの書き込みが実行されて、完了後、CIRCUITPYが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

動作確認(REPL)

以上、CircuitPythonのインストールが終わったので、picocomを使いXIAOとシリアルで通信する。(REPL)

以下、通信(REPL)例:

$ picocom /dev/ttyACM0 -b115200 Adafruit CircuitPython 5.3.0 on 2020-04-29; Seeeduino XIAO with samd21g18 >>> import os >>> os.uname() (sysname='samd21', nodename='samd21', release='5.3.0', version='5.3.0 on 2020-04-29', machine='Seeeduino XIAO with samd21g18') >>> import gc >>> gc.collect() >>> gc.mem_free() 21664 >>> help('modules') __main__ digitalio pulseio sys analogio gc random time array math rotaryio touchio board microcontroller rtc usb_hid builtins micropython storage usb_midi busio neopixel_write struct collections os supervisor Plus any modules on the filesystem >>> >>> 10000000000 OverflowError: long int not supported in this build >>> 10_000_000_000 OverflowError: long int not supported in this build >>> 1_000_000_000 1000000000 # code_size削減のためにlong_intはサポートされていない

mpy library install

以下の手順でmpyライブラリをインストールする:

wget https://github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/download/20200522/adafruit-circuitpython-bundle-5.x-mpy-20200522.zip unzip adafruit-circuitpython-bundle-5.x-mpy-20200522.zip cd adafruit-circuitpython-bundle-5.x-mpy-20200522 # ドラッグ&ドロップか、libの内容をCIRCUITPY/libにコピーするが # CIRCUITPYの容量が小さいので必要なもののみをコピーする # デモスクリプトで必要なもので言えば以下をコピーする: adafruit_framebuf.mpy adafruit_pypixelbuf.mpy neopixel.mpy font5x8.bin # font5x8.binは以下でダウンロードする: wget https://github.com/adafruit/Adafruit_CircuitPython_framebuf/raw/master/examples/font5x8.bin

blink.py

import time import board from digitalio import DigitalInOut, Direction led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT while True: led.value = True time.sleep(0.1) led.value = False time.sleep(0.1)

analogin_test

analogin_test.py

import time import board from analogio import AnalogIn analog_in = AnalogIn(board.A0) # Analog pin on Seeedino XIAO def get_voltage(pin): return (pin.value * 3.3) / 65536 while True: print("Voltage: ", get_voltage(analog_in)) time.sleep(0.1)

AOがアナログ入力になっているので、簡単なtestとしては A0をGNDまたは3V3に繋いでアナログ入力の機能を確認できる。

neoflashデモ

disp_text_neoflash.py

# disply text on NeoFlash import time import board import neopixel pixel_pin = board.D4 num_pixels = 126 ORDER = neopixel.GRB pixels = neopixel.NeoPixel( pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER ) #----------------------------- # framebuffer related import adafruit_framebuf # pixel size for display WIDTH = 18 HEIGHT = 7 fbuf = bytearray(round(WIDTH * HEIGHT / 8)+2) fb = adafruit_framebuf.FrameBuffer(fbuf, WIDTH, HEIGHT,adafruit_framebuf.MVLSB) #------------------------------- # buffer to NeoFlash(Neopixel) def buffer2pixels(the_fb,fcolor,bcolor): pos = 0 for y in range(the_fb.height): for x in range(the_fb.width): if fb.pixel(x, y): pixels[pos]=fcolor else: pixels[pos]=bcolor pos += 1 pixels.show() #------------------------------- # (for debug) Ascii printer for very small framebufs! def print_buffer(the_fb): print("." * (the_fb.width+2)) for y in range(the_fb.height): print(".", end='') for x in range(the_fb.width): if fb.pixel(x, y): print("*", end='') else: print(" ", end='') print(".") print("." * (the_fb.width+2)) # clear framebuffer def clear_fbuf(): for i, _ in enumerate(fbuf): fbuf[i] = 0 #---------------------------------- print("Text test: ") clear_fbuf() fb.text("ABC", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(15,0,0),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("012", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(15,0,0),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("345", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(0,15,0),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("678", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(0,0,15),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("9AB", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(int(255/4),int(213/4),int(40/4)),(0,0,0)) time.sleep(1) clear_fbuf() fb.text("abc", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(128,0,128),(0,0,0)) time.sleep(1)

接続は以下のようにする:

NeoFlash XIAO
GND GND
5V0 3.3V
G26 D4

本来、5V動作のようだが、3.3Vでも動作する。

neoflashの詳細は以下を参照のこと:
M5StickC NeoFlash Hat

Performance Test

performanceCircuitPython_XIAO.py

# Peformace Test XIAO CircuitPython from time import monotonic def performanceTest(): endTime = monotonic() + 10.0 # 10 sec count = 0 while monotonic() < endTime: count += 1 print("Count: ", count) performanceTest()

コードサイズ削減のため実装されていない機能があるので、 XIAO用のperformanceTestになっている。

出力結果(例):
Count: 174388

参照URL

Seeeduino XIAO

XIAO Schematic
XIAO Pinout

Build CircuitPython
Adding Frozen Modules

Adafruit CircuitPython API Reference(v5.x)

CircuitPython Essentials
Example Code

以上

続きを読む "XIAOにCircuitPythonをインストールする"

| | コメント (0)

2020年6月 2日 (火)

CircuitPythonでNeoFlashにテキストを表示する

2020/6/2

CircuitPython NeoFlash Disp Text

CircuitPython NeoFlash Disp Text

概要

CircuitPythonで以下のNeoFlashにテキストを表示する。 ここでは、Feather-M4-ExpressのCircuitPythonを使用する。なお、NeoFlashは、M5StickC用であるが、neopixel互換なので neopixelとして動かす。 (以下、ホストPCとしてはubuntuを想定している)

M5StickC NeoFlash Hat

接続

以下のように接続する:

NeoFlash FeartherM4
GND GND
5V0 3.3V
G26 D4

本来、5V動作のようだが、3.3Vでも動作する。

準備

フォントデータfont5x8.binをCIRCUITPYのディレクトリにコピーする:

# framebufで使用するフォントをダウンロードする wget https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/master/examples/font5x8.bin cp font5x8.bin CIRCUITPY/

デモ・スクリプト

disp_text_neoflash.py

# disply text on NeoFlash import time import board import neopixel pixel_pin = board.D4 num_pixels = 126 ORDER = neopixel.GRB pixels = neopixel.NeoPixel( pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER ) #----------------------------- # framebuffer related import adafruit_framebuf # pixel size for display WIDTH = 18 HEIGHT = 7 fbuf = bytearray(round(WIDTH * HEIGHT / 8)+2) fb = adafruit_framebuf.FrameBuffer(fbuf, WIDTH, HEIGHT,adafruit_framebuf.MVLSB) #------------------------------- # buffer to NeoFlash(Neopixel) def buffer2pixels(the_fb,fcolor,bcolor): pos = 0 for y in range(the_fb.height): for x in range(the_fb.width): if fb.pixel(x, y): pixels[pos]=fcolor else: pixels[pos]=bcolor pos += 1 pixels.show() #------------------------------- # (for debug) Ascii printer for very small framebufs! def print_buffer(the_fb): print("." * (the_fb.width+2)) for y in range(the_fb.height): print(".", end='') for x in range(the_fb.width): if fb.pixel(x, y): print("*", end='') else: print(" ", end='') print(".") print("." * (the_fb.width+2)) # clear framebuffer def clear_fbuf(): for i, _ in enumerate(fbuf): fbuf[i] = 0 #---------------------------------- print("Text test: ") clear_fbuf() fb.text("ABC", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(15,0,0),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("012", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(15,0,0),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("345", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(0,15,0),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("678", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(0,0,15),(15,15,15)) time.sleep(1) clear_fbuf() fb.text("9AB", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(int(255/4),int(213/4),int(40/4)),(0,0,0)) time.sleep(1) clear_fbuf() fb.text("abc", 0, 0, 1) print_buffer(fb) buffer2pixels(fb,(128,0,128),(0,0,0)) time.sleep(1)

framebufferを利用してテキストを表示している。 framebufferのフォーマットとしてRGB565を使用したかったが未実装のようなのでMVLSBを使用した。

なお、デバッグ用にREPL画面にframebufferの内容を「*」を使ってテキスト表示している。

参照情報

M5Stack Docs - Neoflash HAT

Adafruit Feather M4 Express PINOUTS
Adafruit Feather M4 Express Overview

Adafruit-Feather-M4-ExpressにCircuitPythonをインストールする

Build CircuitPython
Adding Frozen Modules

Adafruit CircuitPython API Reference(v5.x)

CircuitPython Essentials
Example Code

以上

続きを読む "CircuitPythonでNeoFlashにテキストを表示する"

| | コメント (0)

2020年5月28日 (木)

NeoFlashをCircuitPythonで動かす

2020/5/28

CircuitPython NeoFlash

CircuitPython NeoFlash

概要

以下のNeoFlashをCircuitPythonで動かす。 ここでは、Feather-M4-ExpressのCircuitPythonを使用する。なお、NeoFlashは、M5StickC用であるが、neopixel互換なので neopixelとして動かす。 (以下、ホストPCとしてはubuntuを想定している)

M5StickC NeoFlash Hat

## 接続 以下のように接続する:

NeoFlash FeartherM4
GND GND
5V0 3.3V
G26 D4

本来、5V動作のようだが、3.3Vでも動作する。

デモ・スクリプト

import time import board import neopixel # On CircuitPlayground Express, and boards with built in status NeoPixel -> board.NEOPIXEL # Otherwise choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D1 #pixel_pin = board.NEOPIXEL pixel_pin = board.D4 # The number of NeoPixels num_pixels = 126 # The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed! # For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW. ORDER = neopixel.GRB pixels = neopixel.NeoPixel( pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER ) def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos * 3) g = 0 b = int(pos * 3) else: pos -= 170 r = 0 g = int(pos * 3) b = int(255 - pos * 3) return (r, g, b) if ORDER in (neopixel.RGB, neopixel.GRB) else (r, g, b, 0) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): pixel_index = (i * 256 // num_pixels) + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) while True: # Comment this line out if you have RGBW/GRBW NeoPixels pixels.fill((255, 0, 0)) # Uncomment this line if you have RGBW/GRBW NeoPixels # pixels.fill((255, 0, 0, 0)) pixels.show() time.sleep(1) # Comment this line out if you have RGBW/GRBW NeoPixels pixels.fill((0, 255, 0)) # Uncomment this line if you have RGBW/GRBW NeoPixels # pixels.fill((0, 255, 0, 0)) pixels.show() time.sleep(1) # Comment this line out if you have RGBW/GRBW NeoPixels pixels.fill((0, 0, 255)) # Uncomment this line if you have RGBW/GRBW NeoPixels # pixels.fill((0, 0, 255, 0)) pixels.show() time.sleep(1) rainbow_cycle(0.001) # rainbow cycle with 1ms delay per step

circuitpythonの標準的なサンプルプログラムの出力ポートとneopixelの数をNeoFlashに合わせて変更したもの.

表示した印象では、添付のアクリル板を付けないと眩しすぎるで、取り付けたほうが良いと思う。

参照情報

M5Stack Docs - Neoflash HAT

Adafruit Feather M4 Express PINOUTS
Adafruit Feather M4 Express Overview

Adafruit-Feather-M4-ExpressにCircuitPythonをインストールする

Build CircuitPython
Adding Frozen Modules

Adafruit CircuitPython API Reference(v5.x)

CircuitPython Essentials
Example Code

以上

続きを読む "NeoFlashをCircuitPythonで動かす"

| | コメント (0)

2020年5月24日 (日)

Adafruit-Feather-M4-ExpressにCircuitPythonをインストールする

2020/5/24

Adafruit Feather M4 Express CircuitPython Install

Adafruit Feather M4 Express CircuitPython Installl

概要

以下のAdafruit-Feather-M4-ExpressにCircuitPythonをインストールする方法について記載する。
以降、Adafruit-Feather-M4-ExpressをFeatherM4とする。
(以下、ホストPCとしてはubuntuを想定している)

Adafruit Feather M4 Express

事前準備

(1)picocomのインストール

sudo apt-get install picocom

bootloader mode

FeatherM4にfirmwareを書き込めるモードを「bootloader mode」といい、このモードでは、USBストレージとしてFEATHERBOOTが現れる。 GCM4に事前に、どんなプログラムが書かれていたかで、やり方が異なる。 arduinoのプログラムかCircuitPythonのプログラムが書き込まれている場合、resetをdouble-clickのように2度押すと このモードに入りUSBストレージとしてFEATHERBOOTが現れる。その他の場合、resetを1度押すと、このモードに入る。

bootloader update

以下の手順でbootloaderをアップデートする:

# download wget https://github.com/adafruit/uf2-samdx1/releases/download/v3.10.0/update-bootloader-feather_m4-v3.10.0.uf2 # FeatherM4をホストPCにUSB接続して、リセットを2度押して、bootloader-modeに入る。 # このモードに入ると、FEATHERBOOTのディレクトリが現れる。 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp update-bootloader-feather_m4-v3.10.0.uf2 /media/USER_NAME/FEATHERBOOT/ # ファームウェアの書き込みが実行されて、完了後、FEATHERBOOTが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

CircuitPythonの書き込み

以下の手順でCircuitPythonを書き込む:

wget https://downloads.circuitpython.org/bin/feather_m4_express/en_US/adafruit-circuitpython-feather_m4_express-en_US-5.3.0.uf2 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp adafruit-circuitpython-feather_m4_express-en_US-5.3.0.uf2 /media/USER_NAME/FEATHERBOOT/ # ファームウェアの書き込みが実行されて、完了後、CIRCUITPYが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

REPL

次にpicocomを使ってREPLに入る。

以下、通信(REPL)例:

$ picocom /dev/ttyACM0 -b115200 Adafruit CircuitPython 5.3.0 on 2020-04-29; Adafruit Feather M4 Express with samd51j19 >>> import os >>> os.uname() (sysname='samd51', nodename='samd51', release='5.3.0', version='5.3.0 on 2020-04-29', machine='Adafruit Feather M4 Express with samd51j19') >>> >>> import gc >>> gc.collect() >>> gc.mem_free() 158976 >>> >>> help('modules') __main__ busio microcontroller storage _os collections micropython struct _pixelbuf digitalio neopixel_write supervisor _time displayio network sys analogio errno os terminalio array fontio ps2io time audiobusio framebufferio pulseio touchio audiocore frequencyio random ulab audioio gamepad re usb_hid audiomixer gc rgbmatrix usb_midi audiomp3 i2cslave rotaryio wiznet bitbangio io rtc board json samd builtins math socket Plus any modules on the filesystem >>>

mpy library install

以下の手順でmpyライブラリをインストールする:

wget https://github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/download/20200522/adafruit-circuitpython-bundle-5.x-mpy-20200522.zip unzip adafruit-circuitpython-bundle-5.x-mpy-20200522.zip cd adafruit-circuitpython-bundle-5.x-mpy-20200522 # ドラッグ&ドロップか、以下を実行して、libの内容をCIRCUITPY/libにコピーする cp -r lib /media/USER_NAME/CIRCUITCPY/lib # 実際に使用するライブラリだけが必要になるが、容量に余裕があるので、全部コピーする # 将来、容量が不足した不要なライブラリを削除すること

「USER_NAME」は実際の環境に合わせること。

サンプル・プログラム

neopixel_test.py

import time import board import neopixel # On CircuitPlayground Express, and boards with built in status NeoPixel -> board.NEOPIXEL # Otherwise choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D1 #pixel_pin = board.NEOPIXEL pixel_pin = board.D4 # The number of NeoPixels num_pixels = 64 # The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed! # For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW. ORDER = neopixel.GRB pixels = neopixel.NeoPixel( pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER ) def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos * 3) g = 0 b = int(pos * 3) else: pos -= 170 r = 0 g = int(pos * 3) b = int(255 - pos * 3) return (r, g, b) if ORDER in (neopixel.RGB, neopixel.GRB) else (r, g, b, 0) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): pixel_index = (i * 256 // num_pixels) + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) while True: # Comment this line out if you have RGBW/GRBW NeoPixels pixels.fill((255, 0, 0)) # Uncomment this line if you have RGBW/GRBW NeoPixels # pixels.fill((255, 0, 0, 0)) pixels.show() time.sleep(1) # Comment this line out if you have RGBW/GRBW NeoPixels pixels.fill((0, 255, 0)) # Uncomment this line if you have RGBW/GRBW NeoPixels # pixels.fill((0, 255, 0, 0)) pixels.show() time.sleep(1) # Comment this line out if you have RGBW/GRBW NeoPixels pixels.fill((0, 0, 255)) # Uncomment this line if you have RGBW/GRBW NeoPixels # pixels.fill((0, 0, 255, 0)) pixels.show() time.sleep(1) rainbow_cycle(0.001) # rainbow cycle with 1ms delay per step

neopixelのDINをD4に接続して「import neopixel_test」でプログラムを実行するとneopixelが色々な色で光る。
また、プログラムを以下のように変更するとボード上のneopixelが色を変えて光る。

pixel_pin = board.NEOPIXEL ... num_pixels = 1

Performance Test

performanceCircuitPython.py

# Peformace Test for CircuitPython from time import monotonic_ns def performanceTest(): endTime = monotonic_ns() + 10000000000 # 10 sec count = 0 while monotonic_ns() < endTime: count += 1 print("Count: ", count) performanceTest()

実行すると以下のような結果が得られる: Count: 438444

参照URL

Adafruit Feather M4 Express PINOUTS
Adafruit Feather M4 Express Overview

Build CircuitPython
Adding Frozen Modules

Adafruit CircuitPython API Reference(v5.x)

CircuitPython Essentials
Example Code

以上

続きを読む "Adafruit-Feather-M4-ExpressにCircuitPythonをインストールする"

| | コメント (0)

GRAND-CENTRAL-M4-EXPRESSにCircuitPythonをインストールする

2020/5/24

GRAND CENTRAL M4 EXPRESS CircuitPython Install

GRAND CENTRAL M4 EXPRESS CircuitPython Installl

概要

以下のADAFRUIT-GRAND-CENTRAL-M4-EXPRESSにCircuitPythonをインストールする方法について記載する。
以降、ADAFRUIT-GRAND-CENTRAL-M4-EXPRESSをGCM4とする。
(以下、ホストPCとしてはubuntuを想定している)

ADAFRUIT GRAND CENTRAL M4 EXPRESS

事前準備

(1)picocomのインストール

sudo apt-get install picocom

bootloader mode

GCM4にfirmwareを書き込めるモードを「bootloader mode」といい、このモードでは、USBストレージとしてGCM4BOOTが現れる。 GCM4に事前に、どんなプログラムが書かれていたかで、やり方が異なる。 arduinoのプログラムかCircuitPythonのプログラムが書き込まれている場合、resetをdouble-clickのように2度押すと このモードに入りUSBストレージとしてGCM4BOOTが現れる。その他の場合、resetを1度押すと、このモードに入る。

bootloader update

以下の手順でbootloaderをアップデートする:

# download wget https://github.com/adafruit/uf2-samdx1/releases/download/v3.10.0/update-bootloader-grandcentral_m4-v3.10.0.uf2 # GCM4をホストPCにUSB接続して、リセットを2度押して、bootloader-modeに入る。 # このモードに入ると、GCM4BOOTのディレクトリが現れる。 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp update-bootloader-grandcentral_m4-v3.10.0.uf2 /media/USER_NAME/GCM4BOOT/ # ファームウェアの書き込みが実行されて、完了後、GCM4BOOTが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

CircuitPythonの書き込み

以下の手順でCircuitPythonを書き込む:

wget https://downloads.circuitpython.org/bin/grandcentral_m4_express/en_US/adafruit-circuitpython-grandcentral_m4_express-en_US-5.3.0.uf2 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp adafruit-circuitpython-grandcentral_m4_express-en_US-5.3.0.uf2 /media/USER_NAME/GCM4BOOT/ # ファームウェアの書き込みが実行されて、完了後、CIRCUITPYが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

REPL

次にpicocomを使ってREPLに入る。

以下、通信(REPL)例:

$ picocom /dev/ttyACM0 -b115200 Adafruit CircuitPython 5.3.0 on 2020-04-29; Adafruit Grand Central M4 Express with samd51p20 >>> import os >>> os.uname() (sysname='samd51', nodename='samd51', release='5.3.0', version='5.3.0 on 2020-04-29', machine='Adafruit Grand Central M4 Express with samd51p20') >>> >>> import gc >>> gc.collect() >>> gc.mem_free() 222976 >>> >>> >>> >>> help('modules') __main__ busio microcontroller storage _os collections micropython struct _pixelbuf digitalio neopixel_write supervisor _time displayio network sys analogio errno os terminalio array fontio ps2io time audiobusio framebufferio pulseio touchio audiocore frequencyio random ulab audioio gamepad re usb_hid audiomixer gc rgbmatrix usb_midi audiomp3 i2cslave rotaryio wiznet bitbangio io rtc board json samd builtins math socket Plus any modules on the filesystem >>> >>>

mpy library install

以下の手順でmpyライブラリをインストールする:

wget https://github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/download/20200522/adafruit-circuitpython-bundle-5.x-mpy-20200522.zip unzip adafruit-circuitpython-bundle-5.x-mpy-20200522.zip cd adafruit-circuitpython-bundle-5.x-mpy-20200522 # ドラッグ&ドロップか、以下を実行して、libの内容をCIRCUITPY/libにコピーする cp -r lib /media/USER_NAME/CIRCUITCPY/lib # 実際に使用するライブラリだけが必要になるが、容量に余裕があるので、全部コピーする # 将来、容量が不足した不要なライブラリを削除すること

「USER_NAME」は実際の環境に合わせること。

サンプル・プログラム

CGM4_SD_tempe_log.py

import time import board import digitalio import microcontroller # make sdcard effective import adafruit_sdcard import busio import storage spi = busio.SPI(board.SD_SCK, board.SD_MOSI, board.SD_MISO) cs = digitalio.DigitalInOut(board.SD_CS) sdcard = adafruit_sdcard.SDCard(spi, cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") led = digitalio.DigitalInOut(board.D13) led.switch_to_output() try: with open("/sd/temperature.txt", "a") as fp: while True: temp = microcontroller.cpu.temperature fp.write('{0:f}\n'.format(temp)) print('{0:f}'.format(temp)) fp.flush() led.value = not led.value time.sleep(1) except OSError as e: delay = 0.5 if e.args[0] == 28: delay = 0.25 while True: led.value = not led.value time.sleep(delay)

REPLで「import GCM4_SD_tempe_log」で実行すると、ボード上のSDにCPU温度のログを残す。無限ループになっているので、Control-Cで止める必要がある。

Performance Test

performanceCircuitPython.py

# Peformace Test for CircuitPython from time import monotonic_ns def performanceTest(): endTime = monotonic_ns() + 10000000000 # 10 sec count = 0 while monotonic_ns() < endTime: count += 1 print("Count: ", count) performanceTest()

実行すると以下のような結果が得られる:
Count: 445404

参照URL

Adafruit Grand Central M4 Express PINOUTS
Adafruit Grand Central M4 Express Overview

Build CircuitPython
Adding Frozen Modules

Adafruit CircuitPython API Reference(v5.x)

CircuitPython Essentials
Example Code

以上

続きを読む "GRAND-CENTRAL-M4-EXPRESSにCircuitPythonをインストールする"

| | コメント (0)

2020年5月23日 (土)

PyPortalにCircuitPythonをインストールする

2020/5/24

PyPortal CircuitPython Install

PyPortal CircuitPython Install

概要

以下のPyPortalにCircuitPythonをインストールする方法について記載する。
工場出荷時に既にCircuitPythonがインストール済みなので 正確に言えば最新版にアップデートすることになる。 (ホストPCとしてはubuntuを想定している)

Adafruit PyPortal - CircuitPython IoTディスプレイ

事前準備

(1)picocomのインストール

sudo apt-get install picocom

bootloader mode

PyPortalにfirmwareを書き込めるモードを「bootloader mode」といい、このモードでは、USBストレージとしてPORTALBOOTが現れる。 PyPortalに事前に、どんなプログラムが書かれていたかで、やり方が異なる。 arduinoのプログラムかCircuitPythonのプログラムが書き込まれている場合、resetをdouble-clickのように2度押すと このモードに入りUSBストレージとしてPORTALBOOTが現れる。その他の場合、resetを1度押すと、このモードに入る。

工場出荷の状態では、CircuitPythonが入っているので 実際にはresetの2度押しで、このモードに入る。

bootloader update

以下の手順でbootloaderをアップデートする:

# download wget https://github.com/adafruit/uf2-samdx1/releases/download/v3.10.0/update-bootloader-pyportal_m4-v3.10.0.uf2 # PyPortalをホストPCにUSB接続して、リセットを2度押して、bootloader-modeに入る。 # このモードに入ると、PORTALBOOTのディレクトリが現れる。 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp update-bootloader-pyportal_m4-v3.10.0.uf2 /media/USER_NAME/PORTALBOOT/ # ファームウェアの書き込みが実行されて、完了後、PORTALBOOTが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

CircuitPythonの書き込み

以下の手順でCircuitPythonを書き込む:

wget https://downloads.circuitpython.org/bin/pyportal/en_US/adafruit-circuitpython-pyportal-en_US-5.3.0.uf2 # ファイルをドラッグ&ドロップするか、以下のコマンドを実行してファイルをコピーする cp adafruit-circuitpython-pyportal-en_US-5.3.0.uf2 /media/USER_NAME/PORTALBOOT/ # ファームウェアの書き込みが実行されて、完了後、CIRCUITPYが現れるまで待つ

「USER_NAME」は実際の環境に合わせること。

書き込んであるサンプルコードを最新版にアップデートする

以下の手順でアップデートする:

wget https://cdn-learn.adafruit.com/assets/assets/000/090/931/original/PyPortal_5x_demo_files.zip unzip PyPortal_5x_demo_files.zip cd boards/pyportal/5.x nano secrets.py #以下の内容を自分のネットワーク環境に合わせて変更する。
# This file is where you keep secret settings, passwords, and tokens! # If you put them in the code you risk committing that info or sharing it # which would be not great. So, instead, keep it all in this one file and # keep it a secret. secrets = { 'ssid' : 'CHANGE ME', # Keep the two '' quotes around the name 'password' : 'CHANGE ME', # Keep the two '' quotes around password 'timezone' : "America/New_York", # http://worldtimeapi.org/timezones 'aio_username' : 'YOUR_ADAFRUIT_ACCOUNT_USERNAME', 'aio_key' : 'YOUR_ADAFRUITIO_KEY', }

変更箇所:
'CHANGE ME'は、それぞれ自分の環境のssid,passwordに置き換える。
timezoneの設定は以下のように変更する:
"America/New_York" → "Asia/Tokyo"

続き:

# CIRCUITPYの内容を全削除する rm -r /media/USER_NAME/CIRCUITCPY/*.* # 内容全部をコピーする cd boards/pyportal/5.x cp -r *.* /media/USER_NAME/CIRCUITCPY/

全コピーが上手く行かない場合、 全削除した段階で再起動する(リセットする)
再起動後、全コピーする。

全コピーが終わって再起動した段階で デモプログラムが起動する。
動作としては、ネットワークにアクセスに行って LCDに偉人の名言(英語)が、つぎつぎとLCDに表示される。

REPL

以上で、CircuitPythonの最新版のアップデートが終わったことになる。
次にpicocomを使ってREPLに入る。

以下、通信(REPL)例:

$ picocom /dev/ttyACM0 -b115200 #デモプログラムを実行中なので #REPLに入るためにControl-Cを押す。 Traceback (most recent call last): File "code.py", line 35, in <module> KeyboardInterrupt: Code done running. Waiting for reload. Auto-reload is on. Simply save files over USB to run them or enter REPL to disable. Press any key to enter the REPL. Use CTRL-D to reload. #ここでEnterを押す。 Adafruit CircuitPython 5.3.0 on 2020-04-29; Adafruit PyPortal with samd51j20 >>> >>> >>> import os >>> os.uname() (sysname='samd51', nodename='samd51', release='5.3.0', version='5.3.0 on 2020-04-29', machine='Adafruit PyPortal with samd51j20') >>> >>> import gc >>> gc.collect() >>> gc.mem_free() 221056 >>> >>> help('modules') __main__ busio microcontroller storage _os collections micropython struct _pixelbuf digitalio neopixel_write supervisor _time displayio network sys analogio errno os terminalio array fontio ps2io time audiobusio framebufferio pulseio touchio audiocore frequencyio random ulab audioio gamepad re usb_hid audiomixer gc rgbmatrix usb_midi audiomp3 i2cslave rotaryio wiznet bitbangio io rtc board json samd builtins math socket Plus any modules on the filesystem >>> #Control-Dを押すとデモプログラムが再起動する。

mpy library install

デモプログラムには不要だが以下の手順でライブラリをインストールできる:
以下の手順でmpyライブラリをインストールする:

wget https://github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/download/20200522/adafruit-circuitpython-bundle-5.x-mpy-20200522.zip unzip adafruit-circuitpython-bundle-5.x-mpy-20200522.zip cd adafruit-circuitpython-bundle-5.x-mpy-20200522 # ドラッグ&ドロップか、以下を実行して、libの内容をCIRCUITPY/libにコピーする cp -r lib /media/USER_NAME/CIRCUITCPY/lib # 実際に使用するライブラリだけが必要になるが、容量に余裕があるので、全部コピーする # 将来、容量が不足した不要なライブラリを削除すること

「USER_NAME」は実際の環境に合わせること。

Performance Test

performanceCircuitPython.py

# Peformace Test for CircuitPython from time import monotonic_ns def performanceTest(): endTime = monotonic_ns() + 10000000000 # 10 sec count = 0 while monotonic_ns() < endTime: count += 1 print("Count: ", count) performanceTest()

実行すると以下のような結果が得られる:
Count: 474734

参照URL

PyPortal PINOUT
PyPortal Overview
Build the PyPortal Stand
Updating ESP32 Firmware
Uploading nina-fw with esptool

Build CircuitPython
Adding Frozen Modules

Adafruit CircuitPython API Reference(v5.x)

CircuitPython Essentials
Example Code

Cleveland Museum of Art PyPortal Frame
PyPortal IoT Weather Station

以上

続きを読む "PyPortalにCircuitPythonをインストールする"

| | コメント (0)

より以前の記事一覧