Skip to content

Instantly share code, notes, and snippets.

@wsmoak
Last active January 9, 2016 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wsmoak/36e0027579eb10dfa112 to your computer and use it in GitHub Desktop.
Save wsmoak/36e0027579eb10dfa112 to your computer and use it in GitHub Desktop.
Cat Feeder - moved from gist to https://github.com/wsmoak/cat_feeder
defmodule CatFeeder do
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Define workers and child supervisors to be supervised
# worker(CatFeeder.Worker, [arg1, arg2, arg3]),
worker(I2c, ["i2c-1", 0x13, [name: ProximitySensor]]),
worker(CatFeeder.ProximityWorker, []),
# worker(CatFeeder.ServoWorker, []),
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: CatFeeder.Supervisor]
Supervisor.start_link(children, opts)
end
end

Copyright 2015 Wendy Smoak

ServoWorker is an Elixir port of the Adafruit_PWM_Servo_Driver code in Adafruit's Raspberry-Pi Python Code Library

https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_PWM_Servo_Driver

As such, it inherits the BSD license and the additional information shown below:

Adafruit's Raspberry-Pi Python Code Library

Here is a growing collection of libraries and example python scripts for controlling a variety of Adafruit electronics with a Raspberry Pi

In progress!

Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!

Written by Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries. BSD license, all text above and below must be included in any redistribution

To download, we suggest logging into your Pi with Internet accessibility and typing:

git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git

============ Copyright (c) 2012-2013 Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

