目前,我有一個程式,旨在通過套接字通信向電機連續發送坐標(編碼為 ASCII),以便電機以正弦運動運動。我希望將這些坐標連續發送到電機,直到用戶輸入end命令列。
我目前有這個:
import socket
import numpy as np
import math
pi = math.pi
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Server Connection
s1.connect(("192.168.177.200", 4001))
gearpositionlim = 10000
# sample sine
step = 2*pi / 2000
time_range = np.arange(0,2*pi step,step)
x_motorrange = gearpositionlim*np.sin(time_range)
x_motorrange = ['la' str(int(i)) for i in x_motorrange]
def motormove():
for i in np.arange(0,len(x_motorrange)):
s1.send(str(str(x_motorrange[i]) "\n").encode("ASCII"))
message = s1.recv(1024).decode()
#-------------------------------------------
while True:
motormove()
name = input("Code Running: Type 'end' to end program: ")
if name == 'end':
break
else:
print("ERROR: Home position not returned to")
exit()
#send the motor back to home position
s1.send("la0\n".encode("ASCII"))
s1.send("m\n".encode("ASCII"))
s1.send("np\n".encode("ASCII"))
s1.send("DI\n".encode("ASCII"))
但是,代碼目前只發送一次坐標x_motorrange,然后提示輸入輸入end。然而,我希望此提示始終出現在命令列中,并且僅在給出motormove()提示時才停止例程end。如何才能做到這一點?
uj5u.com熱心網友回復:
而不是寫exit你可以使用KeyboardInterrupt. 所以當你 prees ctrl c它會停止:
try:
while True:
do_something()
except KeyboardInterrupt:
pass
uj5u.com熱心網友回復:
有很多方法可以解決這個問題:
例如,將一段代碼移動到另一個執行緒或行程
import threading
import socket
import time
import numpy as np
import math
class MotoMover(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
pi = math.pi
self.id = 0
self.s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP Server Connection
self.s1.connect(("192.168.177.200", 4001))
gearpositionlim = 10000
# sample sine
step = 2 * pi / 2000
time_range = np.arange(0, 2 * pi step, step)
self.x_motorrange = gearpositionlim * np.sin(time_range)
self.x_motorrange = ['la' str(int(i)) for i in self.x_motorrange]
self.connected = False
self.stopped = False
def try_to_connect(self):
try:
self.s1.settimeout(1000)
self.s1.connect(("192.168.177.200", 4001), timeout=1000)
self.connected = True
except:
self.connected = False
def motormove(self):
for i in np.arange(0, len(self.x_motorrange)):
self.s1.send(str(str(self.x_motorrange[i]) "\n").encode("ASCII"))
message = self.s1.recv(1024).decode()
def run(self): ## main cycle of the thread
while not self.stopped:
if not self.connected:
# print('connecting to server...')
self.try_to_connect()
else:
self.id = 1
self.motormove()
time.sleep(1) #pause = 1 sec. you can reduce it to a few ms (0.01, for example), but I do not recommend removing it completely
def stop(self):
self.stopped = True
def main():
moto = MotoMover()
moto.start()
while True:
name = input("Code Running: Type 'end' to end program: ")
if name.startswith('end'):
print("end of the program")
moto.stop()
moto.join()
exit(0)
else:
print('!', name)
if len(name) >= 3:
name = ''
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/421473.html
標籤:
上一篇:套接字不發出訊息
