Connect Vibration Motor to Arduino

I want a vibration motor to interact with a distance sensor. The vibration motor activates when the distance sensor measures a distance below 20 cm.

The code below does what I said above,except that it lights up an LED called “vibrator1.” I thought I could easily replace the LED with a vibration motor, but that doesnt work. What should I do? Is this a coding issue, a connection issue, or both?

#define trigPin1 2 //initialize pins

#define echoPin1 3

#define trigPin2 4

#define vibrator1 8

long duration, distance, Sensor1;

void setup()

{

Serial.begin (9600);

pinMode(trigPin1, OUTPUT);

pinMode(echoPin1, INPUT);

}

void loop() {

SonarSensor(trigPin1, echoPin1);

Sensor1 = distance;

if (Sensor1 < 20)
{
DigitalWrite(vibrator1, HIGH);
}
else
{
DigitalWrite(vibrator1, LOW);

}

Serial.print(Sensor1);} //print distance

void SonarSensor(int trigPin,int echoPin) //calculates distance from sensor

{

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH); //emits ultrasonic wave

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH); //pulseIn calculates the time between sending and receiving

distance = (duration/2) / 29.1; // use the time and velocity of the ultrasonic wave to find distance

delay(250);}

replace the LED with a vibration motor, but that doesnt work.

You ought to elaborate about what “doesn’t work” really means, but I’d guess that your motor is trying to draw too much current from a digital pin. What are the symptoms?

What does the motor’s datasheet say about current requirement?

What should I do?

Probably need to drive the vibrator with its own power, controlled by a transistor.

Your code, which you clearly never tested, doesn't set the vibra pin to be an output.

AWOL: Your code, which you clearly never tested, doesn't set the vibra pin to be an output.

Keen eye. This is part of a larger code, I missed that line while copy/pasting.

CGL2017: Keen eye. This is part of a larger code, I missed that line while copy/pasting.

So then what about current as I suggested in #1?

You didn't say what model motor you have, but details of two that I found have current of about 75mA, 100 at startup iirc, which is 2 or even almost 3 times the current a digital pin can provide, 4-5 times the recommended.

CGL2017:
Keen eye. This is part of a larger code, I missed that line while copy/pasting.

It’s not just one line. Your copy paste also seems to have a toupper functionality.