Seeed Studio XIAO ESP32C3 を MicroPython で使う

MicroPython は、一部にネイティブコードコンパイル機能を備えた Python インタプリタです。組み込みプロセッサや制約のあるシステム向けに実装された、Python 3.5 機能のサブセットを提供します。これは CPython とは異なり、その違いについてはこちらで詳しく読むことができます。
MicroPython のインストール
Esptool のインストール
まだ esptool.py をインストールしていない場合は、PC 上で pip を使ってインストールできます:
pip install esptool
XIAO ESP32C3 用 MicroPython ファームウェアのダウンロード
micropython.org からファームウェアのバイナリファイルをダウンロードする必要があります。 正しい bin ファイルをダウンロードしたら、そのフォルダへ移動し、そこで cmd ターミナルを開きます。 最終稿の時点で、最新バージョンの bin ファイルは次のとおりです:
ESP32_GENERIC_C3-20230602-v1.23.0.bin
XIAO ESP32C3 を PC に接続する
XIAO ESP32C3 ボードの BOOT ボタンを押し続けたまま、Type-C USB ケーブルで PC に接続して「bootloader」モードに入る必要があります。
ポートの確認
PC 上のすべてのシリアルデバイスを確認します。
- Linux
Linux では、dmesg コマンドを使用して接続されているデバイスを確認できます:
dmesg | grep tty
または、ls を使用してシリアルデバイスを一覧表示できます:
ls /dev/ttyS* /dev/ttyUSB*
- Window
Windows では、デバイスマネージャーからシリアルポートを確認できます。「ポート (COM と LPT)」セクションを探して、利用可能なシリアルポートを確認してください。また、コマンドプロンプトで mode コマンドを使用してシリアルポートを一覧表示することもできます:
mode
- macOS
macOS では、ls コマンドを使用して利用可能なシリアルポートを一覧表示できます:
ls /dev/cu*
これにより、すべてのシリアルポートデバイスが表示されます。

ポートがビジー状態の場合、次のコマンドを使用して、そのポートを使用しているプロセスを特定し、終了させることができます(macOS の場合): ポートを使用しているプロセスを特定します:
lsof | grep port
このコマンドはオープンファイルを一覧表示し、指定したポートを使用しているプロセスを検索します。 出力からプロセス ID(PID)を見つけ、そのプロセスを終了します:
kill -9 <PID>
PID を、実際に見つかったプロセス ID に置き換えてください。
フラッシュの消去
esptool.py --chip esp32c3 --port /dev/cu.usbmodem11301 erase_flash
'/dev/cu.usbmodem11301' を、お使いのシステムでの正しいポート名(例:Windows では COM3、Linux では /dev/ttyUSB0)に置き換えてください。

フラッシュへの書き込み
XIAO ESP32C3 にファームウェアを書き込みます:
esptool.py --chip esp32c3 --port /dev/cu.usbmodem11301 --baud 460800 write_flash -z 0x0 ESP32_GENERIC_C3-20240602-v1.23.0.bin
同様に、'/dev/cu.usbmodem11301' を正しいポート名に、'ESP32_GENERIC_C3-20240602-v1.23.0.bin' を使用するファームウェアファイルへのパスに置き換えてください。

その後、お好みのツールを使って ESP32 向けにスクリプトをコンパイルし始めることができます!
MicroPython におすすめのエディタ
一般的なツールの一部を以下に示します。
1. Thonny
Thonny をインストールして開き、次の手順に従って Thonny を設定します:
pip install thonny
#open thonny after installation
thonny
Run-->Configure Interpreter に移動し、Thonny のオプション内の Interpreter タブが下図のようになっていることを確認し、「CircuitPython (generic)」とポートを選択します:

ダイアログで "OK" をクリックすると、下図のように Thonny ウィンドウ下部に Micropython シェルが表示されるはずです。 Shell にスクリプトを 1 行ずつ入力して、フラッシュと SRAM のサイズを取得します:
import gc
gc.mem_free()
import esp
esp.flash_size()

