Hi all,
I'm trying to send a command to my sensor and get the response back, but I'm facing these problems:
i. The time elapsed between each received/saved data is not exactly 1 second
ii. The program stops printing/saving data after a few iterations, even though the code is still running
Here is the code I'm using:
I'm trying to send a command to my sensor and get the response back, but I'm facing these problems:
i. The time elapsed between each received/saved data is not exactly 1 second
ii. The program stops printing/saving data after a few iterations, even though the code is still running
Here is the code I'm using:
import serial import time import os # Create a directory with the desired name format folder_name = time.strftime("%H%M%S%d%m%y") os.makedirs(folder_name, exist_ok=True) # Establish serial connection ser = serial.Serial('COM3', 19200, parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) # Save column headers to the file file_path = os.path.join(folder_name, "data.txt") with open(file_path, "a") as file: file.write("date_time\telapsed_seconds\tO2_ppm\tO2_percent\n") start_time = time.time() try: while True: # Send MODBUS command to read O2 ppm ser.write(b':010400000004F7\r\n') response = ser.readline().decode().strip() print(response) o2_ppm = float(response[7:15]) / 100.0 # Adjust according to the format mentioned print(o2_ppm) o2_percent = o2_ppm / 10000 print(o2_percent) # Calculate elapsed seconds elapsed_seconds = time.time() - start_time # Get current timestamp timestamp = time.strftime("%Y-%m-%d %H:%M:%S") # Append data to the file with open(file_path, "a") as file: file.write(f"{timestamp}\t{elapsed_seconds:.2f}\t{o2_ppm:.2f}\t{o2_percent:.6f}\n") time.sleep(1) # Wait for 1 second except KeyboardInterrupt: pass finally: # Close the serial connection ser.close()Please give me some suggestions to rectify the issue. Thanks in advance.
Larz60+ write Aug-18-2023, 10:52 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Added tags for you this post, please use BBCode tags on future posts.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Added tags for you this post, please use BBCode tags on future posts.