#現在の出力値を取得 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): """シリアルポートをオープンする""" 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): """シリアルポートをクローズする""" if self.serial_conn and self.serial_conn.is_open: self.serial_conn.close() print("Connection closed.") def send_command(self, command): """コマンドを送信する""" if self.serial_conn and self.serial_conn.is_open: self.serial_conn.write(command.encode("utf-8")) time.sleep(0.1) # コマンド処理のため少し待機 response = self.serial_conn.readline().decode().strip() print(f"Response: {response}") return response else: print("Connection is not open.") return None def status(self): """電源のステータスを確認する""" command = "#1 STS\r\n" #ユニット番号は設定に合わせて変更してください。 self.send_command(command) print(f"コマンド{command}") def set_remote(self): """リモートモードに設定する""" command = "#1 REN\r\n" # リモートモードに設定 self.send_command(command) def set_local(self): """ローカルモードに設定する""" command = "#1 GTL\r\n" # ローカルモードに設定 self.send_command(command) def set_voltage(self, voltage): """電圧を設定する""" command = f"#1 VSET {voltage:.2f}\r\n" #電圧設定コマンド self.send_command(command) def set_current(self, current): """電流を設定する""" command = f"#1 ISET {current:.2f}\r\n" #電流設定コマンド self.send_command(command) def power_on(self): """電源をONにする""" command = "#1 SW1\r\n" self.send_command(command) def power_off(self): """電源をOFFにする""" command = "#1 SW0\r\n" self.send_command(command) def get_voltage(self): """現在の電圧値を取得する""" command = "#1 VGET\r\n" return self.send_command(command) def get_current(self): """現在の電流を取得する""" command = "#1 IGET\r\n" return self.send_command(command) # メインプログラム if __name__ == "__main__": # シリアルポートの設定 (ポート名は環境に合わせて変更してください) port_name = "COM3" # Windowsの場合 # port_name = "/dev/ttyUSB0" # Linux/Macの場合 # インスタンス作成とポートのオープン power_controller = PowerSupplyController(port=port_name) power_controller.open_connection() # リモートモードに設定 power_controller.set_remote() # 電圧と電流の設定 power_controller.set_voltage(5.0) # 5Vに設定 power_controller.set_current(1.0) # 1Aに設定 # 電源をONにする power_controller.power_on() time.sleep(5) # 5秒間ONの状態を維持 for i in range(5): voltage = power_controller.get_voltage() current = power_controller.get_current() print(f"{i + 1}秒目, Voltage: {voltage} V, Current: {current} A") time.sleep(1) #1秒間待機 # 電源をOFFにする power_controller.power_off() # ローカルモードに設定 power_controller.set_local() # 接続を閉じる power_controller.close_connection()