功能描述:
1、树莓派上通过python脚本实现GPIO自动切换,并预留udp接口,可实现自动控制和手动控制切换。
2、启动脚本自动控制GPIO18输出切换,udp向9999端口发送"change",转为手动切换,并改变输出状态,每发送一次改变一次状态,发送"auto"切换为自动控制。
3、源码:
#!/usr/bin/python3
from socket import*
import RPi.GPIOasGPIO
import _thread
import time
HOST="0.0.0.0"
PORT=9999
PIN=18
model ="auto"
state ="close"
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN,GPIO.OUT)
s = socket(AF_INET, SOCK_DGRAM)
s.bind((HOST, PORT))
def threadForControl(threadName):
global model,state
while True:
if model=='auto':
if state=="open":
GPIO.output(PIN, GPIO.LOW)
state ="close"
else:
GPIO.output(PIN, GPIO.HIGH)
state ="open"
time.sleep(10)
def threadForComm(threadName):
global model,state
while True:
data, address = s.recvfrom(1024)
cmd = data.decode('ascii')
if cmd=='auto':
model ='auto'
s.sendto('auto'.encode('ascii'),address)
elif cmd=='change':
model ='hand'
if state=="open":
GPIO.output(PIN, GPIO.LOW)
state ="close"
else:
GPIO.output(PIN, GPIO.HIGH)
state ="open"
s.sendto('changed'.encode('ascii'),address)
print('Accept message:'+ cmd)
try:
_thread.start_new_thread( threadForControl, ("controlThread", ) )
_thread.start_new_thread(threadForComm, ("commThread", ))
except:
s.close()
print("Error: unable to start thread")
while1:
pass