Hello Ankit,
To achieve continuous reading and writing to two different serial ports, you can use multi-threading in Python. Below is a small code snippet using the threading module to handle this:
import threading
import serial
import time
# Initialize serial ports
dc_load_port = serial.Serial('COM1', baudrate=9600, timeout=1)
lmg500_port = serial.Serial('COM2', baudrate=9600, timeout=1)
def write_to_dc_load():
while True:
# Replace with your actual variable from the base workspace
current_variable = "your_current_variable"
dc_load_port.write(current_variable.encode())
time.sleep(1) # Adjust the delay as needed
def read_from_lmg500():
while True:
data = lmg500_port.readline().decode('utf-8').strip()
if data:
print(f"LMG500 Data: {data}")
time.sleep(1) # Adjust the delay as needed
# Create threads for reading and writing
write_thread = threading.Thread(target=write_to_dc_load)
read_thread = threading.Thread(target=read_from_lmg500)
# Start the threads
write_thread.start()
read_thread.start()
# Join the threads to the main thread
write_thread.join()
read_thread.join()
Explanation:
- Serial Port Initialization: Initialize the serial ports for the DC load and LMG500.
- Write Function: Continuously writes the current variable to the DC load.
- Read Function: Continuously reads data from the LMG500.
- Threads: Create and start separate threads for reading and writing operations.
- Joining Threads: Join the threads to the main thread to ensure they run concurrently.
Ensure you replace 'COM1' and 'COM2' with the actual COM port numbers for your serial devices. Adjust the time.sleep() delay as needed for your specific application.
This code should help you achieve continuous reading and writing to two different serial ports on a single system.
hope it helps