Last active
August 29, 2015 14:19
-
-
Save seki/30ea7dda7d1ffe28ff92 to your computer and use it in GitHub Desktop.
HC-SR04.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module GPIO | |
module_function | |
def export(n, dir) | |
File.open("/sys/class/gpio/export", "w") do |fp| | |
fp.write(n.to_s) | |
end | |
sleep 0.1 | |
File.open("/sys/class/gpio/gpio#{n}/direction", "w") do |fp| | |
fp.write(dir) | |
end | |
end | |
def unexport(n) | |
File.open("/sys/class/gpio/unexport", "w") do |fp| | |
fp.write(n.to_s) | |
end | |
end | |
def read(n) | |
File.read("/sys/class/gpio/gpio#{n}/value") | |
end | |
def write(n, value) | |
File.open("/sys/class/gpio/gpio#{n}/value", "w") do |fp| | |
fp.write(value.to_s) | |
end | |
end | |
class Edge | |
def initialize(n, mode='both') | |
File.open("/sys/class/gpio/gpio#{n}/edge", "w") do |fp| | |
fp.write(mode) | |
end | |
@value = File.open("/sys/class/gpio/gpio#{n}/value") | |
end | |
def wait(timeout=nil) | |
IO.select([], [], [@value], timeout) | |
read | |
end | |
def read | |
@value.seek(0) | |
@value.read | |
end | |
def close | |
@value.close | |
end | |
end | |
end | |
GPIO.export(17, 'out') | |
GPIO.export(27, 'in') | |
GPIO.write(17, 1) | |
sleep 0.00001 | |
GPIO.write(17, 0) | |
edge = GPIO::Edge.new(27) | |
puts edge.read | |
puts edge.wait(10) | |
s = Time.now | |
puts edge.wait(10) | |
e = Time.now | |
edge.close | |
puts (e.to_f - s.to_f) * 17000 | |
GPIO.unexport(17) | |
GPIO.unexport(27) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment