1 | #!/usr/bin/env python3 |
---|
2 | |
---|
3 | import pylibmodbus |
---|
4 | import sys |
---|
5 | |
---|
6 | # Siemens LOGO! 8 Modbus TCP Configuration |
---|
7 | PLC_IP = "192.168.1.103" # Change this to your LOGO! 8 IP |
---|
8 | PLC_PORT = 502 # Default Modbus TCP Port |
---|
9 | |
---|
10 | # NI Register Address |
---|
11 | #NI1_REGISTER = 0 # NI1 is stored in Register 0 |
---|
12 | #WRITE_VALUE = 0x0F # Value to write to NI1 |
---|
13 | |
---|
14 | NI1_REGISTER = int(sys.argv[1]) |
---|
15 | WRITE_VALUE = int(sys.argv[2]) |
---|
16 | |
---|
17 | if (WRITE_VALUE == 1): |
---|
18 | WRITE_VALUE = 0x0F |
---|
19 | |
---|
20 | |
---|
21 | |
---|
22 | def main(): |
---|
23 | """Write to NI1 and verify the result.""" |
---|
24 | modbus = pylibmodbus.ModbusTcp(PLC_IP, PLC_PORT) |
---|
25 | |
---|
26 | try: |
---|
27 | if modbus.connect() == -1: |
---|
28 | print("❌ Failed to connect to Siemens LOGO! 8 PLC") |
---|
29 | return |
---|
30 | |
---|
31 | print("✅ Connected to Siemens LOGO! 8 PLC") |
---|
32 | |
---|
33 | # Write 0 to NI1 (Register 0) |
---|
34 | cmd_status = modbus.write_register(NI1_REGISTER, WRITE_VALUE) |
---|
35 | print(f"command status = {cmd_status}") |
---|
36 | if (cmd_status == None): |
---|
37 | print(f"✅ Successfully wrote {WRITE_VALUE} to NI1 (Register {NI1_REGISTER})") |
---|
38 | else: |
---|
39 | print(f"❌ Failed to write to NI1 (Register {NI1_REGISTER})") |
---|
40 | |
---|
41 | # Read back NI1 to confirm the write operation |
---|
42 | ni_value = modbus.read_registers(NI1_REGISTER, 1) |
---|
43 | if ni_value is not None: |
---|
44 | print(f"📖 NI1 (Register {NI1_REGISTER}) After Write = {ni_value[0]}") |
---|
45 | else: |
---|
46 | print("❌ Failed to verify NI1 value") |
---|
47 | |
---|
48 | except Exception as e: |
---|
49 | print(f"❌ Exception: {e}") |
---|
50 | |
---|
51 | finally: |
---|
52 | modbus.close() |
---|
53 | print("🔌 Disconnected from Siemens LOGO! 8 PLC") |
---|
54 | |
---|
55 | if __name__ == "__main__": |
---|
56 | main() |
---|
57 | |
---|