0

Here's my code after editing the measurement had error. Now the ultrasonic measurement is working but the vibration motor is not vibrating.

#define trigPin1 8
#define echoPin1 7
#define motorPin1 13

long duration, distance, UltraSensor;

void setup()
{ 
  Serial.begin(9600); // to use the serial monitor.
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  //pinMode(motorPin1, OUTPUT);

}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  delay(100);
}

void loop()
{ 
  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;
  Serial.print(distance); // print out the distance on Serial Monitor
  Serial.println("cm");
//
  if (distance <= 60 && distance >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  } 
  else if(distance < 45 && distance >=30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  } 
  else if(distance < 30) 
  {
   digitalWrite(motorPin1, HIGH);
   delay(50);
   digitalWrite(motorPin1, LOW);
   delay(50); 
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }
}
  • 1
    Cut out everything from your sketch except the distance measuring. Forget the rest for now. Get the distance measuring working first. – Majenko Feb 26 '18 at 16:14
  • And while you are at it, disconnect the motor and post a picture clearly showing how you have the ultrasonic sensor wired to the arduino. – Chris Stratton Feb 26 '18 at 16:34
  • After i cut out everything except the distance measuring part also not working. You can check below. Sorry for inconvenience – Htoo Feb 26 '18 at 17:10
  • do not put updates into comments ... update the original question ... there is an edit button for doing that ... while you are at it, change the title of your question to Arduino not measuring distance correctly, because that is the problem, it is not a motor problem. – jsotola Feb 26 '18 at 18:43
  • I already edited my code and now the measurement is working but the motor is not vibrating. Any help ? – Htoo Feb 27 '18 at 6:14
0

I think you have to uncomment the line that defines the motor as an output device.

//pinMode(motorPin1, OUTPUT);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.