python - Python写两次但随机?
问题描述
所以我目前正在开发一个从以前的同事那里传给我的程序,我正在解决一个奇怪的错误。当从 2 个单独的串行源逐字节读取数据输出时,python 将写入 .csv 文件以及控制台中的同一单元格。
import serial
from datetime import datetime
import os
pressure_passed = False
arduino_passed = False
file_passed = False
BAUD_RATE = 115200
GARBAGE_CYCLES = 3 # how many cycles to ignore before logging data
garbage_cycle = 0
# Save data to log file
def LogData(startTime, pressureData, arduinoData, file):
global garbage_cycle
if garbage_cycle < GARBAGE_CYCLES:
garbage_cycle += 1
else:
delta = datetime.now() - startTime
ms = delta.total_seconds() * 1000
dataString = "{:0.2f}, {}, {}\n".format(ms, pressureData, arduinoData)
file.write(dataString)
file.flush()
print(dataString, end = "")
# Get the COM port for the Mark-10 Series 5
while not pressure_passed:
try:
pressure_com = input("Enter Mark-10 Series 5 COM Port #: ")
pressure_ser = serial.Serial("COM" + str(pressure_com), BAUD_RATE)
pressure_passed = True
except:
print("Invalid COM Port, please enter a valid port.\n-----")
# Get the COM port for the Arduino
while not arduino_passed:
try:
arduino_com = input("Enter Ardunio COM Port #: ")
arduino_ser = serial.Serial("COM" + str(arduino_com), BAUD_RATE)
arduino_passed = True
except:
print("Invalid COM Port, please enter a valid port.\n-----")
# Get the name for the log file
while not file_passed:
try:
file_name = input("Enter log file name: ")
# Add extension if not already given
if "." not in file_name:
file_name += ".csv"
log_file = open(file_name, "a")
# Add header row to log file
if os.stat(log_file.name).st_size == 0:
log_file.write("time (ms), pressure, rate (deg/ms)")
file_passed = True
except:
print("Invalid file, or could not open the file specified.\n-----")
start = datetime.now()
# Variables to read serial input
pressure_data = ""
last_pressure = ""
arduino_data = ""
last_arduino = ""
# Main program loop
# Serial is read from byte by byte to better sync the two devices
while True:
try:
x_changed = False
y_changed = False
# Read from Mark-10 serial if available
# x is a byte read from the serial line, converted to ascii
if pressure_ser.in_waiting > 0:
x = pressure_ser.read().decode('ascii')
x_changed = True
# Read from Arduino serial if available
# y is a byte read from the serial line, converted to ascii
if arduino_ser.in_waiting > 0:
y = arduino_ser.read().decode('ascii')
y_changed = True
# If new data received, check if we should log it
if x_changed:
if x == '\n': # New line detected, log the accumulated data
if last_pressure != pressure_data:
LogData(start, last_pressure, last_arduino, log_file)
last_pressure = pressure_data
pressure_data = ""
elif x != '\r': # Otherwise, add the read character to the string
pressure_data += x
if y_changed:
if y == '\n': # New line detected, log the accumulated data
if last_arduino != arduino_data:
LogData(start, last_pressure, last_arduino, log_file)
last_arduino = arduino_data
arduino_data = ""
elif y != '\r': # Otherwise, add the read character to the string
arduino_data += y
except Exception as e:
print(e)
if arduino_ser.isOpen():
arduino_ser.close()
if pressure_ser.isOpen():
pressure_ser.close()
log_file.close()
break
这是文件吐出的内容,即双重打印到单个单元格。数据样本
任何建议都非常感谢,谢谢大家!
解决方案
我喜欢你的用户名!我的猜测是,在 arduino 有时间更改in_waiting
.
在代码顶部添加:
import time
并在LogData
函数中添加:
time.sleep(0.1)
试一试,如果有帮助,请告诉我。0.1s 对您的应用程序来说可能太长了,但这是一个很好的测试,看看这是否是问题所在。如果是这样,您可以玩弄它的睡眠时间。
推荐阅读
- jasmine - 如何在量角器的同一个 chrome 浏览器上并行运行多个规范文件
- xcode9 - XCode 项目突然因“缺少必需的模块”CgRPC“而失败
- scikit-learn - OneVsRestClassifier中的多个类的Classifier的参数可以不同吗
- python-2.7 - 如何为单元测试类创建超时包装器
- vba - 使用 VBA 从 Excel 加载 Powerpoint 数组
- python - 无法在 Windows 10 上的 PowerShell 中的 virtualenv 上运行 python
- sql - 如何根据条件在 SQL 中创建行?
- python - 计算下面的空值数量并将它们放在新的df中
- c++ - 什么是 R"===(?
- python - 使用 TFLite 转换 LSTM 图形失败