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 Answer 1
I think you have to uncomment the line that defines the motor as an output device.
//pinMode(motorPin1, OUTPUT);
lang-cpp
edit
button for doing that ... while you are at it, change the title of your question toArduino not measuring distance correctly
, because that is the problem, it is not a motor problem.