Thonny を使って XIAO ESP32C3 上で MicroPython のセットアップに成功したこと、おめでとうございます!
2. Arduino Lab for MicroPython
Arduino Lab for MicroPython をダウンロードし、デバイスを PC に接続します。

次のようにコードを書きます:
from machine import Pin
import time
# Define the LED pin
led = Pin(7, Pin.OUT) # Use the correct GPIO number instead of D10
# Blink the LED in a loop
while True:
led.value(1) # Turn the LED on
time.sleep(1) # Wait for a second
led.value(0) # Turn the LED off
time.sleep(1) # Wait for a second

3. Visual Studio Code 上の Pymakr
-
Pymakr のインストール installation instructions に従って Pymakr をインストールします。
-
XIAO ESP32C3 をコンピュータに接続します。
-
新しいプロジェクトを作成 VS Code を開き、マイコン用の新しいプロジェクトを作成します。
-
新しい Python ファイルを追加 プロジェクト内に新しい Python ファイルを作成します。
-
スクリプトを MCU にアップロードし、スクリプトをコンパイル

4. uPtCraft IDE
ピン配置 / ポート情報

- さらに詳しい情報は、hardware overview を参照してください。
- Seeed Studio XIAO ESP32C3 回路図
XIAO ESP32C3 で MicroPython を始める
こちらに、micropython による ESP32 の操作に関するクイックリファレンスがあります。 micropython libraries についての詳細な知識はこちらを参照してください。
一般的なボード制御
MicroPython REPL(Read-Eval-Print-Loop)は、ボーレート 115200 の UART0(GPIO1=TX、GPIO3=RX)上にあります。オブジェクトが持つメソッドを調べるには、タブ補完が便利です。ペーストモード(ctrl-E)は、大きな Python コードの塊を REPL に貼り付けるのに便利です。 MicroPython(Python と同様)では、dir() 関数を使用してオブジェクトの属性やメソッドを一覧表示できます。 例えば、シェルで dir(machine) と入力します:

