Skip to content

Instantly share code, notes, and snippets.

@nezuppo
Created May 12, 2019 13:16
Show Gist options
  • Save nezuppo/a48fcac5d286c186d05a93302e35bb24 to your computer and use it in GitHub Desktop.
Save nezuppo/a48fcac5d286c186d05a93302e35bb24 to your computer and use it in GitHub Desktop.
ラズパイに取り付けたタクトスイッチ用のスクリプト
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import subprocess
import urllib.request
import json
GPIO_POWER = 3
GPIO_DISABLE_STEPPERS = 20
GPIO_LED = 16
def disable_steppers(channel):
url = 'http://localhost:5000/api/printer/command'
json_data = json.dumps({
'command': 'M18 X Y Z',
}).encode("utf-8")
with open('/some/where/api-key') as f:
api_key = f.read().rstrip()
req = urllib.request.Request(url)
req.add_header('X-Api-Key', api_key)
req.add_header('Content-Type', 'application/json')
req.data = json_data
with urllib.request.urlopen(req) as f:
buff = f.read().decode()
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_POWER, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(GPIO_DISABLE_STEPPERS, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(GPIO_DISABLE_STEPPERS, GPIO.FALLING,
callback=disable_steppers, bouncetime=2000)
# LED 点灯
GPIO.setup(GPIO_LED, GPIO.OUT)
GPIO.output(GPIO_LED, GPIO.HIGH)
while True:
GPIO.wait_for_edge(GPIO_POWER, GPIO.FALLING)
sw_counter = 0
while True:
sw_status = GPIO.input(GPIO_POWER)
if sw_status == 0:
sw_counter = sw_counter + 1
if sw_counter >= 50:
# long press of the button
#print('long press')
# LED 点滅
GPIO.output(GPIO_LED, GPIO.LOW)
time.sleep(0.5)
GPIO.output(GPIO_LED, GPIO.HIGH)
subprocess.run(['shutdown', '-h', 'now'])
break
else:
# short press of the button
# print('short press')
break
time.sleep(0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment