I thought about doing something with the Raspberry Pi that I had left for a long time, but I can't think of a theme ... (sweat)
As a result of thinking for a while, I decided to try how versatile PyCall I have been using from the other day can be used, so I put PyCall in Raspberry Pi and made a circuit to detect ON / OFF of the switch and run it with Ruby Saw.
[Reference site] Raspberry Pi GPIO input / output sample (Python, C language, shell script)
Since Ruby 2.1 was included immediately after the initial installation, I will use it as it is. Install PyCall with the following command.
python
$ sudo apt install -y ruby-dev
$ sudo gem install --pre pycall
Let's take a look at the source code published on the reference site mentioned above.
gpio_input.py
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
IO_NO = 4
print("press ^C to exit program ...\n")
GPIO.setmode(GPIO.BCM)
GPIO.setup(IO_NO, GPIO.IN)
try:
while True:
print(GPIO.input(IO_NO))
time.sleep(1)
except KeyboardInterrupt:
print("detect key interrupt\n")
GPIO.cleanup()
print("Program exit\n")
When I try it out ...
python
$ python gpio_input.py
press ^C to exit program ...
1
1
1
0
0
1
1
1
0
1
1
^Cdetect key interrupt
Program exit
$
It seems that when you press the button, it becomes 0, and when you release it, 1 is displayed. For the time being, I found that the wiring was correct.
If you use the sample code as it is, it will be a little dull, so let's change it so that it is displayed while counting the number of ON / OFF times.
gpio_input.rb
require 'pycall/import'
include PyCall::Import
pyimport 'RPi.GPIO', as: 'gpio'
io_no = 4
status = 1
buff = 1
cnt = 0
puts "press ^C to exit program ...\n"
gpio.setmode.(gpio.BCM)
gpio.setup.(io_no, gpio.IN)
# 「Ctrl」+Stop at "C"
Signal.trap(:INT) do
puts "detect key interrupt\n"
gpio.cleanup.()
puts "Program exit\n"
exit 0
end
loop do
status = gpio.input.(io_no)
if buff != status
if status == 1
puts "OFF"
else
cnt += 1
puts "ON(#{cnt})"
end
end
buff = status
sleep 0.5
end
By the way, in Ruby, variables starting with uppercase letters cannot be defined (I've heard that ...), so I change them to lowercase letters.
Execute the command and press the button several times ...
python
$ ruby gpio_input.rb
press ^C to exit program ...
ON(1)
OFF
ON(2)
OFF
ON(3)
OFF
^Cdetect key interrupt
Program exit
$
It was done (^-^)
If you use a gem called PI Piper, you can do it with Ruby without any problem, so you don't need to use PyCall ...
Well, what should I do next?
Recommended Posts