6
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: IExでCircuits.GPIOを試す

6
Last updated at Posted at 2025-11-18

はじめに

ElixirでGPIO操作を行うには Circuits.GPIO を使います。
ノートPCのような一般的な開発環境ではGPIOデバイスが存在しないため、実機なしでの動作確認は難しいのですが、Circuits.GPIO v2のテスト用バックエンドや CircuitsSim を使うことで、テスト環境でもIEx上でもGPIOの挙動を試すことができます。

GPIOデバイスがない環境でCircuits.GPIOを使ってみる

IEx
Mix.install([{:circuits_gpio, "~> 2.1"}])
# :ok

Circuits.GPIO.open(17, :input)
# {:error, :not_found}

当然ながら、ホストPCにGPIOが無いため open/2 は失敗します。

テスト用バックエンドを使ってみる

Circuits.GPIOには、実機がなくても挙動を確認できるテスト用バックエンドが用意されています。
test: true を指定すると、CDevバックエンドのスタブ実装が有効になり、IEx上でもGPIOの読み書きを試すことができます。

IEx
Mix.install(
  [{:circuits_gpio, "~> 2.1"}],
  config: [
    circuits_gpio: [default_backend: {Circuits.GPIO.CDev, test: true}]
  ]
)

出力ピンの読み書きを確認する

テストモードでは、output ピンに対して値を書き込み、その値を read/1 で確認できます。

IEx
{:ok, pin} = Circuits.GPIO.open(17, :output)
# {:ok, %Circuits.GPIO.CDev{...}}

Circuits.GPIO.read(pin)
# 0

Circuits.GPIO.write(pin, 1)
# :ok

Circuits.GPIO.read(pin)
# 1

参考ドキュメント:

ピン一覧を確認する

IEx
Circuits.GPIO.enumerate()
# [
#   %{label: "pair_0_0", location: {"gpiochip0", 0}, controller: "stub0"},
#   %{label: "pair_0_1", location: {"gpiochip0", 1}, controller: "stub0"},
#   ...
# ]

CircuitsSimを使ったシミュレーション

CircuitsSimを使うと、仮想的なLEDやボタンを使って、GPIOの出力・入力・状態変化を確認できます。

単なるスタブではなく、「押す・離す」「点灯させる」などの状態変化を明示的に再現できるのが特長です。

仮想デバイスを構成する

次のように CircuitsSim.GPIO.Backend を指定し、
仮想LED(ピン10)と仮想ボタン(ピン11)をそれぞれGPIOピンに割り当てます。

IEx
Mix.install(
  [
    {:circuits_gpio, "~> 2.1"},
    {:circuits_sim, "~> 0.1"}
  ],
  config: [
    circuits_gpio: [default_backend: CircuitsSim.GPIO.Backend],
    circuits_sim: [
      config: [
        {CircuitsSim.Device.GPIOLED, gpio_spec: 10},
        {CircuitsSim.Device.GPIOButton, gpio_spec: 11}
      ]
    ]
  ]
)

出力ピン(LED)を操作する

IEx
{:ok, led} = Circuits.GPIO.open(10, :output)

Circuits.GPIO.write(led, 1)

仮想LEDの状態が 1(on) になります。
見た目に変化はありませんが、状態は内部で保持されており、CircuitsSim.info/0 で確認できます。

IEx
CircuitsSim.info()

ボタンを押す・離す

仮想ボタンの状態は次のように手動で操作できます。

IEx
CircuitsSim.Device.GPIOButton.press(11)
Circuits.GPIO.read(btn)
# 1

CircuitsSim.Device.GPIOButton.release(11)
Circuits.GPIO.read(btn)
# 0

参考ドキュメント:

おわりに

Circuits.GPIOは、テスト用バックエンドやCircuitsSimを活用することで、実機がなくてもGPIOの動作を試すことができます。

6
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
6
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?