我正在运行一个使用pyserial
包的python脚本。我使用一块板来控制电机的旋转,并通过USB接口连接。
该板已编程,并可旋转的电机与给定的命令。以下是一些例子:
产出:
{
.."beambreak": [0,0,0,0,0],
.."prox": [0.003,0.003],
.."T1": [0,0],
.."T2": [0,0],
.."MT": [-1,-1]
.."test_switch": 0,
.}
输出:{“旋转”:“成功”}
任务:在‘while’循环中,如何每1分钟发送一次命令(例如,H010101),检查输出消息(例如,{“旋转”:“成功”}),并根据输出消息条件发送下一个命令。
问题:当我运行代码时,"can set“输出消息出现在linux终端/IDE控制台中,但我不知道如何将消息保存为变量并在循环条件下应用。我的意思是,要检查消息是否是同一条消息,请等待1分钟,然后再次发送H010101命令?
我还尝试在*.log或*.txt保存文件,但没有使用示例:
$ python test.py >> *.txt
$ python test.py > *.log
这是我的代码:
import time
import serial
# configure the serial connections
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
while True :
print(' Check Status')
ser.write('H010000\n'.encode())
status_cmd = ser.readline()
print(status_cmd)
if status_cmd === "test_switch: 0 " : # i can't save the message as variable from running terminal
time.sleep(5)
# Command to rotate motor
ser.write('H010101\n'.encode())
# read respond of give command
reading = ser.readline()
print(reading)
if reading == {"Drop":"Successful"} : # i can't save the message as variable from running terminal
time.sleep(60)
# rotate motor
ser.write('H010101\n'.encode())
# read respond of give command
reading = ser.readline()
print(reading)
发布于 2022-04-12 10:40:38
您可以做的第一件事是将您的函数封装到方法中(如果您愿意,也可以使用类)。
检查状态
def check_status(ser):
print('Check Status')
ser.write('H010000\n'.encode())
current_status = ser.readline().decode('utf-8')
return current_status
旋转电机
def rotate_motor(ser):
print('Rotating ..')
ser.write('H010101\n'.encode())
rotation_status = ser.readline().decode('utf-8')
return rotation_status
您还需要导入json作为dict加载响应。
e.g
>>> import json
>>> rotation_status='{"Drop":"Successful"}'
>>> json.loads(rotation_status)
{'Drop': 'Successful'}
现在您已经准备好了这些代码片段,您可以根据结果调用它们来连续运行操作。
while True:
status = json.loads(check_status(ser))
if status['test_switch'] == 0:
time.sleep(5)
is_rotated = json.loads(rotate_motor(ser))
if is_rotated['Drop'] == 'Successful':
time.sleep(60)
else:
print('Something went wrong')
raise Exception(is_rotated)
https://unix.stackexchange.com/questions/698828
复制相似问题