MicroPython

2021年5月 6日 (木)

microbit-v2にMicropythonをインストールする

2021/5/10
LCD表示スクリプトを追加した。

2021/5/6
初版

microbit-v2 MicroPython Install

microbit-v2 MicroPython Install

概要

microbit-v2にMicropythonをインストールする方法について記載する
webブラウザーから「micro:bit python editor」にアクセスしてプログラムを作成する方法があるが、ここではmicrobit-v2のボードにmicropythonインタープリタを書き込んで使用する。
(ホストPCとしてはubuntuを想定している)

注意:
microbit-v1のmicropythonの書き込み/実行には以下のエディタを使用すること。
micro:bit python editor

事前準備

(1)Thonny(pythonエディタ)
以下の手順でインストールする:

bash <(wget -O - https://thonny.org/installer-for-linux)

(2)picocom(通信ソフト)
以下の手順でインストールする:

sudo apt-get install picocom

ビルド手順

以下の手順でmicrobit-v2用のmicropythonをビルドする:

mkdir mb2_mp cd mb2_mp git clone https://github.com/microbit-foundation/micropython-microbit-v2.git cd micropython-microbit-v2 git submodule update --init make -C lib/micropython/mpy-cross cd src gedit Makefile # Makefileを自分のビルド環境にあわせて変更する

Makefile
以下の部分を自分の実行パスに合わせて変更する:
(実行パスは、which rm,which mkdirなどを実行すると分かる)

<省略> RM = /usr/bin/rm MKDIR = /usr/bin/mkdir PYTHON3 ?= python3 <省略>

続き:

make # makeが完了すると以下のようにMICROBIT.hexが生成される: ls MICROBIT.hex addlayouttable.py codal.patch codal_port Makefile build codal_app # miicrobit-v2ボードを接続してファームウェアを描き込む cp MICROBIT.hex /media/USER/MICROBIT/

以上でfirmwareがボードに書き込まれる。
・USERは環境依存なので、自分の環境に合わせること。

動作確認

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

$ picocom /dev/ttyACM0 -b115200 MPY: soft reboot MicroPython v1.15-64-g1e2f0d280 on 2021-05-06; micro:bit v2.0.0-beta.5 with nRF52833 Type "help()" for more information. >>> import os >>> os.uname() (sysname='microbit', nodename='microbit', release='2.0.0-beta.5', version='micro:bit v2.0.0-beta.5+c28e6bd-dirty on 2021-05-06; MicroPython v1.15-64-g1e2f0d280 on 2021-05-06', machine='micro:bit with nRF52833') >>> import gc >>> gc.collect() >>> gc.mem_free() 62272 >>> 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] >>> >>> dir() ['pin_logo', 'panic', 'pin2', 'pin3', 'pin0', 'pin1', 'pin6', 'compass', 'pin4', 'pin5', 'pin7', 'sleep', 'temperature', 'pin9', 'pin8', 'ws2812_write', 'SoundEvent', 'pin13', 'pin12', 'pin11', 'pin10', 'running_time', 'spi', 'pin15', 'pin14', 'display', 'accelerometer', 'pin16', 'pin19', '__thonny_helper', 'audio', '__thonny_relevant', 'button_a', 'button_b', 'Sound', 'os', 'speaker', 'pin_speaker', 'pin20', 'i2c', '__name__', 'uart', 'set_volume', 'Image', 'microphone', 'gc', 'reset'] >>> help('modules') __main__ machine os uerrno antigravity math radio urandom audio microbit speech ustruct builtins micropython this usys gc music uarray utime love neopixel ucollections Plus any modules on the filesystem >>> #オンライン・ヘルプ >>> help() Welcome to MicroPython on the micro:bit! Try these commands: display.scroll('Hello') running_time() sleep(1000) button_a.is_pressed() What do these commands do? Can you improve them? HINT: use the up and down arrow keys to get your command history. Press the TAB key to auto-complete unfinished words (so 'di' becomes 'display' after you press TAB). These tricks save a lot of typing and look cool! Explore: Type 'help(something)' to find out about it. Type 'dir(something)' to see what it can do. Type 'dir()' to see what stuff is available. For goodness sake, don't type 'import this'. Control commands: CTRL-C -- stop a running program CTRL-D -- on a blank line, do a soft reset of the micro:bit CTRL-E -- enter paste mode, turning off auto-indent For a list of available modules, type help('modules') For more information about Python, visit: http://python.org/ To find out about MicroPython, visit: http://micropython.org/ Python/micro:bit documentation is here: https://microbit-micropython.readthedocs.io/ >>>

サンプルスクリプト

helloWorld.py

from microbit import * while True: display.scroll('Hello, World!') display.show(Image.HEART) sleep(2000)

blink.py

from microbit import * while True: pin0.write_digital(0) sleep(500) pin0.write_digital(1) sleep(500)

・接続しているLED(pin0)が点滅する。

dimmer.py

from microbit import * min_power = 50 max_power = 1023 power_step = (max_power - min_power) / 9 brightness = 0 def set_power(brightness): display.show(str(brightness)) if brightness == 0: pin0.write_analog(0) else: pin0.write_analog(brightness * power_step + min_power) set_power(brightness) while True: if button_a.was_pressed(): brightness -= 1 if brightness < 0: brightness = 0 set_power(brightness) elif button_b.was_pressed(): brightness += 1 if brightness > 9: brightness = 9 set_power(brightness) sleep(100)

・ボタンBを押すと接続しているLEC(pin0)の光量が増す。
・ボタンAを押すと接続しているLEC(pin0)の光量が減る。

linghtsensor.py

from microbit import * while True: if display.read_light_level() < 100: display.show(Image.HEART) else: display.clear() sleep(2000)

・光をLED-Matrixに当てると表示されているLEDのハートマークが消える。
 (強い光を当てないと光センサーが動作しないようだ)

conway.py

''' Conway's Game Of Life for the micro:bit Press button A or tap the micro:bit to generate a fresh layout. ''' import microbit import random arena1 = bytearray(7 * 7) arena2 = bytearray(7 * 7) def show(): img = microbit.Image(5,5) for y in range(5): for x in range(5): img.set_pixel(x, y, arena1[8 + y * 7 + x]*9) microbit.display.show(img) # do 1 iteration of Conway's Game of Life def conway_step(): global arena1, arena2 for i in range(5 * 5): # loop over pixels i = 8 + (i // 5) * 7 + i % 5 # count number of neighbours num_neighbours = (arena1[i - 8] + arena1[i - 7] + arena1[i - 6] + arena1[i - 1] + arena1[i + 1] + arena1[i + 6] + arena1[i + 7] + arena1[i + 8]) # check if the centre cell is alive or not self = arena1[i] # apply the rules of life if self and not (2 <= num_neighbours <= 3): arena2[i] = 0 # not enough, or too many neighbours: cell dies elif not self and num_neighbours == 3: arena2[i] = 1 # exactly 3 neighbours around an empty cell: cell is born else: arena2[i] = self # stay as-is # swap the buffers (arena1 is now the new one to display) arena1, arena2 = arena2, arena1 while True: # randomise the start for i in range(5 * 5): # loop over pixels i = 8 + (i // 5) * 7 + i % 5 arena1[i] = random.randrange(2) # set the pixel randomly show() microbit.sleep(1) # need to yield to update accelerometer (not ideal...) # loop while button a is not pressed while not microbit.button_a.is_pressed() and microbit.accelerometer.get_z() < -800: conway_step() show() microbit.sleep(150)

