So I have the base of a BC547 connected to pin 8 and I have a relay with a diode running parallel with the coil using the G5V-1 5V relay. I'm powering one side with 5V and the other side is connected to the collector of the BC547 and the emitter is connected to ground. I'm using a ultrasonic sensor that I want to tell if something gets within 3 inches of it to turn on the relay. However the relay chatters. SO I put a pause and tried again however this time the relay won't engage at all. I'm posting the code as well as the schematic and was hoping someone could help me understand why the relay won't latch. I've used dozen relays and none latch. I can short it with a 5V signal and it will latch fine however using the Arduino Nano to turn this relay on has proven to be troublesome. Any help would be greatly appreciated. Thanks.
Code:
[
#define trigPin 12
#define echoPin 13
int Relay = 8; // Connect Relay pin to 8
int ledPin= 6; //Connect LEd pin to 6
int duration, distance; //to measure the distance and time taken
void setup() {
Serial.begin (9600);
//Define the output and input objects(devices)
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(Relay, OUTPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW); //Blink once
delay(500);
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW); // Blink Twice
delay(500);
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW); // Blink thrice
delay(500);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//when distance is greater than or equal to 200 OR less than or equal to 0,the buzzer and LED are off
if (distance >= 10 || distance <= 0)
{
Serial.println("no object detected");
digitalWrite(Relay,LOW);
digitalWrite(ledPin,LOW);
}
else {
Serial.println("object detected \n");
Serial.print("distance= ");
Serial.print(distance);
digitalWrite(ledPin,HIGH);
digitalWrite(Relay, HIGH);
}
}
]
