ultrasonic sensor arduino distance unstable

i use ultrasonic sensor arduino and atmega328p ,when i upload the arduino example ping code , the result will be normal,stable.but when i write my c code in atmel studio upload it, everything is fine except the distance stable,like this: 968,968...968, 138,968.....968,138. i don't know how it come out ? i just know after i send a pulse message and wait for the echo, the power will be low,high,low(for the distance 968) , i think the situation 138 is just high low, could anyone tell me why? thank you!

if someone need the code , i will upload it .

Are you using the Arduino pulseIn() function in Atmel Studio?

yes i rewrite the code by myself.

int getPulseWidth(int pingID) {
    int timecount = 0;
    int val = 0 ;
    if(pingID == 7) {
        val = PIND>>pingID; // Append signal value to val
      
        while(val ==0) { // Loop until pin reads a high value

            val = PIND>>pingID;
    //      USART_putint(val);
        }


        while(val == 1)
        {
    //      USART_send('b');
          val = PIND>>pingID;
        //  USART_putint(val);
         ++timecount;  // Count echo pulse time
        }
}

pulseIn() returns an unsigned long. Perhaps you are overflowing your 16-bit integer.

Do you not care what the actual time is? It looks like your pulse width is returned in arbitrary units.

johnwasser: pulseIn() returns an unsigned long. Perhaps you are overflowing your 16-bit integer.

Do you not care what the actual time is? It looks like your pulse width is returned in arbitrary units.

I think so. That might be the reason.

because i want detect the number of people who come through the door, so i don't need the accurate distance , i just set a distance , when someone come in or out the data will be small than the distance what i set. i'm sorry i forget to show all of the program , it should return timecount .