5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Elixir(AtomVM)非同期Lチカ LEDごとプロセスを作る 〜 Raspberry Pi Pico 〜

Last updated at Posted at 2025-12-07

今回はElixir(AtomVM)で非同期Lチカを作ります
Elixirを使っているので簡単にプロセスを増やして非同期処理が可能です

前提知識

Raspberry Pi Pico でLチカの知識を前提とします

実行イメージ

配線

こちらと同じです↓

プログラムを書く

mix.exs
defmodule RpiPicoLed.MixProject do
  use Mix.Project

  def project do
    [
      app: :rpi_pico_led,
      version: "0.1.0",
      elixir: "~> 1.17",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      atomvm: [
-       start: RpiPicoLed,
+       start: RpiPicoLed03,
        lash_offset: 0x210000
      ]
    ]
  end

## 省略 ###

lib/rpi_pico_led03.exを追加

lib/rpi_pico_led03.ex
defmodule RpiPicoLed03 do
  @moduledoc """
  Documentation for `RpiPicoLed`.
  """
  @led_on_sec 150
  @blue_pin 2
  @yellow_pin 3
  @red_pin 4

  # コンパイルする際の警告を抑制する
  # AtomVMのライブラリGPIOが対象です

  def start do
    init(@blue_pin)
    init(@yellow_pin)
    init(@red_pin)
    spawn(fn -> on_off(@blue_pin, 1000) end)
    spawn(fn -> on_off(@yellow_pin, 500) end)
    spawn(fn -> on_off(@red_pin, 250) end)
    loop()
  end

  defp loop() do
    Process.sleep(1000)
    loop()
  end

  @compile {:no_warn_undefined, [GPIO]}
  defp init(pin) do
    GPIO.init(pin)
    GPIO.set_pin_mode(pin, :output)
  end

  @compile {:no_warn_undefined, [GPIO]}
  defp on_off(pin, sec) do
    GPIO.digital_write(pin, :high)
    Process.sleep(@led_on_sec)
    GPIO.digital_write(pin, :low)
    Process.sleep(sec - @led_on_sec)
    on_off(pin, sec)
  end
end

説明

  • start
    • 各LEDを初期化
    • spawnを使って各LEDごと無限ループするプロセスを作ります
      • 青LED 1秒間隔で光る
      • 黄LED 0.5秒間隔で光る
      • 赤LED 0.25秒間隔で光る
    • loop
      • 1秒ごとループ
        • これはメインプロセスを無限ループすることによって終了を防いています

参考

ソース

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?