neopixel_random.py

""" neopixel_random.py Repeatedly displays random colours onto the LED strip. This example requires a strip of 8 Neopixels (WS2812) connected to pin0. """ from microbit import * import neopixel from random import randint # Setup the Neopixel strip on pin0 with a length of 8 pixels #np = neopixel.NeoPixel(pin0, 8) np = neopixel.NeoPixel(pin0, 64) while True: #Iterate over each LED in the strip for pixel_id in range(0, len(np)): red = randint(0, 60) green = randint(0, 60) blue = randint(0, 60) # Assign the current LED a random red, green and blue value between 0 and 60 np[pixel_id] = (red, green, blue) # Display the current pixel data on the Neopixel strip np.show() #sleep(100)

・使用するneopixelの数に応じてsleep時間は調整すること。

firefly.py

# A micro:bit Firefly. # By Nicholas H.Tollervey. Released to the public domain. import radio import random from microbit import display, Image, button_a, sleep # Create the "flash" animation frames. Can you work out how it's done? flash = [Image().invert()*(i/9) for i in range(9, -1, -1)] # The radio won't work unless it's switched on. radio.on() # Event loop. while True: # Button A sends a "flash" message. if button_a.was_pressed(): radio.send('flash') # a-ha # Read any incoming messages. incoming = radio.receive() if incoming == 'flash': # If there's an incoming "flash" message display # the firefly flash animation after a random short # pause. sleep(random.randint(50, 350)) display.show(flash, delay=100, wait=False) # Randomly re-broadcast the flash message after a # slight delay. if random.randint(0, 9) == 0: sleep(500) radio.send('flash') # a-ha

・2つのmicrobitを用意して上のプログラムを描き込み実行する。
・Aボタンを押すとbluetooth経由で信号を受信して対向のmicrobitのLEDが光る。
(対向のmicrobitはv2でなくても良い)

performanceTest.py

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

以下が出力される:(出力例)

Count: 669283

LCD表示スクリプト(2021/5/10)

以下は 「DEPRECATED LIBRARY micropython-adafruit-rgb-display」のソースをmicrobit-v2のmicropythonに合わせて修正したものになる:
(使用しているLCDは以下のもの)
1.8inch colorful display module for micro:bit, 160x128

rgb.py

