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

More than 1 year has passed since last update.

概要

paiza.ioでelixirやってみた。
練習問題やってみた。

練習問題

GPIOを操作したフリをせよ。

サンプルコード


defmodule Pin2 do
  use GenServer

  def start_link(state) do
    GenServer.start_link(__MODULE__, state, name: __MODULE__)
  end

  def value() do
    GenServer.call(__MODULE__, :get)
  end

  def on(key) do
    GenServer.call(__MODULE__, {:on, key})
  end

  def off(key) do
    GenServer.call(__MODULE__, {:off, key})
  end

  def init(state) do
    {:ok, state}
  end

  def handle_call({:on, key}, _from, state) do
    IO.puts("#{key} 1")
    state = Map.put(state, key, 1)
    {:reply, state, state}
  end

  def handle_call({:off, key}, _from, state) do
    IO.puts("#{key} 0")
    state = Map.put(state, key, 0)
    {:reply, state, state}
  end

  def handle_call(:get, _from, state) do
    IO.inspect(state)
    {:reply, state, state}
  end
end

Pin2.start_link(%{GPIO15: 0, GPIO16: 0, GPIO17: 1, GPIO18: 0})
|> IO.inspect()

Pin2.value()
Pin2.on(:GPIO15)
Process.sleep(300)
Pin2.on(:GPIO16)
Pin2.on(:GPIO18)
Pin2.value()

実行結果

{:ok, #PID<0.97.0>}
%{GPIO15: 0, GPIO16: 0, GPIO17: 1, GPIO18: 0}
GPIO15 1
GPIO16 1
GPIO18 1
%{GPIO15: 1, GPIO16: 1, GPIO17: 1, GPIO18: 1}

成果物

以上。

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