MP3 sound control
This simple project will use a mp3 player, a simple, recycled speaker, and arduino and a HLK-LD2420 human motion sensor to play sounds when a human walks past the device.
sketch code:
/*
* Arduino Sketch for Motion-Activated MP3 Playback, Servo Control, and Display
*
* This code interfaces with an LD2420 MMWave Sensor to detect motion. Upon
* detecting motion, it commands a DF Player Mini to play an MP3 file, controls
* an MG996R servo motor to rotate 45 degrees, and updates an SSD1306 I2C
* display. The system uses an Arduino Nano as the main controller.
*/
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
// Pin definitions
#define SERVO_PIN A7
#define DFPLAYER_RX_PIN A2
#define DFPLAYER_TX_PIN A3
#define SENSOR_PIN A6
#define OLED_RESET -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Create objects
SoftwareSerial mySoftwareSerial(DFPLAYER_RX_PIN, DFPLAYER_TX_PIN);
DFRobotDFPlayerMini myDFPlayer;
Servo myServo;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
// Initialize serial communication
mySoftwareSerial.begin(9600);
Serial.begin(9600);
// Initialize DFPlayer
if (!myDFPlayer.begin(mySoftwareSerial)) {
Serial.println("Unable to begin DFPlayer Mini");
while (true);
}
myDFPlayer.volume(20); // Set volume level (0-30)
// Initialize Servo
myServo.attach(SERVO_PIN);
myServo.write(0); // Set initial position
// Initialize sensor pin
pinMode(SENSOR_PIN, INPUT);
// Initialize display
if (!display.begin(SSD1306_I2C_ADDRESS, 0x3C)) {
Serial.println("SSD1306 allocation failed");
for (;;);
}
display.display();
delay(2000);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("System Ready");
display.display();
}
void loop() {
// Check for motion detection
if (digitalRead(SENSOR_PIN) == HIGH) {
// Play MP3 file
myDFPlayer.play(1); // Play the first track
// Rotate servo 45 degrees
myServo.write(45);
delay(1000); // Wait for 1 second
// Return servo to initial position
myServo.write(0);
delay(1000); // Wait for 1 second
// Update display
display.clearDisplay();
display.setCursor(0, 0);
display.println("Motion Detected!");
display.display();
delay(2000);
display.clearDisplay();
display.setCursor(0, 0);
display.println("System Ready");
display.display();
}
}
Basic Wiring