|
我們用多線程寫了這些code ,a() b() c() 函式可以執行,但是d()(tcp)卻沒有運作
可是我們單獨執行d() 卻可以成功傳送資料
不知是何處出了問題
import socket
import sys
import RPi.GPIO as GPIO
import serial,time
import threading
ser=serial.Serial('/dev/ttyACM1',9600,timeout=0.25)
ser2=serial.Serial('/dev/ttyACM0',9600,timeout=0.25)
turn=17
motor=19
speedchange=21
no=24
GPIO.setmode(GPIO.BCM)
GPIO.setup(turn,GPIO.OUT)
GPIO.setup(motor,GPIO.OUT)
GPIO.setup(speedchange,GPIO.OUT)
GPIO.setup(no,GPIO.OUT)
pwm=GPIO.PWM(motor,55)
pwm1=GPIO.PWM(turn,55)
def a():
global decode2
global decode3
while True:
try:
response=ser.readline()
if response[0]==ord('b'):
print('b')
decode2=int(response[1:].decode("utf-8"))
print(decode2)
if response[0]==ord('c'):
print('c')
decode3=int(response[1:].decode("utf-8"))
print(decode3)
except:
a()
def b():
global decode4
global decode5
global decode6
global decode7
while True:
try:
response2=ser2.readline()
if response2[0]==ord('d'):
print('d')
decode4=int(response2[1:].decode("utf-8"))
print(decode4)
if response2[0]==ord('e'):
print('e')
decode5=int(response2[1:].decode("utf-8"))
print(decode5)
if response2[0]==ord('f'):
print('f')
decode6=int(response2[1:].decode("utf-8"))
print(decode6)
if response2[0]==ord('g'):
print('g')
decode7=int(response2[1:].decode("utf-8"))
print(decode7)
except:
b()
def c():
while True:
if decode2 > 50 and decode3 > 7 : #前進後退
pwm.start(8.5)
if 10 > (decode4 - decode5) > 5 : #左右微調
pwm1.start(7.7)
count=7.7
while count>5:
count=count-0.01
time.sleep(0.001)
duty=float(count)
pwm1.ChangeDutyCycle(duty)
if -10 < (decode4 - decode5) < -5 :
pwm1.start(7.7)
count=7.7
while count<10:
count=count+0.01
time.sleep(0.001)
duty=float(count)
pwm1.ChangeDutyCycle(duty)
if (decode4 - decode5) > 10 : #左轉
pwm1.start(7.7)
count=7.7
while count>5:
count=count-0.2
time.sleep(0.001)
duty=float(count)
pwm1.ChangeDutyCycle(duty)
if (decode6 - decode7) > 10 : #右轉
pwm1.start(7.7)
count=7.7
while count>12:
count=count+1
time.sleep(0.001)
duty=float(count)
pwm1.ChangeDutyCycle(duty)
if decode2 < 50 :
pwm.start(7.2)
if decode3 < 5 and decode2 > 50 :
pwm1.start(12)
pwm.start(7)
def d():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
well_known_port = 8881
sock.bind(('192.168.0.106', well_known_port))
sock.listen(10)
newSocket, address = sock.accept( )
print("connection success")
while True:
response=ser.readline()
response2=ser2.readline()
if not response.strip():
continue
if not response2.strip():
continue
sensor1=str(response.decode("utf-8"))
aaa=str(len(sensor1))+sensor1
newSocket.send(aaa.encode("utf-8"))
sensor2=str(response2.decode("utf-8"))
bbb=str(len(sensor2))+sensor2
newSocket.send(bbb.encode("utf-8"))
time.sleep(0.25)
def main():
threading.Thread(target=d).start()
threading.Thread(target=a).start()
threading.Thread(target=b).start()
time.sleep(1)
threading.Thread(target=c).start()
main()
|
|