Relay problems G5V-1 using ultrasonic Distance Sensor

Your schematic is connecting the base of the transistor to pin 5 (not 8) but that aside are you powering all this from the 5v on the Arduino board? Try removing the relay and just using an LED - does that 'chatter' or stay lit / unlit as expected?

If it works then I suspect one of the following:

  • that the relay coil is demanding too much current, so that the Arduino is struggling or resetting
  • the relay is noisy (despite your diode protection) and causes the Arduino to reset

I would certainly put a 1k resistor in line with the base of the transistor, you are overloading it (it won't solve your issue but you could end up with a defunct transistor).

If you then supply that resistor (connected to the base of the transistor) with 5 volts does the relay latch as expected?

Try powering the relay from a separate supply (not connected in any way to the Arduino except for the ground line).

What do you intend to drive from the relay? As long as it's low level voltage stuff then fine. Otherwise I would highly recommend an optically isolated relay like the one I show in my video #18, much safer for you and your Arduino!