Arduino mega freeze

Hi guys!

I have an arduino mega and an arduino ethernet shield.

I have a basic udp server:

void webServerListener() {
  int packetSize = Udp.parsePacket();
  
  if(packetSize)
  {
    digitalWrite(12, HIGH);

    IPAddress remote = Udp.remoteIP();


    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
    String command = String(packetBuffer[0]);
    
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    if (command == "0") {
      // live
      Udp.print(getCurrentPosition());
      Udp.print(";");
      Udp.print(getWaterPressure());
      Udp.print(";");
      Udp.print(getRPM());
      
    }
    
    Udp.endPacket();
    digitalWrite(12, LOW);
    
    
  }
  delay(10);
  
}

the functions getCurrentPosition, getWaterPressure, getRPM are just reading analog pins like:

int val = analogRead(4);return val;

It works until a while, but then freezes. Sometimes it is good for a day, sometime it is good only for one hour?
I have tested that I do not connect to the analog pins anything, to be sure it does not get more than 5 V.

I am sure it freezes in this function because I turn on a led with digitalWrite(12, HIGH) at the beginning of the function and turn off at the end. And when it freezes the led stays on...

What can be a problem? The memory get full? But why? Or the analog read is broken?

Thanks.
szotyi

I had a problem like that when using TCP and UDP. It ended up being the microSD card interface on the ethernet shield. Maybe your challenge is the same?

void setup()
{
   Serial.begin(9600);

   // sprinkle a little magic pixie dust (disable SD SPI)
   pinMode(4,OUTPUT);
   digitalWrite(4,HIGH);

   Ethernet.begin(mac,ip);

   // rest of your setup
}

The easiest way is to find the closest spot to the problem.
I would first set-up the code to verbosely output messages to the PC in every critical step/function. Then when it crashes you can see the last outputted message.

Or maybe find the Freemem code on the forum and periodically verify your free ram.
Or remove layers of your code until the error disappears, then you know where the bug is.
Or maybe it is the SD card error pointed by SurferTim.

Post all your code and someone may see the problem, are you using dynamic memory at all?

Hey!

Thank you very much the answers.

I have added the code for pin 4 and I have changed the ip and port, and now it is working!

Thanks again!!!!