Skip to content

Instantly share code, notes, and snippets.

@sonkm3
Last active February 14, 2021 01:02
Show Gist options
  • Save sonkm3/1e6c2fbfd592e9b7193350b19799e824 to your computer and use it in GitHub Desktop.
Save sonkm3/1e6c2fbfd592e9b7193350b19799e824 to your computer and use it in GitHub Desktop.
Raspberry Pi pico、MicroPythonでLチカするまでのメモ

Raspberry Pi pico、MicroPythonでLチカするまでのメモ

MicroPythonを使えるように準備する

https://www.raspberrypi.org/documentation/pico/getting-started/

  • 「Getting started with MicroPython」のところから「Download UF2 file」をダウンロード
  • Raspberry Pi picoのボタンを押しながらUSBケーブルを接続する(PCに接続する)
  • ダウンロードしたUF2ファイルをマウントされた「RPI-RP2」にコピー
  • 自動でアンマウントされ、再起動したら完了

vscodeの環境整備

  • Pico-Goをインストールする

REPLでLチカ

Pico-GoのターミナルがRaspberry Pi picoに接続するとREPLが使えるようになるのでREPLでLEDの点灯、消灯ができる

Searching for boards on serial devices...
No boards found on USB
Connecting to /dev/tty.usbmodem0000000000001...

>>> from machine import Pin
>>> led = Pin(25, Pin.OUT)
>>> led.value(1)
>>> led.value(0)
>>> 

lambdaを使って点滅させる

>>> from machine import Pin, Timer
>>> led = Pin(25, Pin.OUT)
>>> tim = Timer()
>>> tim.init(freq=2.5, mode=Timer.PERIODIC, callback=lambda _: led.toggle())
>>> from machine import Pin, Timer
>>> Timer().init(freq=2.5, mode=Timer.PERIODIC, callback=lambda _: Pin(25, Pin.OUT).toggle())

2行でいけた

点滅のためのTimerを停止する場合はdeinit()

>>> tim.deinit()

PWMで緩やかに点滅させる

from machine import Pin, PWM, Timer

pwm = PWM(Pin(25))
pwm.freq(1000)
tim = Timer()

def get_pwm_callback(duty, direction):
    def pwm_callback(_):
        nonlocal duty, direction
        duty += direction
        if duty >= 255:
            direction = -1
        elif duty <= 0:
            direction = 1
        pwm.duty_u16(duty * duty)
    return pwm_callback

pwm_callback = get_pwm_callback(0, 1)

tim.init(freq=100, mode=Timer.PERIODIC, callback=pwm_callback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment