SNAP7: write_NI_choice2.py

File write_NI_choice2.py, 1.6 KB (added by krit, 3 weeks ago)
Line 
1#!/usr/bin/env python3
2
3import pylibmodbus
4import sys
5
6# Siemens LOGO! 8 Modbus TCP Configuration
7PLC_IP = "192.168.1.103"  # Change this to your LOGO! 8 IP
8PLC_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
14NI1_REGISTER = int(sys.argv[1])
15WRITE_VALUE =  int(sys.argv[2])
16
17if (WRITE_VALUE == 1):
18    WRITE_VALUE = 0x0F
19
20
21
22def 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
55if __name__ == "__main__":
56    main()
57