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);
 }
}
asked Feb 26, 2018 at 16:07
5
  • 1
    Cut out everything from your sketch except the distance measuring. Forget the rest for now. Get the distance measuring working first. Commented Feb 26, 2018 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. Commented Feb 26, 2018 at 16:34
  • After i cut out everything except the distance measuring part also not working. You can check below. Sorry for inconvenience Commented Feb 26, 2018 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. Commented Feb 26, 2018 at 18:43
  • I already edited my code and now the measurement is working but the motor is not vibrating. Any help ? Commented Feb 27, 2018 at 6:14

1 Answer 1

0

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

//pinMode(motorPin1, OUTPUT);

answered Feb 27, 2018 at 6:21
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.