0

A 12v motor is connected to a 5v relay and a HC-SRO4 is connected to an Arduino. Sometimes the relay clicks so the motor is on for less than 170 seconds which is the delay time but sometimes the motor just keep on running but also there are times that it works properly so I am wondering if my Arduino or my relay is malfunctioning or there's something wrong with my code?

int echopin=10;
int trigpin=9;
int motorpin=8;
int sensorval; 
int delayt=170;
int greenpin=7;
int redpin=2;

void setup() {
  Serial.begin(9600);
  pinMode(echopin,INPUT);
  pinMode(trigpin,OUTPUT);
  pinMode(motorpin,OUTPUT);
  pinMode(redpin,OUTPUT);
  pinMode(greenpin,OUTPUT);
}

void loop() {


 digitalWrite(trigpin,LOW);
 delayMicroseconds(10);
 digitalWrite(trigpin,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigpin,LOW);
 delayMicroseconds(10);
 sensorval=pulseIn(echopin,HIGH);
 Serial.println(sensorval);

 if(sensorval<500){
 digitalWrite(motorpin,HIGH);
 digitalWrite(greenpin,HIGH);
 digitalWrite(redpin,LOW);
 delay(delayt);
 digitalWrite(motorpin,LOW);
 digitalWrite(greenpin,LOW);
 digitalWrite(redpin,HIGH);
 delay(1500);
 }
 digitalWrite(motorpin,LOW);
 digitalWrite(redpin,HIGH);
 digitalWrite(greenpin,LOW);
 
 if(sensorval>500){
 digitalWrite(greenpin,LOW);
  digitalWrite(redpin,HIGH);
  digitalWrite(motorpin,LOW);
 }
 
}
  • what is redpin and greenpin? .... why are you providing incomplete information? ... you said nothing about the values printed in serial monitor – jsotola Jul 11 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.