machine モジュール:
import machine
machine.freq() # get the current frequency of the CPU, for esp32c3 is 160000000
machine.freq(160000000) # set the CPU frequency to 160 MHz
esp モジュール:
import esp
esp.osdebug(None) # turn off vendor O/S debugging messages
esp.osdebug(0) # redirect vendor O/S debugging messages to UART(0)
# low level methods to interact with flash storage
esp.flash_size()
esp.flash_user_start()
esp.flash_erase(sector_no)
esp.flash_write(byte_offset, buffer)
esp.flash_read(byte_offset, buffer)
esp32 モジュール: ESP32C3、ESP32S2、および ESP32S3 には内部温度センサが搭載されており、摂氏温度を返します:
import esp32
esp32.mcu_temperature() # read the internal temperature of the MCU, in Celsius
ネットワーク - WLAN
Network モジュール: 詳細情報はこちらを参照してください。
import network
wlan = network.WLAN(network.STA_IF) # create station interface
wlan.active(True) # activate the interface
wlan.scan() # scan for access points
wlan.isconnected() # check if the station is connected to an AP
wlan.connect('ssid', 'key') # connect to an AP
wlan.config('mac') # get the interface's MAC address
wlan.ifconfig() # get the interface's IPv4 addresses
ap = network.WLAN(network.AP_IF) # create access-point interface
ap.config(ssid='ESP-AP') # set the SSID of the access point
ap.config(max_clients=10) # set how many clients can connect to the network
ap.active(True) # activate the interface
ローカル WiFi ネットワークに接続するための便利な関数は次のとおりです:
def do_connect():
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('ssid', 'key') #replace the ssid and key
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
遅延とタイミング
time モジュール:
import time
time.sleep(1) # sleep for 1 second
time.sleep_ms(500) # sleep for 500 milliseconds
time.sleep_us(10) # sleep for 10 microseconds
start = time.ticks_ms() # get millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
タイマー
ESP32 ポートには 4 つのハードウェアタイマーがあります。0 から 3(両端を含む)までのタイマー ID を指定して class を使用します:
from machine import Timer
tim0 = Timer(0)
tim0.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(0))
tim1 = Timer(1)
tim1.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(1))
周期はミリ秒単位です。 このポートでは現在、仮想タイマーはサポートされていません。
ピンと GPIO
machine.Pin クラス:
from machine import Pin
p2 = Pin(2, Pin.OUT) # create output pin on GPIO2
p2.on() # set pin to "on" (high) level
p2.off() # set pin to "off" (low) level
p2.value(1) # set pin to on/high
p3 = Pin(3, Pin.IN) # create input pin on GPIO3
print(p3.value()) # get value, 0 or 1
p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation
p6 = Pin(6, Pin.OUT, drive=Pin.DRIVE_3) # set maximum drive strength
使用可能なピンは次の範囲(両端を含む)です:2,3,4,5,6,7,8,9,10,20,21。これらは ESP32C3 チップの実際の GPIO ピン番号に対応します。
UART(シリアルバス)
machine.UART クラス:
from machine import UART
uart1 = UART(1, baudrate=9600, tx=21, rx=20)
uart1.write('hello') # write 5 bytes
uart1.read(5) # read up to 5 bytes
ESP32C3 には 1 つのハードウェア UART があります。ピンは以下のとおりです:
| UART | Pin |
|---|---|
| TX | 21 |
| RX | 20 |
PWM(パルス幅変調)
PWM はすべての出力対応ピンで有効にできます。基本周波数は 1Hz から 40MHz まで設定できますが、トレードオフとして、基本周波数が高くなるほどデューティ分解能は低下します。 machine.PWM クラス:
from machine import Pin, PWM
pwm2 = PWM(Pin(2), freq=5000, duty_u16=32768) # create PWM object from a pin
freq = pwm2.freq() # get current frequency
pwm2.freq(1000) # set PWM frequency from 1Hz to 40MHz
duty = pwm2.duty() # get current duty cycle, range 0-1023 (default 512, 50%)
pwm2.duty(256) # set duty cycle from 0 to 1023 as a ratio duty/1023, (now 25%)
duty_u16 = pwm2.duty_u16() # get current duty cycle, range 0-65535
pwm2.duty_u16(2**16*3//4) # set duty cycle from 0 to 65535 as a ratio duty_u16/65535, (now 75%)
duty_ns = pwm2.duty_ns() # get current pulse width in ns
pwm2.duty_ns(250_000) # set pulse width in nanoseconds from 0 to 1_000_000_000/freq, (now 25%)
pwm2.deinit() # turn off PWM on the pin
pwm3 = PWM(Pin(3), freq=20000, duty=512) # create and configure in one go
print(pwm3) # view PWM settings
ESP チップには異なるハードウェアペリフェラルがあります:
| ハードウェア仕様 | ESP32C3 | ESP32 |
|---|---|---|
| グループ数(スピードモード) | 1 | 2 |
| グループあたりのタイマー数 | 4 | 4 |
| グループあたりのチャネル数 | 6 | 8 |
| 異なる PWM 周波数(グループ * タイマー) | 4 | 8 |
| 合計 PWM チャネル数(ピン、デューティ)(グループ * チャネル) | 6 | 16 |
ADC(アナログ-デジタル変換)
XIAO ESP32C3 では、ピン 2,3,4 で ADC 機能が利用できます。
A3(GP105) は ADC2 を使用しており、誤ったサンプリング信号により動作しなくなる場合があります。アナログ読み取りには、代わりに ADC1(A0/A1/A2) を使用してください。XIAO ESP32C3 のデータシートを参照してください。
machine.ADC クラス:
from machine import ADC
adc = ADC(pin) # create an ADC object acting on a pin
val = adc.read_u16() # read a raw analog value in the range 0-65535
val = adc.read_uv() # read an analog value in microvolts
SPI
ソフトウェア SPI バス
ソフトウェア SPI(ビットバンギングを使用)はすべてのピンで動作し、machine.SoftSPI クラスを介してアクセスします:
from machine import Pin, SoftSPI
# construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(2), mosi=Pin(4), miso=Pin(6))
spi.init(baudrate=200000) # set the baudrate
spi.read(10) # read 10 bytes on MISO
spi.read(10, 0xff) # read 10 bytes while outputting 0xff on MOSI
buf = bytearray(50) # create a buffer
spi.readinto(buf) # read into the given buffer (reads 50 bytes in this case)
spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI
spi.write(b'12345') # write 5 bytes on MOSI
buf = bytearray(4) # create a buffer
spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf
ハードウェア SPI バス
ハードウェア SPI は machine.SPI クラスを介してアクセスし、上記のソフトウェア SPI と同じメソッドを持ちます:
from machine import Pin, SPI
hspi = SPI(1, 10000000)
hspi = SPI(1, 10000000, sck=Pin(8), mosi=Pin(10), miso=Pin(9))
| SPI | Pin |
|---|---|
| SCK | D8 |
| MOSI | D10 |
| MISO | D9 |
I2C
ソフトウェア I2C バス
ソフトウェア I2C(ビットバンギングを使用)は、すべての出力対応ピンで動作し、machine.SoftI2C クラスを介してアクセスします:
from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(7), sda=Pin(6), freq=100000)
i2c.scan() # scan for devices
i2c.readfrom(0x3a, 4) # read 4 bytes from device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a
buf = bytearray(10) # create a buffer with 10 bytes
i2c.writeto(0x3a, buf) # write the given buffer to the peripheral
ハードウェア I2C バス
ドライバは machine.I2C クラスを介してアクセスし、上記のソフトウェア I2C と同じメソッドを持ちます:
from machine import Pin, I2C
i2c = I2C(0, scl=Pin(7), sda=Pin(6), freq=400000)
| I2C | GPIO | Pin |
|---|---|---|
| SCL | GPIO7 | D5 |
| SDA | GPIO6 | D4 |
XIAO 用拡張ボードベース
前提条件:
| ヘッダーピンをはんだ付けした XIAO ESP32C3 | XIAO 用拡張ボードベース | Grove Light sensor |
|---|---|---|
![]() | ![]() | ![]() |
照度センサーのデータを読み取る