import utime import ustruct def color565(r, g, b): return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3 class DummyPin: """A fake gpio pin for when you want to skip pins.""" OUT = 0 IN = 0 PULL_UP = 0 PULL_DOWN = 0 OPEN_DRAIN = 0 ALT = 0 ALT_OPEN_DRAIN = 0 LOW_POWER = 0 MED_POWER = 0 HIGH_PWER = 0 IRQ_FALLING = 0 IRQ_RISING = 0 IRQ_LOW_LEVEL = 0 IRQ_HIGH_LEVEL = 0 def __call__(self, *args, **kwargs): return False init = __call__ value = __call__ out_value = __call__ toggle = __call__ high = __call__ low = __call__ on = __call__ off = __call__ mode = __call__ pull = __call__ drive = __call__ irq = __call__ class Display: _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ = None _INIT = () _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" _DECODE_PIXEL = ">BBB" def __init__(self, width, height): self.width = width self.height = height self.init() def init(self): """Run the initialization commands.""" for command, data in self._INIT: self._write(command, data) def _block(self, x0, y0, x1, y1, data=None): """Read or write a block of data.""" self._write(self._COLUMN_SET, self._encode_pos(x0, x1)) self._write(self._PAGE_SET, self._encode_pos(y0, y1)) if data is None: size = ustruct.calcsize(self._DECODE_PIXEL) return self._read(self._RAM_READ, (x1 - x0 + 1) * (y1 - y0 + 1) * size) self._write(self._RAM_WRITE, data) def _encode_pos(self, a, b): """Encode a postion into bytes.""" return ustruct.pack(self._ENCODE_POS, a, b) def _encode_pixel(self, color): """Encode a pixel color into bytes.""" return ustruct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): """Decode bytes into a pixel color.""" return color565(*ustruct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): """Read or write a pixel.""" if color is None: return self._decode_pixel(self._block(x, y, x, y)) if not 0 <= x < self.width or not 0 <= y < self.height: return self._block(x, y, x, y, self._encode_pixel(color)) def fill_rectangle(self, x, y, width, height, color): """Draw a filled rectangle.""" x = min(self.width - 1, max(0, x)) y = min(self.height - 1, max(0, y)) w = min(self.width - x, max(1, width)) h = min(self.height - y, max(1, height)) self._block(x, y, x + w - 1, y + h - 1, b'') chunks, rest = divmod(w * h, 512) pixel = self._encode_pixel(color) if chunks: data = pixel * 512 for count in range(chunks): self._write(None, data) if rest: self._write(None, pixel * rest) def fill(self, color=0): """Fill whole screen.""" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x, y, width, color): """Draw a horizontal line.""" self.fill_rectangle(x, y, width, 1, color) def vline(self, x, y, height, color): """Draw a vertical line.""" self.fill_rectangle(x, y, 1, height, color) def blit_buffer(self, buffer, x, y, width, height): """Copy pixels from a buffer.""" if (not 0 <= x < self.width or not 0 <= y < self.height or not 0 < x + width <= self.width or not 0 < y + height <= self.height): raise ValueError("out of bounds") self._block(x, y, x + width - 1, y + height - 1, buffer) class DisplaySPI(Display): def __init__(self, spi, dc, cs=None, rst=None, width=1, height=1): self.spi = spi self.cs = cs self.dc = dc self.rst = rst if self.rst is None: self.rst = DummyPin() if self.cs is None: self.cs = DummyPin() #self.cs.init(self.cs.OUT, value=1) #self.dc.init(self.dc.OUT, value=0) #self.rst.init(self.rst.OUT, value=1) self.cs.write_digital(1) self.dc.write_digital(0) self.rst.write_digital(1) self.reset() super().__init__(width, height) def reset(self): #self.rst(0) self.rst.write_digital(0) utime.sleep_ms(50) #self.rst(1) self.rst.write_digital(1) utime.sleep_ms(50) def _write(self, command=None, data=None): if command is not None: #self.dc(0) #self.cs(0) self.dc.write_digital(0) self.cs.write_digital(0) self.spi.write(bytearray([command])) #self.cs(1) self.cs.write_digital(1) if data is not None: #self.dc(1) #self.cs(0) self.dc.write_digital(1) self.cs.write_digital(0) self.spi.write(data) #self.cs(1) self.cs.write_digital(1) def _read(self, command=None, count=0): #self.dc(0) #self.cs(0) self.dc.write_digital(0) self.cs.write_digital(0) if command is not None: self.spi.write(bytearray([command])) if count: data = self.spi.read(count) #self.cs(1) self.cs.write_digital(1) return data

・ピン制御の部分をmicrobitのmicropythonに合わせて修正した。

st7735.py

from rgb import DisplaySPI, color565 import ustruct _NOP=const(0x00) _SWRESET=const(0x01) _RDDID=const(0x04) _RDDST=const(0x09) _SLPIN=const(0x10) _SLPOUT=const(0x11) _PTLON=const(0x12) _NORON=const(0x13) _INVOFF=const(0x20) _INVON=const(0x21) _DISPOFF=const(0x28) _DISPON=const(0x29) _CASET=const(0x2A) _RASET=const(0x2B) _RAMWR=const(0x2C) _RAMRD=const(0x2E) _PTLAR=const(0x30) _COLMOD=const(0x3A) _MADCTL=const(0x36) _FRMCTR1=const(0xB1) _FRMCTR2=const(0xB2) _FRMCTR3=const(0xB3) _INVCTR=const(0xB4) _DISSET5=const(0xB6) _PWCTR1=const(0xC0) _PWCTR2=const(0xC1) _PWCTR3=const(0xC2) _PWCTR4=const(0xC3) _PWCTR5=const(0xC4) _VMCTR1=const(0xC5) _RDID1=const(0xDA) _RDID2=const(0xDB) _RDID3=const(0xDC) _RDID4=const(0xDD) _PWCTR6=const(0xFC) _GMCTRP1=const(0xE0) _GMCTRN1=const(0xE1) class ST7735(DisplaySPI): """ A simple driver for the ST7735-based displays. >>> from machine import Pin, SPI >>> import st7735 >>> display = st7735.ST7735(SPI(1), dc=Pin(12), cs=Pin(15), rst=Pin(16)) >>> display = st7735.ST7735R(SPI(1, baudrate=40000000), dc=Pin(12), cs=Pin(15), rst=Pin(16)) >>> display.fill(0x7521) >>> display.pixel(64, 64, 0) """ _COLUMN_SET = _CASET _PAGE_SET = _RASET _RAM_WRITE = _RAMWR _RAM_READ = _RAMRD _INIT = ( (_SWRESET, None), (_SLPOUT, None), (_MADCTL, b'\x08'), # bottom to top refresh (_COLMOD, b'\x05'), # 16bit color (_INVCTR, b'0x00'), # line inversion # 1 clk cycle nonoverlap, 2 cycle gate rise, 3 sycle osc equalie, # fix on VTL (_DISSET5, b'\x15\x02'), # fastest refresh, 6 lines front porch, 3 line back porch (_FRMCTR1, b'\x00\x06\x03'), (_PWCTR1, b'\x02\x70'), # GVDD = 4.7V, 1.0uA (_PWCTR2, b'\x05'), # VGH=14.7V, VGL=-7.35V (_PWCTR3, b'\x01\x02'), # Opamp current small, Boost frequency (_PWCTR6, b'\x11\x15'), (_VMCTR1, b'\x3c\x38'), # VCOMH = 4V, VOML = -1.1V (_GMCTRP1, b'\x09\x16\x09\x20\x21\x1b\x13\x19' b'\x17\x15\x1e\x2b\x04\x05\x02\x0e'), # Gamma (_GMCTRN1, b'\x08\x14\x08\x1e\x22\x1d\x18\x1e' b'\x18\x1a\x24\x2b\x06\x06\x02\x0f'), (_CASET, b'\x00\x02\x00\x81'), # XSTART = 2, XEND = 129 (_RASET, b'\x00\x02\x00\x81'), # YSTART = 2, YEND = 129 (_NORON, None), (_DISPON, None), ) _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" def __init__(self, spi, dc, cs, rst=None, width=128, height=128): super().__init__(spi, dc, cs, rst, width, height) class ST7735R(ST7735): _INIT = ( (_SWRESET, None), (_SLPOUT, None), (_MADCTL, b'\xc8'), (_COLMOD, b'\x05'), # 16bit color (_INVCTR, b'\x07'), (_FRMCTR1, b'\x01\x2c\x2d'), (_FRMCTR2, b'\x01\x2c\x2d'), (_FRMCTR3, b'\x01\x2c\x2d\x01\x2c\x2d'), (_PWCTR1, b'\x02\x02\x84'), (_PWCTR2, b'\xc5'), (_PWCTR3, b'\x0a\x00'), (_PWCTR4, b'\x8a\x2a'), (_PWCTR5, b'\x8a\xee'), (_VMCTR1, b'\x0e'), (_INVOFF, None), (_GMCTRP1, b'\x02\x1c\x07\x12\x37\x32\x29\x2d' b'\x29\x25\x2B\x39\x00\x01\x03\x10'), # Gamma (_GMCTRN1, b'\x03\x1d\x07\x06\x2E\x2C\x29\x2D' b'\x2E\x2E\x37\x3F\x00\x00\x02\x10'), ) def __init__(self, spi, dc, cs, rst=None, width=128, height=160): super().__init__(spi, dc, cs, rst, width, height) def init(self): super().init() cols = ustruct.pack('>HH', 0, self.width - 1) rows = ustruct.pack('>HH', 0, self.height - 1) for command, data in ( (_CASET, cols), (_RASET, rows), (_NORON, None), (_DISPON, None), ): self._write(command, data)

・特に修正はない。

displayLCD.py

from microbit import * from st7735 import ST7735, ST7735R from rgb import color565 spi.init(mode=3, baudrate=300000000, sclk=pin13, mosi=pin15, miso=pin14) #spi.init(0) lcd = ST7735R(spi, dc=pin12, cs=pin16, rst=pin8) lcd.fill(0) for x in range(128): for y in range(160): lcd.pixel(x,y,color565(x*2, y*3//2, 255-x-y*3//4))

・転送速度が遅いようで描画速度が遅い。
 (設定の問題だと思うが画面端にゴミが表示される)
・他のmicropythonと異なり最初からSPIのインスタンスが用意されているので、コーディング時は、そこに注意する必要がある。(メモリの制約と推測する)

main.py

電源オン時に自動的にmain.pyが実行されるので、直接実行したいプログラムをmain.pyに置くことができる。
直接実行したいプログラムがxxxx.pyの場合は、
main.pyを以下のようにしても良い。

main.py

# main.py import xxxx

参照URL

micro:bit-v2_MicroPython関連:
MicroPython on the micro:bit via CODAL
Hello, World! (v2-doc)日本語版
micro:bit v2 用 MicroPython で新機能を試してみる
Hello, World! (v2-doc)
Out of box experience(factory reset)
Python guide(examples)
micropython/examples

Thonny関連:
Thonny (Python IDE for beginners)
Thonnyインストール方法(PicoボードにMicropython/CircuitPythonをインストールする)

(別の)MicroPython関連:
TFT LCD(ST7735R)をMicroPythonで動かしてみた
DEPRECATED LIBRARY micropython-adafruit-rgb-display

MakeCode(python)関連:(参考)
(the difference between) MakeCode Python and MicroPython
micro:bit v2(マイクロビット)に関する技術情報を集約

以上

続きを読む "microbit-v2にMicropythonをインストールする"

| | コメント (0)

2021年2月10日 (水)

PicoボードのMicroPythonをVS_CodeのextensionのPico-Goでプログラミングする

2021/2/9+

VS Code extension PicoGo for MicroPython

VS Code extension PicoGo for MicroPython

概要

以下のPicoボードのMicroPythonをVS_CodeのextensionのPico-Goでプログラミングする。
(ホストPCとしてはubuntuを想定している)

Raspberry Pi Pico

準備

以下のものをインストールする:

sudo apt install nodejs pip install micropy-cli pip install pylint cd ~/Downloads wget https://github.com/cpwood/Pico-Stub/archive/main.zip uzip main.zip cd Pico-Stub-main/stubs micropy stubs add micropython-rp2-1_13-290

VS_Code_extension'Pico-Go'のインストール:
VS_CodeのなかでCtrl-Pを押して
以下を実行する:

ext install ChrisWood.pico-go

参照: Pico-Go

プロジェクトの作成

以下の手順でプロジェクトを作成する:

mkdir proj cd proj micropy init # メニューが表示されるので、以下の2つを選択して改行を押す [VScode setting ...] [Pylint MicroPython setting ..] # その後、以下を選択する [rp2-micropython-1.13] # 以上でプロジェクトの雛形が作成される # MicroPythonが書き込まれたPicoボードをUSB接続する # 以下でVS Codeを起動する code .

なお、projは。任意のプロジェクト名とする。

プログラムの作成

起動しているVS_Codeで 新規ファイルとして flash.pyを作成して
以下の内容に編集する:

flash.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)

プログラムの実行

VS_Codeの最下行の[Run]をクリックすると プログラムが実行される。

もう一度、[Run]をクリックすると実行が中止される。(トグル動作)

上のやり方で、上手く実行できなかったときは 最下行の[Pico Connected]をクリックして いったん接続を切り 最下行の[Pico Disconnected]をクリックして 再度、接続する。

なお、このやり方の実行の場合、RAMでプログラムが実行される。

フラッシュへの書き込み

Picoボードに書き込む場合は、 最初に実行されるのがboot.pyなので 以下のboot.pyを作成する:

boot.py

print("boot start..") import flash

上のプログラムでは、boot.pyから flash.pyを呼び出す形で プログラムが実行される。

最下行の[Upload]をクリックすると Picoボードにカレントディレクトリにあるファイルが書き込まれる。
実行例:

Failed to read project status, uploading all files [1/5] Writing file boot.py (0kb) [2/5] Writing file dev-requirements.txt (0kb) [3/5] Writing file flash.py (0kb) [4/5] Writing file micropy.json (0kb [5/5] Writing file requirements.txt (0kb) Upload done, resetting board... OK

upload後、プログラムが自動に実行される。
実行を止めたい場合、TERMINAL画面でCtrl-Cを押す。

これで止まらない場合は、いったん、接続を切ってから 再接続して、Ctrl-Cを押す。

なお、uploadが上手く実行できなかったときは
以下を実行する:
(1)最下行メニューから[All commands]/[Pico-Go > Delete all files from boardt]を選択する。
(2)・確認のダイヤログが画面の最上行に現れるので、[Cancel][Yes]のなかから[Yes]を選択する。
(3)TERMINAL画面に「All files and directories have been deleted from the board.」が表示され
Picoボードのなかのファイルをすべて削除される。
(4)[Uplaod]をクリックする。

参照情報

micropython-pico PDF download

Pico-Go VS Code Extension
Developing for the Raspberry Pi Pico in VS Code — Getting Started
Developing for the Raspberry Pi Pico in VS Code — Start Coding!

以上

続きを読む "PicoボードのMicroPythonをVS_CodeのextensionのPico-Goでプログラミングする"

| | コメント (0)

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)

2021年1月 3日 (日)

MicroPython(F767ZI) Network Samples

2021/1/3
初版

MicroPython(F767ZI ) Network Samples

MicroPython(F767ZI ) Network Samples

概要

MicroPython(F767ZI) Network Samples

この記事は「 MicroPython(F767ZI)でStartwars(AsciiArt)を動かす 」の続編にあたり、NetworkアクセスSamplesを記述している。ネットワークの接続が完了すれば、それ以降はESP8266のmicropythonとほぼ同じようだ。
(ホストはubuntuを想定している)

sample1

http_get.py

# ネットワークを有効化する import network nic = network.LAN() nic.active(1) # 以下はESP8266のサンプルと全く同じ def http_get(url): import socket _, _, host, path = url.split('/', 3) addr = socket.getaddrinfo(host, 80)[0][-1] s = socket.socket() s.connect(addr) s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8')) while True: data = s.recv(100) if data: print(str(data, 'utf8'), end='') else: break s.close() print(http_get('http://micropython.org/ks/test.html'))

REPL実行例:

paste mode; Ctrl-C to cancel, Ctrl-D to finish === import network === nic = network.LAN() === nic.active(1) === === >>> nic.ifconfig() ('192.168.0.18', '255.255.255.0', '192.168.0.4', '192.168.0.4') >>> paste mode; Ctrl-C to cancel, Ctrl-D to finish === === def http_get(url): === import socket === _, _, host, path = url.split('/', 3) === addr = socket.getaddrinfo(host, 80)[0][-1] === s = socket.socket() === s.connect(addr) === s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8')) === while True: === data = s.recv(100) === if data: === print(str(data, 'utf8'), end='') === else: === break === s.close() === === print(http_get('http://micropython.org/ks/test.html')) === ===

REPL出力結果:

HTTP/1.1 200 OK Server: nginx/1.10.3 Date: Sun, 03 Jan 2021 09:54:59 GMT Content-Type: text/html Content-Length: 180 Last-Modified: Tue, 03 Dec 2013 00:16:26 GMT Connection: close Vary: Accept-Encoding ETag: "529d22da-b4" Accept-Ranges: bytes <!DOCTYPE html> <html lang="en"> <head> <title>Test</title> </head> <body> <h1>Test</h1> It's working if you can read this! </body> </html> None

sample2

目的のプログラム実行前に
以下を実行して ネットワークの有効化と
IPアドレスの確認を行なう。

import network nic = network.LAN() nic.active(1) nic.ifconfig()

httpserver.py

# 以下はESP8266のサンプルを差分のあるmachine関係をコメントアウトしたもの #import machine #pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] html = """<!DOCTYPE html> <html> <head> <title>ESP8266 Pins</title> </head> <body> <h1>ESP8266 Pins</h1> <table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table> </body> </html> """ import socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on', addr) while True: cl, addr = s.accept() print('client connected from', addr) cl_file = cl.makefile('rwb', 0) while True: line = cl_file.readline() if not line or line == b'\r\n': break #rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins] rows = ['<tr><td>ABC</td><td>123</td></tr>'] response = html % '\n'.join(rows) cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close()

REPL実行例:

>>> nic.active() True >>> nic.ifconfig() ('192.168.0.18', '255.255.255.0', '192.168.0.4', '192.168.0.4') >>> # 上の192.168.0.18がサーバーアドレスになるので覚えておいてサーバー起動後、このIPアドレスにアクセスする paste mode; Ctrl-C to cancel, Ctrl-D to finish === #import machine === #pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] === === html = """<!DOCTYPE html> === <html> === <head> <title>ESP8266 Pins</title> </head> === <body> <h1>ESP8266 Pins</h1> === <table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table> === </body> === </html> === """ === === import socket === addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] === === s = socket.socket() === s.bind(addr) === s.listen(1) === === print('listening on', addr) === === while True: === cl, addr = s.accept() === print('client connected from', addr) === cl_file = cl.makefile('rwb', 0) === while True: === line = cl_file.readline() === if not line or line == b'\r\n': === break === === #rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins] === rows = ['<tr><td>ABC</td><td>123</td></tr>'] === response = html % '\n'.join(rows) === cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') === cl.send(response) === cl.close() === ===

上でサーバーを起動したら 確認したIPアドレス(192.128.0.xxx:80)で ブラウザー・アクセスする。

REPL出力例:

listening on ('0.0.0.0', 80) client connected from ('192.168.0.2', 56016) 44 229 client connected from ('192.168.0.2', 56018) 44 229

ウェブ画面表示例:

ESP8266 Pins

Pin Value
ABC 123

参考情報

https://docs.micropython.org/en/latest/esp8266/tutorial/network_basics.html
https://docs.micropython.org/en/latest/esp8266/tutorial/network_tcp.html

M5Stack MicroPython API調査記録 ネットワーク編
ESP32/ESP8266のMicroPythonでMQTTを使ってみた
ESP32のMicroPythonでOSC(Open Sound Control)で通信する

以上

続きを読む "MicroPython(F767ZI) Network Samples"

| | コメント (0)

2020年12月29日 (火)

MicroPython(F767ZI)でStartwars(AsciiArt)を動かす

2020/12/28:
初版

MicroPython(F767ZI) STARWARS

MicroPython(F767ZI) STARWARS

概要

MicroPython(F767ZI)でStartwars(AsciiArt)を動かす

本記事では「 NUCLEO F767ZI MicroPython Install(v2) 」 でビルドしたMicroPythonでStarwars(AsciiArt)を動かす。

接続

(1)本体ボード部分のUSBはホストPCに接続する
(2)デバッグ(st-link)ボード部分のUSBは電源供給用なのでACアダプターなどに接続する
(3)LANソケットは有線LANに接続する

デモ・プログラム

以下のプログラムをmicropythonのフラッシュに置く:

PYBFLASH/starwars.py

# starwars import network, socket nic = network.LAN() nic.active(1) addr = socket.getaddrinfo('towel.blinkenlights.nl', 23)[0][-1] s = socket.socket() s.connect(addr) while True: data = s.recv(1500) print(data.decode('utf-8'), end='')

「picocom /dev/ttyACM0 -b115200」を実行してREPLモードに入る:
(なにも表示されないようなら、本体ボードのリセット・ボタンを押す)

$ picocom /dev/ttyACM0 -b115200 <省略> import starwars #以下のようなAsciiArtのアニメが実行される: ........... @@@@@ @@@@@ ........... .......... @ @ @ @ .......... ........ @@@ @ @ .......... ....... @@ @ @ ......... ...... @@@@@@@ @@@@@ th ........ ..... ----------------------- ....... .... C E N T U R Y ....... ... ----------------------- ..... .. @@@@@ @@@@@ @ @ @@@@@ ... == @ @ @ @ @ == __||__ @ @@@@ @ @ __||__ | | @ @ @ @ @ | | _________|______|_____ @ @@@@@ @ @ @ _____|______|_________

参考情報

MicroPythonでSTM32のEthernetが正式サポートされました
5. ネットワーク - TCPソケット

Installing ST-Link v2 to flash STM32 targets on Linux

以上

続きを読む "MicroPython(F767ZI)でStartwars(AsciiArt)を動かす"

| | コメント (0)

2020年5月22日 (金)

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

2020/5/22

NUCLEO F767ZI MicroPython Install(v2)

NUCLEO F767ZI MicroPython Install(v2)

概要

「NUCLEO F767ZI」にMicropythonをインストールする方法について記載する (ホストPCとしてはubuntuを想定している)

事前準備

(1)書き込みツール(st-flash)のインストール

sudo apt install cmake sudo apt install libusb-1.0 git clone https://github.com/texane/stlink.git cd stlink make cd build/Release sudo make install sudo ldconfig

(2)ampyのインストール
AMPY_PORTは、自分の環境に合わせる。

pip install adafruit-ampy export AMPY_PORT=/dev/ttyACM0 export AMPY_BAUD=115200

(3)picocomのインストール

sudo apt-get install picocom

以上のうち、exportしているものは、.bashrcに登録することを勧める。

コンパイラのバージョンアップ

以下でインストールしたコンパイラが古くてビルドエラーが出たのでバージョンアップする。
sudo apt-get install gcc-arm-none-eabi

(1)以下のurlから最新版をダウンロードする:
https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads

解凍したものを以下のフォルダに置く:
$HOME/Downloads/gcc-arm-none-eabi-8-2019-q3-update

(2)パス設定
#古いコンパイラを削除する
sudo apt-get remove gcc-arm-none-eabi
#パスを設定する
export PATH=$PATH:$HOME/Downloads/gcc-arm-none-eabi-8-2019-q3-update/bin

ビルド手順

以下の手順で行なう:

mkdir mp_nucleo cd mp_nucleo git clone https://github.com/micropython/micropython.git cd micropython cd mpy-cross make cd .. cd ports/stm32 make submodules make BOARD=NUCLEO_F767ZI ls -l build-NUCLEO_F767ZI/firmware.* -rw-rw-r-- 1 xxxx xxxx 458749 5月 21 23:42 build-NUCLEO_F767ZI/firmware.dfu -rwxrwxr-x 1 xxxx xxxx 921348 5月 21 23:42 build-NUCLEO_F767ZI/firmware.elf -rw-rw-r-- 1 xxxx xxxx 1289515 5月 21 23:42 build-NUCLEO_F767ZI/firmware.hex -rw-rw-r-- 1 xxxx xxxx 1949998 5月 21 23:42 build-NUCLEO_F767ZI/firmware.map arm-none-eabi-objcopy -O binary build-NUCLEO_F767ZI/firmware.elf build-NUCLEO_F767ZI/firmware.bin ls -l build-NUCLEO_F767ZI/firmware.* -rwxrwxr-x 1 xxxx xxxx 574668 5月 21 23:44 build-NUCLEO_F767ZI/firmware.bin -rw-rw-r-- 1 xxxx xxxx 458749 5月 21 23:42 build-NUCLEO_F767ZI/firmware.dfu -rwxrwxr-x 1 xxxx xxxx 921348 5月 21 23:42 build-NUCLEO_F767ZI/firmware.elf -rw-rw-r-- 1 xxxx xxxx 1289515 5月 21 23:42 build-NUCLEO_F767ZI/firmware.hex -rw-rw-r-- 1 xxxx xxxx 1949998 5月 21 23:42 build-NUCLEO_F767ZI/firmware.map

書き込み手順

上でビルドしたbinをst-flashで書き込む

st-flash write build-NUCLEO_F767ZI/firmware.bin 0x8000000 #出力例: st-flash 1.6.0 2020-05-21T23:51:37 INFO common.c: Loading device parameters.... 2020-05-21T23:51:37 INFO common.c: Device connected is: F76xxx device, id 0x10016451 2020-05-21T23:51:37 INFO common.c: SRAM size: 0x80000 bytes (512 KiB), Flash: 0x200000 bytes (2048 KiB) in pages of 2048 bytes 2020-05-21T23:51:37 INFO common.c: Attempting to write 574668 (0x8c4cc) bytes to stm32 address: 134217728 (0x8000000) Flash page at addr: 0x08080000 erasedEraseFlash - Sector:0x6 Size:0x40000 2020-05-21T23:51:43 INFO common.c: Finished erasing 7 pages of 262144 (0x40000) bytes 2020-05-21T23:51:43 INFO common.c: Starting Flash write for F2/F4/L4 2020-05-21T23:51:43 INFO flash_loader.c: Successfully loaded flash loader in sram enabling 32-bit flash writes size: 32768 size: 32768 <省略> size: 32768 size: 17612 2020-05-21T23:51:52 INFO common.c: Starting verification of write complete 2020-05-21T23:51:57 INFO common.c: Flash written and verified! jolly good!

動作確認

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

$ picocom /dev/ttyACM0 -b115200 MicroPython v1.12-464-gcae77da on 2020-05-21; NUCLEO-F767ZI with STM32F767 Type "help()" for more information. >>> import os >>> os.uname() (sysname='pyboard', nodename='pyboard', release='1.12.0', version='v1.12-464-gcae77da on 2020-05-21', machine='NUCLEO-F767ZI with STM32F767') >>> >>> >>> 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() 273696 >>> >>> help('modules') __main__ math uasyncio/lock uos _onewire micropython uasyncio/stream urandom _uasyncio network ubinascii ure _webrepl onewire ucollections uselect builtins pyb ucryptolib usocket cmath stm uctypes ussl dht sys uerrno ustruct framebuf uarray uhashlib utime gc uasyncio/__init__ uheapq utimeq lcd160cr uasyncio/core uio uwebsocket lcd160cr_test uasyncio/event ujson uzlib lwip uasyncio/funcs umachine Plus any modules on the filesystem >>> # network,usocket,uwebsocketなどネットワーク関連が追加されていることが分かる。

ampy実行例

$ ampy -p /dev/ttyACM0 ls /flash $ ampy -p /dev/ttyACM0 ls /flash /flash/README.txt /flash/boot.py /flash/main.py /flash/pybcdc.inf $ ampy -p /dev/ttyACM0 get /flash/boot.py # boot.py -- run on boot-up # can run arbitrary Python, but best to keep it minimal import machine import pyb pyb.country('US') # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU #pyb.main('main.py') # main script to run after this one #pyb.usb_mode('VCP+MSC') # act as a serial and a storage device #pyb.usb_mode('VCP+HID') # act as a serial device and a mouse $ ampy -p /dev/ttyACM0 get /flash/main.py # main.py -- put your code here!

サンプルスクリプト

blink.py

# LED(1) // Green LED on board # LED(2) // Blue LED on board # LED(3) // Red LED on board while True: pyb.LED(1).on() pyb.LED(2).on() pyb.LED(3).on() pyb.delay(1000) pyb.LED(1).off() pyb.LED(2).off() pyb.LED(3).off() pyb.delay(250)

ボード上の3つのLEDが点滅する。

実行例:

$ ampy -p /dev/ttyACM0 run blink.py

この場合、flashにスクリプトを書き込まずに直接RAMで実行される。

ボードの電源オンで直接スクリプトを実行する場合は
以下のようにする。(blink.pyをmain.pyに上書きする)

$ ampy -p /dev/ttyACM0 put blink.py /flash/main.py

この書き込み後、リセットボタンを押すと自動的にスクリプトが動作する。

User USB

User_USBコネクタをホストPCとUSB接続するとPYBFLASHホルダが現れ、ここにMicroPythonのプログラムを置くことができる。 (電源はstlink側のUSBコネクタから供給されているので、stlink側のコネクタもホストPCに接続する必要がある)
ストレージとしてMicroPythonのプログラムを置くことができるので、この場合、ampyを使用する必要はない、

Perfomance Test

performanceTest.py

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

実行結果としては以下のような数字になった:

>>> import performanceTest Count: 5676566 >>>

参照URL

Turtorial Examples for Nucleo-MicroPython

NUCLEO-F767ZI digikey
NUCLEO-F767ZI mbed

The MicroPython project
STM32 Nucleo Board STM32F446RE
Quick reference for the pyboard ampyを用いたMicroPythonのファイル操作とプログラム実行
MicroPython pyboard v1.1
新しいボードへMicroPythonを対応させる方法をざっくり解説

MicroPython Performance Test

以上

続きを読む "NUCLEO-F767ZIにMicropythonをインストールする(v2)"

| | コメント (0)

2020年4月 4日 (土)

FT232Hボードにneopixelsを接続する

2020/4/4

FT232H neopixels(spi)

FT232H neopixels(spi)

概要

以下のFT232Hボードにneopixelsを接続する。

FT232H使用USB⇔GPIO+SPI+I2C変換モジュール
Adafruit FT232H Breakout
PCのpython3でCircuitPythonのAPIを使用する

接続

D1(MOSI)をneopixelsのDINに接続する。

demo1

Module Install:

pip3 install adafruit-circuitpython-neopixels_spi

Demo Script:
neopixel_spi_test.py

# FT232H board import math from time import sleep import board import neopixel_spi as neopixel NUM_PIXELS = 64 PIXEL_ORDER = neopixel.GRB COLORS = (0xFF0000, 0x00FF00, 0x0000FF) DELAY = 0.1 spi = board.SPI() pixels = neopixel.NeoPixel_SPI(spi, NUM_PIXELS, pixel_order=PIXEL_ORDER, auto_write=False) def show_pixels(data): for n in range(NUM_PIXELS): pixels[n] = data[n] pixels.show() def data_generator(led_count): data = [(0, 0, 0) for i in range(led_count)] step = 0 while True: red = int((1 + math.sin(step * 0.1324)) * 127) green = int((1 + math.sin(step * 0.1654)) * 127) blue = int((1 + math.sin(step * 0.1)) * 127) data[step % led_count] = (red, green, blue) yield data step += 1 for data in data_generator(NUM_PIXELS): show_pixels(data) sleep(0.01)

実行:

$ export BLINKA_FT232H=1 $ python3 neopixel_spi_test.py

demo2

Module Install:

git clone https://github.com/JanBednarik/micropython-ws2812.git cd micropython-ws2812 cp ws2812.py ws2812_spi0_cpy.py nano ws2812_spi0_cpy.py # 次の「Patched Module」に記載されているパッチを反映する。 cp ws2812_spi0_cpy.py ~/ft232h_ws/

Patched Module:
ws2812_spi0_cpy.py
「#m」を含む行が修正行になる。

# -*- coding: utf-8 -*- import gc #m import pyb import board #m import busio #m class WS2812: """ Driver for WS2812 RGB LEDs. May be used for controlling single LED or chain of LEDs. Example of use: chain = WS2812(spi_bus=1, led_count=4) data = [ (255, 0, 0), # red (0, 255, 0), # green (0, 0, 255), # blue (85, 85, 85), # white ] chain.show(data) Version: 1.0 """ buf_bytes = (0x88, 0x8e, 0xe8, 0xee) def __init__(self, spi_bus=1, led_count=1, intensity=1): """ Params: * spi_bus = SPI bus ID (1 or 2) * led_count = count of LEDs * intensity = light intensity (float up to 1) """ self.led_count = led_count self.intensity = intensity # prepare SPI data buffer (4 bytes for each color) self.buf_length = self.led_count * 3 * 4 self.buf = bytearray(self.buf_length) # SPI init #m self.spi = pyb.SPI(spi_bus, pyb.SPI.MASTER, baudrate=3200000, polarity=0, phase=1) self.spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI) #m self.spi.try_lock() #m self.spi.configure(baudrate=3200000, polarity=0, phase=0) #m # turn LEDs off self.show([]) def show(self, data): """ Show RGB data on LEDs. Expected data = [(R, G, B), ...] where R, G and B are intensities of colors in range from 0 to 255. One RGB tuple for each LED. Count of tuples may be less than count of connected LEDs. """ self.fill_buf(data) self.send_buf() def send_buf(self): """ Send buffer over SPI. """ #m self.spi.send(self.buf) self.spi.write(self.buf) #m #m gc.collect() def update_buf(self, data, start=0): """ Fill a part of the buffer with RGB data. Order of colors in buffer is changed from RGB to GRB because WS2812 LED has GRB order of colors. Each color is represented by 4 bytes in buffer (1 byte for each 2 bits). Returns the index of the first unfilled LED Note: If you find this function ugly, it's because speed optimisations beated purity of code. """ buf = self.buf buf_bytes = self.buf_bytes intensity = self.intensity mask = 0x03 index = start * 12 for red, green, blue in data: red = int(red * intensity) green = int(green * intensity) blue = int(blue * intensity) buf[index] = buf_bytes[green >> 6 & mask] buf[index+1] = buf_bytes[green >> 4 & mask] buf[index+2] = buf_bytes[green >> 2 & mask] buf[index+3] = buf_bytes[green & mask] buf[index+4] = buf_bytes[red >> 6 & mask] buf[index+5] = buf_bytes[red >> 4 & mask] buf[index+6] = buf_bytes[red >> 2 & mask] buf[index+7] = buf_bytes[red & mask] buf[index+8] = buf_bytes[blue >> 6 & mask] buf[index+9] = buf_bytes[blue >> 4 & mask] buf[index+10] = buf_bytes[blue >> 2 & mask] buf[index+11] = buf_bytes[blue & mask] index += 12 return index // 12 def fill_buf(self, data): """ Fill buffer with RGB data. All LEDs after the data are turned off. """ end = self.update_buf(data) # turn off the rest of the LEDs buf = self.buf off = self.buf_bytes[0] for index in range(end * 12, self.buf_length): buf[index] = off index += 1

demo1のAdafruit製モジュールよりも表示が速い。たぶん、gc.collect()をコメントアウトしているせいと思われる。PCのpython3で動作させる前提ではメモリが潤沢にあるので gc.collect()は不要と判断した。
注意:APIはAdafruitのものと異なっている。

Demo Script:
ws2812_spi_test.py

from time import sleep import math from ws2812_spi0_cpy import WS2812 #ring = WS2812(led_count=64, intensity=0.1) ring = WS2812(led_count=64, intensity=1) def data_generator(led_count): data = [(0, 0, 0) for i in range(led_count)] step = 0 while True: red = int((1 + math.sin(step * 0.1324)) * 127) green = int((1 + math.sin(step * 0.1654)) * 127) blue = int((1 + math.sin(step * 0.1)) * 127) data[step % led_count] = (red, green, blue) yield data step += 1 for data in data_generator(ring.led_count): ring.show(data) sleep(0.01)

実行:

$ export BLINKA_FT232H=1 $ python3 ws2812_spi_test.py

参照情報

FT232H Blinka PINOUT

CircuitPython Libraries on any Computer with FT232H

FT232H使用USB⇔GPIO+SPI+I2C変換モジュール
Adafruit FT232H Breakout

CircuitPython on Linux and Raspberry Pi
CircuitPython 5.0.x - I2C

以上

続きを読む "FT232Hボードにneopixelsを接続する"

| | コメント (0)

2020年3月30日 (月)

CircuitPython/MicroPythonに気圧センサーLPS331AP(i2c)を接続する

2020/3/30

CircuitPython LPS331AP(i2c)

CircuitPython LPS331AP(i2c)

概要

CircuitPython/MicroPythonに以下の気圧センサーLPS331AP(i2c)を接続する。
(ホストPCとしてはubuntuを想定している)

LPS331AP 気圧センサモジュール(I2C/SPIタイプ)

接続

以下のように接続する。

Wiring:

LPS331AP Teensy4.0
1(GND) GND
2(SCL) D19(SCL)
3(SDA) D18(SDA)
4(SA0) 3.3V
5(CS) 3.3V
LPS331AP Teensy4.0
10(VDD_IO) 3.3V
9(VDD) 3.3V
8(GND) GND
7(INT1) NC
6(INT2) NC

SCL/SDAは、(モジュール内でPullUpしていないので)それぞれ10kΩでPullUpすること。
NC: None Connection
i2c-addressは、0x5d(93)になる。

該当モジュールのインストール

Module Install:

wget https://beta-notes.way-nifty.com/blog/files/lps331ap_cpy.py # copy related modules cp lps331ap_cpy.py CIRCUTPY/lib/

lps331ap_cpy.pyの内容:

# lps331ap_cpy.py # 2020/3/30: # modification for CircutPython/MicroPython # forked from the following source code: # http://lumenbolk.com/?p=814 class LPS331AP(object): """ # sample code # CircuitPython from lps331ap_cpy import LPS331AP from time import sleep import board import busio i2c = busio.I2C(board.SCL, board.SDA) i2c.try_lock() sensor = LPS331AP(i2c, address=0x5d) while True: press, tempe = sensor.press_tempe print('press: {0:.2f} tempe: {1:.1f}'.format(press, tempe)) print('') sleep(1) #----------------------------- # MicroPython from lps331ap_cpy import LPS331AP from time import sleep from machine import Pin, I2C i2c = I2C(1) sensor = LPS331AP(i2c, address=0x5d) while True: press, tempe = sensor.press_tempe print('press: {0:.2f} tempe: {1:.1f}'.format(press, tempe)) print('') sleep(1) """ def __init__(self, bus, address=0x5d): self.bus = bus self.address = address self.temp2 = bytearray(2) self.temp1 = bytearray(1) self.value = bytearray(1) def _write(self,regist,value): self.temp2[0] = regist self.temp2[1] = value #bus.write_byte_data(address, regist, value) self.bus.writeto(self.address, self.temp2) def _read(self,regist): self.temp1[0] = regist #value=bus.read_byte_data(address, regist) self.bus.writeto(self.address, self.temp1) self.bus.readfrom_into(self.address, self.value) ##bus.writeto_then_readfrom(self.address,self.temp1,self.value) #return value return self.value[0] def _read_16bit(self,registL,registH): value1 = self._read(registL) value2 = self._read(registH) value = (value2 << 8) + value1 return value def _read_24bit(self,registL,registH,registHH): value1 = self._read(registL) value2 = self._read(registH) value3 = self._read(registHH) value4 = (value3 << 8) + value2 value = (value4 << 8) + value1 return value @property def press_tempe(self): # air_pressure and temperature self._write(0x20,0x00) self._write(0x10,0x7a) self._write(0x20,0x84) self._write(0x21,0x01) while self._read(0x21): pass air_pressure = self._read_24bit(0x28,0x29,0x2a) temperature = self._read_16bit(0x2b,0x2c) # air_pressure_calc if air_pressure & (1<<23): air_pressure = -((air_pressure^0xffffff) + 1)/4096. else: air_pressure = air_pressure /4096. # temperature_calc if temperature & (1<<15): temperature = 42.5 - ((temperature^0xffff) + 1)/480. else: temperature = 42.5 + temperature/480. return air_pressure, temperature #--------------------------------------------------

CircuitPythonとMicroPythonに共通してあるi2c.writeto,i2c.readfrom_intoのみを使用しているので、両方に対応できている。

Demo Script(動作確認)

lps331ap_test.py

# CircuitPython from lps331ap_cpy import LPS331AP from time import sleep import board import busio i2c = busio.I2C(board.SCL, board.SDA) i2c.try_lock() sensor = LPS331AP(i2c, address=0x5d) while True: press, tempe = sensor.press_tempe print('press: {0:.2f} tempe: {1:.1f}'.format(press, tempe)) # for plotter of Mu-editor # tempe100 = 100*tempe # scaling # print('({0:.2f}, {1:.1f})'.format(press, tempe100)) sleep(1)

MicroPython(Nucleo)の場合

該当モジュールlps331ap_cpy.pyが、CircuitPython/MicroPython両方に対応しているので そのまま/flashに書き込むだけでパッチなどは必要ない。
動作確認をしていないが以下のようなコードになる:

Demo Script:

# MicroPython from lps331ap_cpy import LPS331AP from time import sleep from machine import Pin, I2C i2c = I2C(1) sensor = LPS331AP(i2c, address=0x5d) while True: press, tempe = sensor.press_tempe print('press: {0:.2f} tempe: {1:.1f}'.format(press, tempe)) # for plotter of Mu-editor # tempe100 = 100*tempe # scaling # print('({0:.2f}, {1:.1f})'.format(press, tempe100)) sleep(1)

デバイスなどの初期化以外はCircuitPythonのものと全く同じ。

参照情報

18 I2c通信で気圧,標高を取得しよう.(LPS331AP気圧センサ)

LPS331AP 気圧センサモジュール(I2C/SPIタイプ)
LPS331AP説明書
メーカーパンフレット
よくある質問とサポートのページ

LPS331AP datasheet

Turtorial Examples for CircuitPython(Teensy4.0)
Teensy4.0にCircuitPythonをインストールする

Turtorial Examples for Nucleo-MicroPytho
NUCLEO-F446REにMicropythonをインストールする(v2)

CircuitPython 5.0.x - I2C

python3/micro:bit-micropython/CircuitPython用エディタ(mu-editor)をインストールする(linux版)

以上

続きを読む "CircuitPython/MicroPythonに気圧センサーLPS331AP(i2c)を接続する"

| | コメント (0)

python3/micro:bit-micropython/CircuitPython用エディタ(mu-editor)をインストールする(linux版)

2020/3/30

mu-editor install for linux

mu-editor install for linux

概要

python3/micro:bit-micropython/CircuitPython用エディタとしてmu-editorがあるが windowsやmac向けのインストーラーは存在するがlinux用が存在しないので、linux版は存在しないと 誤解していたが、普通のpythonプログラムのようにpip3でインストールできる。ここでは、その方法について 記載する。

インストール方法

以下を実行する:

# mu-editorのインストール pip3 install mu-editor # ショートカットを作成するためshortcutをインストールする pip installl shortcut # mu-editorのショートカットを作る shortcut mu-editor # この時点で、デスクトップにmu-editorのショートカット(アイコン)が作られる # そのショートカットをクリックするとmu-editorが起動する

参照情報

How to install Mu with Python packaging on Windows, OSX and Linux

以上

続きを読む "python3/micro:bit-micropython/CircuitPython用エディタ(mu-editor)をインストールする(linux版)"

| | コメント (0)

より以前の記事一覧