defmodule CatFeeder.ProximityWorker do
require Logger
use GenServer
# register address
@cmd 0x80
@prox_result_h 0x87
@prox_result_l 0x88
# Client
def start_link() do
GenServer.start_link(__MODULE__, [], name: ProximityChecker)
end
# Server Callbacks
def init(_opts) do
# turn on proximity sensing by setting bits 0 and 1
pid = Process.whereis( ProximitySensor )
I2c.write(pid, <<@cmd, 0x03>> )
# start it up! wait a bit so the process exists.
Process.send_after(ProximityChecker, :check_it, 1000)
{:ok, %{:status => :idle}}
end
def terminate(reason, _state) do
Logger.debug "Received call to terminate for #{reason}"
pid = Process.whereis(ProximitySensor)
# turn off proximity sensing
I2c.write(pid, <<@cmd, 0x00>> )
end
def handle_info(:check_it, state = %{:status => :waiting} ) do
IO.write "state in :check_it handle_info w/ :waiting pattern match is "
IO.inspect state
# we've received a request to check the proximity
# but we're still waiting ...
# we have to get the official :time_is_up message before we
# change state
Logger.debug "it's not time yet!"
# TODO: sanity check and reset if we've been waiting too long
# Store the last trigger time in the state?
{:noreply, state}
end
# the official timer ended, so change the state
def handle_info(:time_is_up, state) do
Process.send_after(ProximityChecker, :check_it, 513)
{:noreply, Map.update!(state, :status, fn _x -> :idle end) }
end
# this is a 'custom message' in handle_info
def handle_info(:check_it, state) do
IO.write "state in :check_it handle_info w/ pattern match is "
IO.inspect state
val = check_proximity
if val > 2100 do
Logger.debug "FEED THE CAT!"
# spin the servo
# wait "20 minutes" (or 10 seconds for now)
Process.send_after(ProximityChecker, :time_is_up, 10000)
{:noreply, Map.update!(state, :status, fn x -> :waiting end) }
else
Process.send_after(ProximityChecker, :check_it, 513)
{:noreply, Map.update!(state, :status, fn x -> :idle end) }
end
end
def handle_info(msg, state) do
IO.write "in generic handle_info, msg is "
IO.inspect msg
IO.write " ... and state is "
IO.inspect state
{:noreply, state}
end
# Helper Functions
def check_proximity do
pid = Process.whereis(ProximitySensor)
<< val :: 16 >> = I2c.write_read(pid,<<@prox_result_h>> ,2)
Logger.debug "Proximity value #{val}"
val
end
end
defmodule CatFeeder.ServoWorker do
require Logger
use Bitwise
use GenServer
@mode1 0x00 # bit 4 is SLEEP 000X0000
@mode2 0x01
@prescale 0xFE
@all_on_l 0xFA
@all_on_h 0xFB
@all_off_l 0xFC
@all_off_h 0xFD
@led0_on_l 0x06
@led0_on_h 0x07
@led0_off_l 0x08
@led0_off_h 0x09
@allcall 0x01
@outdrv 0x04
@swrst 0x06
# Client
def start_link() do
GenServer.start_link(__MODULE__, [], name: ServoSpinner)
end
# Server Callbacks
def init(_opts) do
Logger.debug "Initializing..."
pid = Process.whereis( Servo )
set_all_pwm(pid,0,0)
I2c.write(pid, <<@mode2, @outdrv>>) # external driver, see docs
I2c.write(pid, <<@mode1, @allcall>>) # program all PCA9685's at once
:timer.sleep 5
prescale(pid, 60) # set pwm to 60 Hz
{:ok, :nostate}
end
def handle_info(:bump, state) do
pid = Process.whereis( Servo )
bump(pid)
{:noreply, state}
end
# PCA9685 Software Reset (Section 7.6 on pg 28)
def swrst do
Logger.debug "PCA9685 Software Reset..."
{:ok,pid}=I2c.start_link("i2c-1", 0x00)
:timer.sleep 10
I2c.write(pid,<<@swrst>>)
end
def prescale(pid,freq) do
Logger.debug "Setting prescale to #{freq} Hz"
# pg 14 and solve for prescale or example on pg 25
prescaleval = trunc(Float.round( 25000000.0 / 4096.0 / freq ) - 1 )
Logger.debug "prescale value is #{prescaleval}"
oldmode = I2c.write_read(pid, <<@mode1>>, 1)
:timer.sleep 5
I2c.write(pid, <<@mode1, 0x11>>) # set bit 4 (sleep) to allow setting prescale
I2c.write(pid, <<@prescale, prescaleval>> )
I2c.write(pid, <<@mode1, 0x01>> ) #un-set sleep bit
:timer.sleep 5 # pg 14 it takes 500 us for the oscillator to be ready
I2c.write(pid, <<@mode1>> <> oldmode ) # put back old mode
end
# spin one way
def min(pid) do
Logger.debug "min"
set_pwm(pid, 0, 0, 0x0096)
end
# spin the other way
def max(pid) do
Logger.debug "max"
set_pwm(pid, 0, 0, 0x0258)
end
# stop
def mid(pid) do
Logger.debug "mid"
set_pwm(pid, 0, 0, 0)
end
# spins just a bit in one direction and stops
def bump(pid) do
Logger.debug "bump"
min(pid)
:timer.sleep 200
mid(pid)
end
# The registers for each of the 16 channels are sequential
# so the address can be calculated as an offset from the first one
def set_pwm(pid, channel, on, off) do
I2c.write(pid, <<@led0_on_l+4*channel, on &&& 0xFF>>)
I2c.write(pid, <<@led0_on_h+4*channel, on >>> 8>>)
I2c.write(pid, <<@led0_off_l+4*channel, off &&& 0xFF>>)
I2c.write(pid, <<@led0_off_h+4*channel, off >>> 8>>)
end
# The PCA9685 has special registers for setting ALL channels
# (or 1/3 of them) to the same value.
def set_all_pwm(pid, on, off) do
I2c.write(pid, <<@all_on_l, on &&& 0xFF>>)
I2c.write(pid, <<@all_on_h, on >>> 8>>)
I2c.write(pid, <<@all_off_l, off &&& 0xFF>>)
I2c.write(pid, <<@all_off_h, off >>> 8>>)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment