Program hanging

I am trying to do a project which includes 2 Serial, Motor driving, LCD and using 3 Analog Reads and ultrasonic sensor. I am using AT mega168. But my code seems to hang frequently. What will be the problem?
Here is the code

#include <LiquidCrystal.h>
#include <NewSoftSerial.h>
LiquidCrystal lcd(8, 14, 9, 10, 11, 12);
NewSoftSerial gps(4,3);
int ledPin = 13;                  // LED test pin
int rxPin = 0;                    // RX PIN 
int txPin = 1;                    // TX TX

int echoPin1 = 15; 
int initPin1 = 13;

int byteGPS=-1;
char linea[300] = "";
char comandoGPR[7] = "$GPRMC";
int cont=0;
int bien=0;
int conta=0;
int indices[13];
char gsmloc[20],m=0;

int x;
int y;
int z;
int t;

unsigned long distance1 = 0; // variable for storing the distance (cm)

void setup() 
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(19,OUTPUT);

  pinMode(ledPin, OUTPUT);       // Initialize LED pin
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);

  pinMode(initPin1, OUTPUT); // set init pin 19 as output
  pinMode(echoPin1, INPUT); // set echo pin 15as input



  Serial.begin(9600);
  gps.begin(9600);
  for (int i=0;i<300;i++)
  {       // Initialize a buffer for received data
    linea[i]=' ';
  }

  lcd.begin(16, 2);
  Serial.begin(9600);
  lcd.setCursor(0, 0);
  lcd.print("Vehicle Accident");
  lcd.setCursor(2, 1);
  lcd.print("Alert System");
  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");
  lcd.setCursor(0, 1);
  lcd.print("Project 2011-12");
  delay(2000);
  lcd.clear();
  Serial.println("AT+CMGF=1"); 
  digitalWrite(5,LOW);
  digitalWrite(6,LOW); 
  digitalWrite(7,LOW);
  digitalWrite(19,LOW); 
}

void loop() 
{


  distance1=ultrasonic(initPin1,echoPin1);
  lcd.clear();
  lcd.setCursor(0, 0);// set the cursor to column 0, line 1
  lcd.print("Distance="); 
  lcd.print(distance1, DEC); 
  lcd.print("cm");
  delay(700);
  fwd();
  axischeck();
}
void fwd()
{
  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);
  digitalWrite(7,HIGH);
  digitalWrite(19,LOW);

}
/////////////////////To Read X,Y and Z axis values/////////// 

void axischeck()
{ 
  x=analogRead(2);
  y=analogRead(3);

  z=analogRead(4);

  axxo();
  lcd.setCursor(0,0);
  lcd.print("x=                  ");
  lcd.setCursor(3,0);
  lcd.print(x);
  lcd.setCursor(8,0);
  lcd.print(" y=           ");
  lcd.setCursor(12,0);
  lcd.print(y);
  lcd.setCursor(0,1);
  lcd.print("    z=       ");
  lcd.setCursor(8,1);
  lcd.print(z);
  lcd.print("        ");
  delay(500);
}


void axxo()
{

  if(x>460 || x<340 || y>460|| y<340 || z>550 || z<400)
  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("ACCIDENT LOC:");
    lcd.setCursor(4,1);
    lcd.print(gsmloc);
    gps.flush();
    Serial.flush();
    delay(1000);
    smsdeliver();
    lcd.clear();
  }
} 

///////GPS LOCATION READ//////////////////////
void gpsread()
{
  do
  {
    m=0;
    byteGPS=gps.read();         // Read a byte of the serial port
    if (byteGPS == -1) {           // See if the port is empty yet
      delay(100); 
    } 
    else {
      linea[conta]=byteGPS;        // If there is serial port data, it is put in the buffer
      conta++;                      
      Serial.print(byteGPS, BYTE); 
      if (byteGPS==13){            // If the received byte is = to 13, end of transmission
        cont=0;
        bien=0;
        for (int i=1;i<7;i++){     // Verifies if the received command starts with $GPR
          if (linea[i]==comandoGPR[i-1]){
            bien++;
          }
        }
        if(bien==6){               // If yes, continue and process the data
          for (int i=0;i<300;i++){
            if (linea[i]==','){    // check for the position of the  "," separator
              indices[cont]=i;
              cont++;
            }
            if (linea[i]=='*'){    // ... and the "*"
              indices[12]=i;
              cont++;
            }
          }
          Serial.println("");      // ... and write to the serial port
          Serial.println("");
          Serial.println("---------------");
          for (int i=2;i<3;i++){
            switch(i){
            case 0 :
              Serial.print("Time in UTC (HhMmSs): ");
              break;
            case 1 :
              Serial.print("Status (A=OK,V=KO): ");
              break;
            case 2 :
              Serial.print("Latitude: ");
              break;
            case 3 :
              Serial.print("Direction (N/S): ");
              break;
            case 4 :
              Serial.print("Longitude: ");
              break;
            case 5 :
              Serial.print("Direction (E/W): ");
              break;
            case 6 :
              Serial.print("Velocity in knots: ");
              break;
            case 7 :
              Serial.print("Heading in degrees: ");
              break;
            case 8 :
              Serial.print("Date UTC (DdMmAa): ");
              break;
            case 9 :
              Serial.print("Magnetic degrees: ");
              break;
            case 10 :
              Serial.print("(E/W): ");
              break;
            case 11 :
              Serial.print("Mode: ");
              break;
            case 12 :
              Serial.print("Checksum: ");
              break;
            }
            for (int j=indices[i];j<(indices[i+1]-1);j++){
              //Serial.print(linea[j+1]);
              gsmloc[m]=linea[j+1];
              //Serial.println("");
              Serial.print(gsmloc[m]); 
              m++;
            }
            Serial.println("");
          }
          Serial.println("---------------");
        }
        conta=0;                    // Reset the buffer
        for (int i=0;i<300;i++){    //  
          linea[i]=' ';             
        }                 
      }
    }
  }
  while(gps.available()>0);
}



//////////////////to check X,Y and Z axis///////////////////  

int x_read()
{
  return(analogRead(0));
}
int y_read()
{
  return(analogRead(1));
}
int z_read()
{
  return(analogRead(2));
}

////////////////to send sms///////////////////////////////

void smssend(char*no,char*msg1,char*msg2)
{
  Serial.println("AT+CMGF=1");
  delay(500);
  Serial.print("AT+CMGS=");               
  Serial.print(34,BYTE);
  Serial.print(no);             
  Serial.println(34,BYTE);                
  delay(1500); 
  Serial.print(msg1);
  Serial.print(msg2);     
  delay(500);
  Serial.print(0x1A,BYTE);   
  Serial.println("smssend");    
} 

////////////////NO's to send sms////////////////////////
void smsdeliver()
{
  smssend("........","ACCIDENT LOCATION IS ",gsmloc);
  //smssend(".......","GPS LOCATION IS ",gsmloc);
  //smssend(".......","GPS LOCATION IS ",gsmloc);
  //smssend("........","GPS LOCATION IS ",gsmloc);
}


unsigned long ultrasonic (int init, int echo)  {
  unsigned long pulseTime = 0; // stores the pulse in Micro Seconds
  unsigned long out = 0; // variable for storing the distance (cm)
  digitalWrite(init, HIGH); // send 10 microsecond pulse
  delayMicroseconds(6); // wait 10 microseconds before turning off (delay 6us + 4us for DW)
  digitalWrite(init, LOW); // stop sending the pulse 4us
  pulseTime = pulseIn(echo, HIGH); // Look for a return pulse, it should be high as the pulse goes low-high-low
  out = pulseTime/58; // Distance = pulse time / 58 to convert to cm.
  if(out < 500)  {
    return out;
  }
}

What may be the Reason? Is it the problem of memory?

Is it the problem of memory?

You have a lot of strings in your sketch, so quite possibly. Grab one of the freemem functions posted in the forums and see. If it is, consider using the F macro to move them to progmem.

What does you function "ultrasonic" return if "out" is >= 500?

But yes, get rid of the strings, they're wasting RAM

Why are you re-initalizing Serial.begin already defined above :

lcd.begin(16, 2);
  Serial.begin(9600);
  lcd.setCursor(0, 0);
  lcd.print("Vehicle Accident");
  lcd.setCursor(2, 1);

@AWOL
It is return the value only if its less than 500. if OUT is >500, its out of range.

@NI$HANT

Its my mistake. Will remove that line

It is return the value only if its less than 500. if OUT is >500, its out of range.

You've declared the function "ultrasonic" as returning an unsigned long.
What unsigned long value do you return if the value is >= 500?

Hope, I have to use 328!

unsigned long ultrasonic (int init, int echo) 
{
  unsigned long pulseTime = 0;
  unsigned long out = 0;
  digitalWrite(init, HIGH);
  delayMicroseconds(6);
  digitalWrite(init, LOW);
  pulseTime = pulseIn(echo, HIGH);
  out = pulseTime/58;
  if(out < 500)
  {
    return out;
  }
  else
  {
     // Don't return a damned thing
     // in clear violation of the intent
     // of the function to always return
     // a value
  }
}

Pay particular to the (implicit in your code; explicit in my rearranged version) else block. 8)

Hope, I have to use 328!

I have no idea what that means.

use 328 :-
I hope the problem can be solved by using At mega.

No, the compiler will still expect you to return a value if that is what you promised to do.

AWOL:
the compiler will still expect you to return a value ...

But there's no compiler on the hanging Arduino UNO running.
Do you mean that lazy compiler does not care and prefers to build crap code instead ?

But there's no compiler on the hanging Arduino UNO running.

True, but the one running on the host will issue a warning, lamentably suppressed by the IDE.

Do you mean that lazy compiler does not care and prefers to build crap code instead ?

True, but the one running on the host will issue a warning, lamentably suppressed by the IDE.

What happens is that there is space reserved on the call stack for a return value. That nothing is placed in that slot by the return function results in a warning ("Not all return paths return a value"), but it is not an error, since the caller may ignore the return value.

If the caller expects that there will always be a valid value returned, then it is an error for the function not to return one. A logic error, not a syntax or enforceable error.

In OPs case, the caller DOES expect that there WILL be a valid return value. Sometimes there is; sometimes the function returns crap. The caller can't tell that, so it happily displays the crap. Which, for some unexplained reason, OP seems to feel is either OK or outside his/her control.

What happens is that there is space reserved on the call stack for a return value. That nothing is placed in that slot by the return function results in a warning ("Not all return paths return a value"), but it is not an error, since the caller may ignore the return value.

I "know" C for more than half of my life, but did not really use it any more for quite a while since I met Arduino.
(In C# or Java " not all code paths return a value " is an error, of course, and nothing executable can be built)

I agree, as long as it does not destroy the call stack, it can be considered "programmer deserves subtle but fair punishment"

A similar issue: a definition like
byte b = 123456; 
can never do what the programmer intends, but is a suppressed warning as well.

However, it's obviously unrelated to OP's original problem, as writing beyond the defined limits of the lcd should not harm, or does it ?

However, it's obviously unrelated to OP's original problem, as writing beyond the defined limits of the lcd should not harm, or does it ?

No, but if one comes here and asks for help, the least the person can do is correct any errors that are pointed out.

Thnx for the replies . I will surely check the code with 'return' and reply soon

Hi

I completed my project after making suggested changes and also I used ATMega328.

Thanks for the replies.