我正在使用套接字将命令从一个RPi发送到另一个。当接收到rpi接收到命令“ turnRight”时,它会转动伺服(通过运行Yservo功能),而当接收到“ stop”时,它会终止进程来停止转动伺服器。伺服位置从x = 50的一半开始。问题是主代码中伺服位置没有更新,因此下一次运行该过程时,它将再次从50开始。
我需要在python进程中更新/更改一个值(以使Yservo中断它的while循环。例如while state == True :,因此当state更新为false时,while循环会中断并可以返回值x而不是终止进程)或让进程在主实例中更新变量(x)。
接收代码:
import socket
from multiprocessing import Process
import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
ps = 27
ys = 28
gpio.setup(ps,gpio.OUT)
gpio.setup(ys,gpio.OUT)
pitchS = gpio.PWM(ps,50)
pitchS.start(0)
x = 50
def Yservo(): #x is starting position / current position
global x
while 1:
x += 1
pitchS.ChangeDutyCycle(x)
time.sleep(1)
print(x)
if x >= 100:
while 1:
pass
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('', 6666))
print ("UDPServer Waiting for client on port 6666")
try:
while True:
dataFromClient, address = server_socket.recvfrom(256)
data = str(dataFromClient.decode('utf-8'))
data = data.split(',')
if data[0] == 'turnRight':
TS = Process(target=Yservo,args=())
TS.daemon = True
TS.start()
#TS.join()
if data[0] == 'stop':
TS.terminate()
TS.join()
except:
print('STOP! wait a minute')
TS.terminate()
TS.join()
答案 0 :(得分:0)
我建议您使进程保持活动状态,或者每次都将其生成/杀死,并让它每1秒侦听一个队列以从主进程获取订单。而且,只要您不终止子流程,只要x>=100
,Yservo子流程中的内部while循环将使核心之一最大化。这是不希望的。这个版本会记住您先前停在的位置:
import socket
from multiprocessing import Process, Queue
import RPi.GPIO as gpio
import time
import Queue
gpio.setmode(gpio.BCM)
start_position=50
ps = 27
ys = 28
gpio.setup(ps,gpio.OUT)
gpio.setup(ys,gpio.OUT)
pitchS = gpio.PWM(ps,50)
pitchS.start(0)
def Yservo(q, start_position):
command = None
x = start_position
while True:
try:
command = q.get(False)
except Queue.Empty:
pass
if command == "turn_right" and x < 100:
x += 1
pitchS.ChangeDutyCycle(x)
time.sleep(1)
print(x)
q = Queue()
TS = Process(target=Yservo,args=(q,start_position))
TS.daemon = True
TS.start()
try:
while True:
dataFromClient, address = server_socket.recvfrom(256)
data = str(dataFromClient.decode('utf-8'))
data = data.split(',')
if data[0] == 'turnRight':
q.put("turn_right")
if data[0] == 'stop':
q.put("stop")
except:
print('STOP! wait a minute')
TS.terminate()
TS.join()
q.get()
将阻止代码的执行,但是通过传递False
布尔值并捕获Queue.Empty
异常,您可以尝试在非封锁方式。