#Set voltage and current, and control output ON/OFF import serial import time class PowerSupplyController: def __init__(self, port , baudrate=9600, timeout=1): self.port = port self.baudrate = baudrate self.timeout = timeout self.serial_conn = None def open_connection(self): """Open the serial port""" self.serial_conn = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout) print(f"Connected to {self.port} at {self.baudrate} baudrate.") def close_connection(self): """Close the serial port""" if self.serial_conn and self.serial_conn.is_open: self.serial_conn.close() print("Connection closed.") def send_command(self, command): """Send a command""" if self.serial_conn and self.serial_conn.is_open: self.serial_conn.write(command.encode("utf-8")) time.sleep(0.1) # Wait briefly for command processing response = self.serial_conn.readline().decode().strip() print(f"Response: {response}") return response else: print("Connection is not open.") return None def status(self): """Check the power status""" command = "#1 STS\r\n" #Change the unit number according to the settings. self.send_command(command) print(f"Command{command}") def set_remote(self): """Set to remote mode""" command = "#1 REN\r\n" # Set to remote mode self.send_command(command) def set_local(self): """Set to local mode""" command = "#1 GTL\r\n" # Set to local mode self.send_command(command) def set_voltage(self, voltage): """Set voltage""" command = f"#1 VSET {voltage:.2f}\r\n" #Voltage setting command self.send_command(command) def set_current(self, current): """Set current""" command = f"#1 ISET {current:.2f}\r\n" #Current setting command self.send_command(command) def power_on(self): """Turn power ON""" command = "#1 SW1\r\n" self.send_command(command) def power_off(self): """Turn power OFF""" command = "#1 SW0\r\n" self.send_command(command) # Main program if __name__ == "__main__": # Serial port settings (Change the port name according to the environment) port_name = "COM3" # For Windows # port_name = "/dev/ttyUSB0" # For Linux/Mac # Create an instance and open the port power_controller = PowerSupplyController(port=port_name) power_controller.open_connection() # Set to remote mode power_controller.set_remote() # Set voltage and current power_controller.set_voltage(5.0) # Set to 5V power_controller.set_current(1.0) # Set to 1A # Turn power ON power_controller.power_on() time.sleep(5) # Keep ON state for 5 seconds # Turn power OFF power_controller.power_off() # Set to local mode power_controller.set_local() # Close the connection power_controller.close_connection()