Code stops after some time using delay

Have you tried serial printing the range number to see if you are really getting what you intend?
Paul