我开发了一种使用继电器的智能灯泡,当我拍手时可以打开和关闭灯泡。这与一个简单的python脚本一起工作,但是我想将django用作处理此用例的服务器。我无法处理以下情况
1)会有一个用于打开和关闭灯泡的按钮(我可以这样做)2)当我拍手时,灯泡应该打开,如果我拍手时灯泡应该关闭。
对于第二种情况,我如何连续监听传感器数据,以便我的灯泡可以相应地采取行动。
这是有效的简单脚本
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
# telling pi we are not using the pin but BCM standard GPIO names for the pins
GPIO.setmode(GPIO.BCM)
BULB_OUTPUT_PIN = 4
SOUND_INPUT_PIN = 17
# as I am refering to the BCM mode instead of BOARD mode so the output pin is
# GPIO4 which is 7th pin in the pi when starting the first pin from left.
GPIO.setup(BULB_OUTPUT_PIN, GPIO.OUT)
GPIO.output(BULB_OUTPUT_PIN, GPIO.HIGH)
# for sound sensor
GPIO.setup(SOUND_INPUT_PIN, GPIO.IN)
SleepTime = 6
# main loop
try:
while 1:
print('#######GPIO INPUT PIN##### ', GPIO.input(SOUND_INPUT_PIN))
if GPIO.input(SOUND_INPUT_PIN) == GPIO.LOW:
print("##########Sound is sensed############")
time.sleep(SleepTime)
GPIO.output(BULB_OUTPUT_PIN, GPIO.LOW)
print("#Relay is triggered in the switch 1########")
time.sleep(SleepTime)
GPIO.cleanup()
print("Good bye!")
# End program cleanly with keyboard
except KeyboardInterrupt:
print("Quit")
# Reset GPIO settings
GPIO.cleanup()
使用Django
import RPi.GPIO as GPIO
import time
SleepTime = 6
BULB_OUTPUT_PIN = 4
SOUND_INPUT_PIN = 17
def smart_bulb(request, action=None):
GPIO.setmode(GPIO.BCM)
GPIO.setup(BULB_OUTPUT_PIN, GPIO.OUT)
try:
if action == "on":
# telling pi we are not using the pin but BCM standard GPIO names for the pins
# as I am refering to the BCM mode instead of BOARD mode so the output pin is
# GPIO4 which is 7th pin in the pi when starting the first pin from left.
print("bulb will glow now")
time.sleep(SleepTime)
GPIO.output(BULB_OUTPUT_PIN, GPIO.HIGH)
else:
print("bulb will fade out")
time.sleep(SleepTime)
GPIO.output(BULB_OUTPUT_PIN, GPIO.LOW)
except KeyboardInterrupt:
GPIO.cleanup()
这不是树莓派的特定问题,而是Django的特定问题。