This is completely different code, and not as well written as the first code. I still don't see anything wrong with the first code you posted.
So I suspect both codes are working as they should, but somehow the original code did not work as you expected and I'm not sure what that was. I think adjusting the sensitivity fixed the problem, not changing the code.
I don't know either, because I did not change the sensitivity adjustment of the sensor, maybe the first code that I used is just not suitable for the sensor that i am using, or there might be another reason why.
There is nothing wrong or unsuitable about the original code. It's just that it didn't work the way you were expecting, but you didn't describe in what way.
I can see that the second code does something a little different, and presumably this is closer to what you expected. I can see that it doesn't print "Motion ended." until the digital input is low and a 3 second pause has elapsed. During that time, if the digital input goes HIGH again, the message is not printed and the timeout period starts over.
So the original code is closely and accurately reflecting the changes in the signal from the sensor. The second code is doing a little more "processing" of the signal, for example sometimes ignoring changes in the signal, or not reporting those changes until a timeout has completed.
Can you describe how you feel the original code is not doing what you expected, and how that is different from what the second code is doing?
Oh it is just that on the original code, the sensor keeps on saying motion detected on the serial monitor even if there is no motion. But in the second code, the sensor will only say motion detected when it really detects something and it says motion ended when there is already no motion.
Odd. You have re-tested the original code, now that you have adjusted the sensitivity? If so, it shouldn't/won't do that. Unless there is another problem with the circuit.
It's disappointing that we were unable to diagnose the problem and fix it. You would have learned more. Now, you might encounter the same problem again, maybe not realising it's the same problem, and have to ask the forum for help again.
To prevent this from becoming a never-ending cycle, next time you ask the forum for help, please read the forum guide first and follow it fully, posting all the code, links, schematic, photos that will be needed to help get to the bottom of the problem.
But actually my main guess here is the coding itself, there might be nothing wrong in the code but its compatibility with the sensors and arduino since thing only went back to normal when i used another code.