Hello!
Firstly, I would like to clarify that I am extremely new to Arduino and I only got to learn about it a few times in class. For this project, I am trying to use an HC-SR04 Ultrasonic Distance Sensor to get different results. When someone comes within a certain distance of the sensor, the continuous servo motor starts to spin clockwise and then anti-clockwise. When they get even closer to the sensor, the motor just spins continuously.
I would like to use a DF mini player so that not only the continuous servo motor spins but music will be played as well. The problem is, I don't know how to incorporate it into my existing code. I have tried a few times before, and both the servo motor and DF mini-player could work, but the DF player only produced some static noise. I was wondering if it's possible for both the servo motor and the DF player to run at the same time? Or if there is something wrong with my code? I would really appreciate any help!
Here's the code for playing audio that I used: https://create.arduino.cc/projecthub/munir03125344286/play-audio-in-arduino-dde2e2
My code:
#include <HCSR04.h>
#include <Servo.h>
#include <DFRobotDFPlayerMini.h>
#include <SoftwareSerial.h>
// Use pins 2 and 3 to communicate with DFPlayer Mini
static const uint8_t PIN_MP3_TX = 2; // Connects to module's RX
static const uint8_t PIN_MP3_RX = 3; // Connects to module's TX
SoftwareSerial softwareSerial(PIN_MP3_RX, PIN_MP3_TX);
// Create the Player object
DFRobotDFPlayerMini player;
UltraSonicDistanceSensor distanceSensor(7, 8);
Servo myServo; // create servo object to control a servo
int pos = 0;
void setup() {
Serial.begin(9600);
myServo.attach(11);
}
void loop() {
float distance = distanceSensor.measureDistanceCm();
Serial.println("Distance: "); //print to serial monitor
Serial.println(distance); //print distance in Cm to the serial monitor
delay(500); //so we don't get overloaded by serial monitor outputs
if (distance >= 11) {
myServo.write(94);
player.stop();
} else if (distance >= 6 && distance <= 10) {
for (pos = 0; pos <= 180; pos += 1) {
// tell servo to go to position in variable 'pos'
myServo.write(pos);
// wait 15 ms for servo to reach the position
delay(15); // Wait for 15 millisecond(s)
}
for (pos = 180; pos >= 0; pos -= 1) {
// tell servo to go to position in variable 'pos'
myServo.write(pos);
// wait 15 ms for servo to reach the position
delay(15); // Wait for 15 millisecond(s)
}
} else if (distance >= 0 && distance <= 5) {
myServo.write(0);
if (player.begin(softwareSerial)) {
Serial.println("OK");
// Set volume to maximum (0 to 30).
player.volume(10);
// Play the first MP3 file on the SD card
player.play(1);
} else {
Serial.println("Connecting to DFPlayer Mini failed!");
}
}
}