import time
from machine import Pin, ADC
# Initialize the analog input on pin 2 (corresponds to A0)
analog_in = ADC(Pin(2))
analog_in.atten(ADC.ATTN_11DB) # Configure the input range (0-3.6V)
def get_voltage(pin):
# Convert the raw ADC value to voltage
return (pin.read() / 4095) * 3.3
while True:
# Read the raw analog value
raw_value = analog_in.read()
# Convert the raw value to voltage
voltage = get_voltage(analog_in)
# Print the raw value and voltage to the serial console
print("[Light] Raw value: {:5d} Voltage: {:.2f}V".format(raw_value, voltage))
# Delay for a short period of time before reading again
time.sleep(1)

OLED 画面を点灯させる
XIAO ESP32C3 を接続し、Thonny を開いて右下をクリックしてインタプリタを設定します インタプリタ Micropython (ESP32) を選択し、Port >>> OK をクリック します

すべてがうまくいけば、シェルに出力が表示されます 必要な libraries をインストールします "Tools" をクリック >>> "Management Packages" をクリック >>> ライブラリ名を入力 >>> "Search micropython-lib and PyPl" をクリック

スクリプトを実行し、ボードにフラッシュします。 コーディングが終わったら、緑のボタンをクリックしてスクリプトを実行します。
import time
from machine import Pin, SoftI2C
import ssd1306
import math
# Pin assignment
i2c = SoftI2C(scl=Pin(7), sda=Pin(6)) # Adjust the Pin numbers based on your connections
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.fill(0) # Clear the screen
oled.text("Hello, Seeder!", 10, 15)
oled.text("/////", 30, 40)
oled.text("(`3`)y", 30, 55)
oled.show() # Show the text

この記事をお読みいただきありがとうございます! コメント欄でぜひご意見をお聞かせください。
リソース
- XIAO ESP32C3 用 MicroPython のファームウェアバイナリファイル
技術サポート & 製品ディスカッション
弊社製品をお選びいただきありがとうございます。私たちは、製品をできるだけスムーズにご利用いただけるよう、さまざまなサポートを提供しています。お好みやニーズに合わせてお選びいただける、複数のコミュニケーションチャネルをご用意しています。


