Mega 2560 changes its IP address

I set the IP address and variables for the Ethernet shield (W5500) and everything starts out fine. I can't post the full code because of job stuff, but will try to post the relevant portions.

// Global
byte mac[] = { 0x4A, 0x62, 0x41, 0x4C, 0x49, 0x4E };
IPAddress ip{ 192, 168, 2, 8 }; 
int TCP_Client_Port = 10001; 
EthernetClient ethClient;
IPAddress server{ 192, 168, 2, 1 };  

// Called in setup()
Ethernet.begin(mac, ip);

Run the code, I connect over TCP to an Allen Bradley PLC. The PLC sends a command to begin writing to a LIN module connected to Serial1. After that, the Arduino disconnects and checking Serial.println(Ethernet.localIP()); give me an IP of 192.0.0.168. What's stranger is that if I run that command during the function where the LINbus commands take place, I get 254.0.148.196 and then the IP address is correct after returning to the main loop().

      for (int Y = 1; Y <= LINwrites; Y++) {
        buf[0] = (InBuffer[47]);
        buf[1] = (InBuffer[48]);
        buf[2] = (InBuffer[49]);
        buf[3] = (InBuffer[50]);
        buf[4] = (InBuffer[51]);
        buf[5] = (InBuffer[52]);
        buf[6] = (InBuffer[53]);
        buf[7] = (InBuffer[54]);
        addr = (InBuffer[56]);
        LINbus();
        delay(LIN_Time_Between_writes);
      }
      Serial.println(Ethernet.localIP());
    }

Am I writing into the array that contains the IP address and mucking things up? I've been trying to limit String, and have about 6 of them in the code. If I am goofing up the array, why would requesting the current IP address before leaving the routine make it fix itself?

Compiled memory is:
Sketch uses 35682 bytes (14%) of program storage space. Maximum is 253952 bytes.
Global variables use 2754 bytes (33%) of dynamic memory, leaving 5438 bytes for local variables. Maximum is 8192 bytes.

Edit: and all Serial print commands that are text are done as Serial.print(F("Status text");

Thanks for any help.

Generally speaking, the ip beginning with 192 is a valid network address. Addresses beginning with 254 are not. The 254 address sounds like you might be receiving the subnet and not the IP. Either that or the IP is in a renewing state, and you’re receiving the multicast address for the segment.

I had a similar thought but what I don't understand is that if I don't request the IP address inside the void loop, once the code returns to Loop() the IP address is wrong and I lose communications. That's when the IP address goes to 192.0.0.8. It's like the middle two octets get erased. But if I request the IP address inside the LINbus function, it returns the garbage address and then the IP is fine coming back into Loop(). If I ask for the IP address multiple times in Loop() it will stay the incorrect 192.0.0.8 address.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.