Skip to content

Instantly share code, notes, and snippets.

@chmanie
Created February 17, 2018 00:38
Show Gist options
  • Save chmanie/e8a76e733b7e5ec7479d1172a14786c7 to your computer and use it in GitHub Desktop.
Save chmanie/e8a76e733b7e5ec7479d1172a14786c7 to your computer and use it in GitHub Desktop.
A blinking LED using GenServer
defmodule Blinky do
use GenServer
alias ElixirALE.GPIO
@duration 2000
def start_link(state \\ %{on: true, pid: nil}) do
GenServer.start_link(__MODULE__, state, name: __MODULE__)
end
def init(%{on: is_on, pid: _pid}) do
{:ok, pid} = GPIO.start_link(23, :output)
schedule_toggle()
{:ok, %{on: is_on, pid: pid}}
end
def handle_info(:toggle, %{on: true, pid: pid}) do
GPIO.write(pid, 1)
schedule_toggle()
{:noreply, %{on: false, pid: pid}}
end
def handle_info(:toggle, %{on: false, pid: pid}) do
GPIO.write(pid, 0)
schedule_toggle()
{:noreply, %{on: true, pid: pid}}
end
def schedule_toggle() do
Process.send_after(self(), :toggle, @duration)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment