背景:LEGO SPIKEを使って教育用コンテンツを試作中、関連する情報をまとめる
LEGO SPIKEとマイコンをシリアル通信させるサンプルコード(copilit)
以下はシリアル送信側(RxD)のコード、Aポートから115200の速度でASCII CODEで"0"~"9"を送信する
Demoでは2台のHUBをケーブルで接続して、通信させている。RxD/TxDをクロスにしていると思うけど。。
import utime
import hub
from hub import port
port.A.mode(port.MODE_FULL_DUPLEX)
a=port.A
a.baud(115200)
i=0
while True:
utime.sleep_ms(150)
p=hub.button.center.was_pressed()
if p==True:
i=i+1
hub.display.show(i)
print("Send: " + str(i))
a.write(str(i))
if i==9:
i=0import utimeimport hubfrom hub import portport.A.mode(port.MODE_FULL_DUP - Pastebin.com
上記コードでシリアル通信できるのなら、機能拡張も容易と思える。さらに、I2Cで通信できたらもっとすごいけど。
copilotに聞いたらI2Cでも通信可能で、Gitのドキュメントを見よと返答された
GitHub - LEGO/spike-prime-docs: Reference documentation for the LEGO® Education SPIKE™ Prime communication protocol.
サンプルコードを尋ねたら以下と返答された。ほとんど標準のMicroPythonのレベルでI2C制御が可能だと。。これはすごい。ここまで来ると、メカや機構はLEGOで実現して、センサー類はI2C経由で、市販のデバイスを接続できるので、ほぼ何でもできるのでは??
from spike import PrimeHub, I2C
from spike.control import wait_for_seconds
# Initialize the hub
hub = PrimeHub()
# Initialize I2C (using port A)
i2c = I2C('A')
# I2C device address
DEVICE_ADDRESS = 0x1E # Example: Address of a magnetic sensor
# Write data (example: write 0x00 to register 0x02)
i2c.write(DEVICE_ADDRESS, [0x02, 0x00])
# Read data (example: read 2 bytes from register 0x03)
data = i2c.read(DEVICE_ADDRESS, 0x03, 2)
# Display the read data
print("Read data:", data)
# Wait for a while
wait_for_seconds(1)
コネクタの仕様、基本3.3Vらしい
The Power Functions 2.0 connector
■追記
AliExpressでPowered Up Connector(多分互換品)を購入
