Skip to content

Instantly share code, notes, and snippets.

@Arkham
Last active September 20, 2023 20:40
Show Gist options
  • Save Arkham/a08f264b98a08defbc0676a153e6d6fe to your computer and use it in GitHub Desktop.
Save Arkham/a08f264b98a08defbc0676a153e6d6fe to your computer and use it in GitHub Desktop.
Fun with Ruby and a Raspberry PI
require 'pi_piper'
require 'ostruct'
laser = PiPiper::Pin.new(pin: 17, direction: :out)
alarm = PiPiper::Pin.new(pin: 18, direction: :out)
vibration = PiPiper::Pin.new(pin: 27, direction: :in)
i2c = PiPiper::I2C.new
def turn_on(pin)
pin.off
end
def turn_off(pin)
pin.on
end
def read_channel(i2c, number)
value = Integer("#{40 + number}", 16).chr.bytes
i2c.write(to: 0x48, data: value)
i2c.read(1)
i2c.read(1)
end
class Rule < OpenStruct
def check
value = read_fun.()
# puts "#{name} = #{value}"
if trigger_fun.(value)
puts "#{name} was triggered! Value = #{value}"
return true
end
end
end
RULES = [
Rule.new(
name: 'laser',
read_fun: ->() { read_channel(i2c, 0).first },
trigger_fun: ->(value) { value > 50 }
),
Rule.new(
name: 'temperature',
read_fun: ->() { read_channel(i2c, 1).first },
trigger_fun: ->(value) { value < 115 }
),
Rule.new(
name: 'sound',
read_fun: ->() { read_channel(i2c, 2).first },
trigger_fun: ->(value) { value < 100 }
),
Rule.new(
name: 'vibration',
read_fun: ->() { vibration.read },
trigger_fun: ->(value) { value.zero? }
)
]
begin
turn_on(laser)
turn_off(alarm)
loop do
sleep 0.2
if RULES.find(&:check)
turn_on(alarm)
else
turn_off(alarm)
end
end
rescue Interrupt
puts "Exiting, bye friend!"
ensure
turn_off(laser)
turn_off(alarm)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment