作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 arduino 和 rpi build 一艘 GPS 引导的遥控船。 arduino 发送串行数据,然后使用此文件对其进行解释:
import serial
with serial.Serial('/dev/ttyAMA0', 115200, timeout=1) as ser:
while True:
line = ser.readline()
max_char = len(line)
a = 3
# read a '\n' terminated line
if len(line) > 0:
if chr(line[0]) == '~':
key = int(chr(line[1]))
if key == 1:
lat = line[a:max_char-2]
print("lat:")
print(lat.decode('utf-8'))
if key == 2:
lng = line[a:max_char-2]
print("lng:")
print(lng.decode('utf-8'))
if key == 3:
alt = line[a:max_char-2]
print("alt:")
print(alt.decode('utf-8'))
if key == 4:
sat = line[a:max_char-2]
print("sat:")
print(sat.decode('utf-8'))
if key == 5:
crs = line[a:max_char-2]
print("Crs:")
print(crs.decode('utf-8'))
else:
print("oops:")
然后我希望另一个 python 脚本能够访问变量 crs、lat、lng 等。但是,当我尝试在另一个 python 脚本中使用以下行时,它运行了整个函数。
from serial2rpi import *
print(crs)
print(lat)
# etc.
我不能合并脚本的原因是 GPS 需要大约半秒的时间来刷新。获取变量的主脚本正在进行计算并更新伺服速度 Controller 的位置。
任何帮助将不胜感激。
最佳答案
您需要向代码中添加线程和锁。我希望这个方法有效:
文件:serial2rpi.py
import serial
import threading
lat = None
lng = None
alt = None
sat = None
crs = None
info_lock = threading.Lock()
def serialReaderThread():
with serial.Serial('/dev/ttyAMA0', 115200, timeout=1) as ser:
while True:
line = ser.readline()
max_char = len(line)
a = 3
# read a '\n' terminated line
if len(line) > 0:
if chr(line[0]) == '~':
key = int(chr(line[1]))
if key == 1:
info_lock.acquire()
lat = line[a:max_char - 2]
print("lat:")
print(lat.decode('utf-8'))
info_lock.release()
if key == 2:
info_lock.acquire()
lng = line[a:max_char - 2]
print("lng:")
print(lng.decode('utf-8'))
info_lock.release()
if key == 3:
info_lock.acquire()
alt = line[a:max_char - 2]
print("alt:")
print(alt.decode('utf-8'))
info_lock.release()
if key == 4:
info_lock.acquire()
sat = line[a:max_char - 2]
print("sat:")
print(sat.decode('utf-8'))
info_lock.release()
if key == 5:
info_lock.acquire()
crs = line[a:max_char - 2]
print("Crs:")
print(crs.decode('utf-8'))
info_lock.release()
else:
print("oops:")
文件:Other.py
from serial2rpi import *
# Run this line whenever you want to start reading the serial's input
threading.Thread(target=serialReaderThread).start()
# Acquire the lock whenever you want to read or write in your code
info_lock.acquire()
print(crs)
print(lat)
info_lock.release()
# etc.
关于python - 如何在两个python脚本之间共享变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096562/
我是一名优秀的程序员,十分优秀!