@@ -53,32 +53,39 @@ void setup() {
5353
5454 // you're connected now, so print out the status:
5555 printWifiStatus ();
56-
57- // start the Modbus RTU client
58- if (!modbusTCPClient.begin (server)) {
59- Serial.println (" Failed to start Modbus TCP Client!" );
60- while (1 );
61- }
6256}
6357
6458void loop () {
65- // write the value of 0x01, to the coil at address 0x00
66- if (!modbusTCPClient.writeCoil (0x00 , 0x01 )) {
67- Serial.print (" Failed to write coil! " );
68- Serial.println (modbusTCPClient.lastError ());
69- }
70-
71- // wait for 1 second
72- delay (1000 );
73-
74- // write the value of 0x00, to the coil at address 0x00
75- if (!modbusTCPClient.writeCoil (0x00 , 0x00 )) {
76- Serial.print (" Failed to write coil! " );
77- Serial.println (modbusTCPClient.lastError ());
59+ if (!modbusTCPClient.connected ()) {
60+ // client not connected, start the Modbus TCP client
61+ Serial.println (" Attempting to connect to Modbus TCP server" );
62+
63+ if (!modbusTCPClient.begin (server, 8502 )) {
64+ Serial.println (" Modbus TCP Client failed to connect!" );
65+ } else {
66+ Serial.println (" Modbus TCP Client connected" );
67+ }
68+ } else {
69+ // client connected
70+
71+ // write the value of 0x01, to the coil at address 0x00
72+ if (!modbusTCPClient.writeCoil (0x00 , 0x01 )) {
73+ Serial.print (" Failed to write coil! " );
74+ Serial.println (modbusTCPClient.lastError ());
75+ }
76+
77+ // wait for 1 second
78+ delay (1000 );
79+
80+ // write the value of 0x00, to the coil at address 0x00
81+ if (!modbusTCPClient.writeCoil (0x00 , 0x00 )) {
82+ Serial.print (" Failed to write coil! " );
83+ Serial.println (modbusTCPClient.lastError ());
84+ }
85+
86+ // wait for 1 second
87+ delay (1000 );
7888 }
79-
80- // wait for 1 second
81- delay (1000 );
8289}
8390
8491void printWifiStatus () {
0 commit comments