Hi, I need help in making this vibration motor work for a school project. I can't see what's wrong since I follow YouTube vids and some articles. Here's my code and circuit:
// declare HC-SSR04 sensor
const int trigPin = 3;
const int echoPin = 2;
// declare LED pins
const int LED1 = 12;
const int LED2 = 9;
const int LED3 = 7;
const int LED4 = 4;
// declare vibration motor components
const int button_pin = 5;
const int motor_pin = 13;
int button_state = 0;
// variables for HC-SR04 sensor
int duration = 0;
int distance = 5;
float duration_us, distance_cm;
void setup() {
Serial.begin(9600);
pinMode(button_pin, INPUT);
pinMode(motor_pin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
}
void loop() {
long duration, inches, cm;
// Trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
cm = microsecondsToCentimeters(duration);
distance_cm = cm; // Store calculated distance
// Print the measured distance
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
// Control the button
if(digitalRead(button_pin) == HIGH){ // if the button is pressed
digitalWrite(motor_pin, HIGH); // turn the vibration motor on
}
else if (digitalRead(button_pin) == LOW){ // if the button is not pressed
digitalWrite(motor_pin, LOW); // turn the LED off
}
// vibration motor
button_state = digitalRead(button_pin);
if (button_state == HIGH){ // turn the motor on when button is on
digitalWrite(motor_pin, HIGH);
Serial.println("Motor ON");
} else if (button_state == LOW){ // if button is off
digitalWrite(motor_pin, LOW); // turn motor off
Serial.println("Motor OFF");
}
// Control LEDs based on distance
if (distance_cm >= 15 && distance_cm < 40) {
digitalWrite(LED1, HIGH);
digitalWrite(LED2, HIGH);
digitalWrite(LED3, HIGH);
digitalWrite(LED4, HIGH);
} else if (distance_cm < 15) {
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
digitalWrite(LED4, LOW);
}
delay(100);
}
// Function to convert microseconds to centimeters
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
