Df player mini подключение к ардуино

Arduino Library

Installatie van Arduino IDE libraries: Arduino info

DFRobotDFPlayerMini bibliotheek

This example shows the all the function of library for DFPlayer.

Created 2016-12-07 By Angelo qiao

GNU Lesser General Public License. See http://www.gnu.org/licenses/ for details. All above must be included in any redistribution

Notice and Trouble shooting

This code is tested on Arduino Uno, Leonardo, Mega boards.

DFPlayer-Mini-mp3 bibliotheek

DFPlayer_Mini_Mp3, This library provides a quite complete function for DFPlayer mini mp3 module.

  • DFRobotDFPlayerMini-

    5,70 kb

  • DFRobotDFPlayerMini-

    5,70 kb

  • DFRobotDFPlayerMini-

    5,70 kb

  • DFRobotDFPlayerMini-

    5,10 kb

  • DFRobotDFPlayerMini-

    4,76 kb

  • DFRobotDFPlayerMini-

    4,79 kb

  • DFPlayer-Mini-mp3 v1.0.7z

    6,68 kb


SD Kaart

NOTE: The order you copy the mp3 into micro SD card will affect the order mp3 played , which means play(1) function will play the first mp3 copied into micro SD card.

For Mac User

NOTE: If you are using Mac OS X to copy the mp3, the file system will automatically add hidden files like: “._0001.mp3” for index, which this module will handle as valid mp3 files. It is really annoying. So you can run following command in terminal to eliminate those files.

dot_clean /Volumes/<SDVolumeName>

1 dot_cleanVolumes<SDVolumeName>

Please replace the <SDVolumeName> to the volume name of your SD card.

Sample Code

We’ve created an Arduino library for DFPlayer Mini to simplify the method for you to make it work.
Connect the hardware as the picture above shown and play with the sample code.
You can download the latest library here: DFRobotDFPlayerMini.

Sample code «GetStarted», switching to next song every 3 seconds

NOTE: The folder name needs to be mp3, placed under the SD card root directory, and the mp3 file name needs to be 4 digits, for example, «0001.mp3», placed under the mp3 folder.
If you want to name it in Both English and Chinese, you can add it after the number, for example, «0001hello.mp3» or «0001后来.mp3».

Go Shopping DFPlayer — A Mini MP3 Player

Category: DFRobot > Sensors & Modules > Modules

category: Product Manual category: DFR Series category: Module category: Diagram category: DFRobot

Using the Driver

Non-Idle Waits

The driver provides you with an optional callback method support, allowing you to do your own stuff while the driver is
waiting for a timeout or performing a delay. This way you can achieve great responsiveness of your system, near to the one achieved
with multi-threaded systems.

These operations should be used for detecting non-interrupt-backed events, or driving displays and/or other devices, as long as
you keep them fast! Do not attempt to call a DFPlayerMini driver method from it, or you will trigger a recursion!

// Do your time-critical stuff here - KEEP IT SHORT AND FAST!
void readSensorsAndDoStuff() {
   actionDetected = readSensorMagic();

// Initialize the driver, passing the busy-wait method
DFPlayerMini player;
player.init(pinBusy, pinReceive, pinTransmit, readSensorsAndDoStuff);

// The readSensorsAndDoStuff() will be called from within the player, even when playing or waiting

Addressing a Sound and Achieving a Gapless Play

All the sounds should be stored on a FAT formatted SD-card. The files can be organized in folders, sorted in a natural
(sort-by-name) order. You address the file by its number (starting from 1) and its folder (also starting from 1).

However, if you need to achieve a gapless play, you should use only WAV format, and write all the files to the root
of the SD-card, rather than using folders. Furthermore, it might be a good idea to format the SD-card each time before copying
the files, and to copy the files in their order of appearence. Using Windows’ Copy/Paste will not guarantee you the proper order,
so you might want to use the SDCardRecorder Utility, a small utility written in Java,
that will also generate entries for each sound.

The module requires some time to respond to a PLAY command, so if you rely just on to achieve a gapless play, you might
still notice a short gap. The only way to solve that issue with the DFPlayer Mini, is to use combined with your own timing, and
trigger the next sample slightly before the previous is done.

If you did all as described, and there is still a pause between playing two files, then try with a faster SD-card.

Supported Sound Formats

The DFPlayerMini supports both WAV and MP3 formats. When using WAV files, you should make sure to remove any metadata
from the WAV file, since the player will interpret it as noise.

I have found the MP3 and WAV to be working great, while MP3
to cause erratic behavior in form of garbled response messages. So, if you notice that the module stars acting funky with certain
sound files, turn on the DFPLAYER_DEBUG_HEAVY mode and see if the module is returning proper responses.

Work Mode

1. Serial Mode

Support for asynchronous serial communication mode via PC serial sending commands
Communication Standard:9600 bps
Data bits :1
Checkout :none
Flow Control :none

Instruction Description

Serial Control Cmd

Serial Query Cmd

2. AD KEY Mode

We use the AD module keys, instead of the traditional method of matrix keyboard connection, it is to take advantage of increasingly powerful MCU AD functionality, Our module default configuration 2 AD port, 20 key resistance distribution.

Refer diagram

3. I/O Mode

Here comes the most simple way to use this module.

Refer diagram

note: short time press means pre/next,and long time press means vol- ,vol +

Other web support

  • /edit for file browsing and upload
  • /upload for simple file upload to bootstrap
  • /dfPlayerStatus for basic status info
  • /firmware for OTA


  • Edit dfPlayer.ino
    • Manual Wifi set up (Comment out WM_NAME)
      • AP_SSID Local network ssid
      • AP_IP If static IP to be used
    • Wifi Manager set up
      • WM_NAME (ssid of wifi manager network)
      • WM_PASSWORD (password to connect)
      • On start up connect to WM_NAME network and browse to to set up wifi
    • AP_PORT to access web services
    • update_username user for updating firmware
    • update_password


  • BitMessages Routines to look up and create pulse sequences for a commands
  • BitTx Bit bang routines to execute a pulse sequence
  • WifiManager
  • FS
  • DNSServer
  • ArduinoJson
  • ESP8266mDNS
  • ESP8266HTTPUpdateServer
  • SoftwareSerial.h
  • DFRobotDFPlayerMini.h
  • ESP8266WiFi.h

Install procedure

  • Normal arduino esp8266 compile and upload
  • A simple built in file uploader (/upload) should then be used to upload the base files to SPIFF
    index.html (can be changed to refer to different favicon)
  • The /edit operation is then supported to upload basic.htm and SD naming files

Tool for folder / track naming

The dfPlayer uses a very simple folder and track naming scheme
folders are 01 to 99
tracks are 001,002

To avoid doing tedious renaming and also to support the mobile web interface a vbscript is used

  • Copy normal folders and tracks mp3 to SD card (e.g. album names for folders)
  • Run the vbscript and point it at the SD card volume&p1
  • Tool will run and in a few seconds will rename all the files
  • It will create a file called Folders.txt mapping the renamed folders to their original names
  • It will also create a set of Tracks.txt file mapping the tracks to their original names (currently unused)
  • The Folders.txt should be uploaded to the ESP8266 via /edit
  • Tracks files may also be uploaded. Software may be enhanced to use these at some stage
  • SD card can be maintained by deleting folders, adding new named ones and re-running the tool. Renaming will be done on new folders and new map files produced.


The dfPlayer does not naturally support mute. Volume can be set to 0 but this also mutes the headphone output.

To get separate speaker mute control a small hardware mod is needed. Replace the 0 Ohm resistor with 10K and solder a mute control onto the pad as shown in the picture in docs. This mute control goes to GPIO16

Library Reference


  • — Constructor.

  • — Destructor.

  • Initializes the driver.
    — input from player’s TX;
    — output to player’s RX;
    — optional pointer to a method that will be kept called in wait cycles

  • — Reset the module.

  • — Play a specified file in specified folder number.
    Folders are optional, and discouraged if you need a gapless play!

  • Play a specified file and wait for it to be completed.
    — optional (see above);
    — optional, specifies a pin connected to a button (active-low) that can be used to abort the waiting;
    — optional timeout (defaults to DFPLAYER_WAIT_TIMEOUT);
    returns if completed successfuly, or if interrupted or failed

  • — Play a specified file in a loop. Non-blocking operation.

  • — Enables or disables looping of the current sample.

  • — Set the volume.

  • — Stop playing any current sound.

  • — Returns if a sound is currently being played (inverted state of the BUSY signal).

  • Wait for a response. Internally used by .


  • supported sampling rates (kHz): 8/11.025/12/16/22.05/24/32/44.1/48
  • 24 -bit DAC output, support for dynamic range 90dB , SNR support 85dB
  • fully supports FAT16 , FAT32 file system, maximum support 32G of the TF card, support 32G of U disk, 64M bytes NORFLASH
  • a variety of control modes, I/O control mode, serial mode, AD button control mode
  • advertising sound waiting function, the music can be suspended. when advertising is over in the music continue to play
  • audio data sorted by folder, supports up to 100 folders, every folder can hold up to 255 songs
  • 30 level adjustable volume, 6 -level EQ adjustable

Характеристики DF Player mini

Распиновка модуля приведена на изображении, он представляет собой недорогой MP3-модуль со встроенным усилителем и выходами к динамикам. DFPlayer поддерживает такие аудио форматы, как MP3, WAV и WMA, которые можно считывать с флэшки или TF-карты до 32 Гб. С помощью данного модуля можно озвучивать проекты на Ардуино, один из них мы представляли ранее — это световой меч своими руками для детей.

Распиновка. Подключение кнопок и динамика, dfplayer mini datasheet

Кроме того, данный модуль можно использовать без платы Arduino Nano, подключив к модулю питание, динамик и кнопки напрямую. Схема данного подключения (datasheet dfplayer mini) размещена далее на схеме выше. Питание модуля должно быть в пределах 3,3 — 5 Вольт. Все звуковые файлы должны лежать в папке «mp3» на флэшке или TF карты в следующем формате: «0001.mp3», «0002.mp3», «0003.mp3» и т.д.

Wiring the Module

Signal Pins

The driver uses two-way communication with the module. Therefore, you must connect module’s pin (2) with a on
the microcontroller, and module’s pin (3) with a on the controller.

In cases where the Arduino is driven at 5V, you must put a 1k resistor between data-out on Arduino and of the player.
and must be connected to their counterparts on the Arduino directly, even if you drive the module at 5V! This is because the
module always uses 3.3V levels for its signal lines.

pin (16) on the module is optional, and is used only by the method. For the method, the driver waits
for a response, instead of reading the signal.

Powering the Module

According to the module specifications, it requires input voltage between 3.2V and 5.0V. However, if you use a breadboard, the
contact resistance of power lines will be around 0.2 Ohm on each contact, and since the module can draw well above 0.5A at full
power, the voltage drop will cause erratic behavior, when the source voltage is not high enough.

Therefore, ensure a stable power source and keep the contact resistance as low as possible, especially in cases when power
leads are not soldered to the module.


Informatie (ENG):

The DFPlayer Mini MP3 Player For Arduino is a small and low price MP3 module with an simplified output directly to the speaker. The module can be used as a stand alone module with attached battery, speaker and push buttons or used in combination with an Arduino UNO or any other with RX/TX capabilities.


  • supported sampling rates (kHz): 8/11.025/12/16/22.05/24/32/44.1/48
  • 24 -bit DAC output, support for dynamic range 90dB , SNR support 85dB
  • fully supports FAT16 , FAT32 file system, maximum support 32G of the TF card, support 32G of U disk, 64M bytes NORFLASH
  • a variety of control modes, I/O control mode, serial mode, AD button control mode
  • advertising sound waiting function, the music can be suspended. when advertising is over in the music continue to play
  • audio data sorted by folder, supports up to 100 folders, every folder can hold up to 255 songs
  • 30 level adjustable volume, 6 -level EQ adjustable


  • Car navigation voice broadcast;
  • Road transport inspectors, toll stations voice prompts;
  • Railway station, bus safety inspection voice prompts;
  • Electricity, communications, financial business hall voice prompts;
  • Vehicle into and out of the channel verify that the voice prompts;
  • The public security border control channel voice prompts;
  • Multi-channel voice alarm or equipment operating guide voice;
  • The electric tourist car safe driving voice notices;
  • Electromechanical equipment failure alarm;
  • Fire alarm voice prompts;
  • The automatic broadcast equipment, regular broadcast.

Seriele Communicatie

De module werkt via asynchrone seriële communicatie

  • Standaard: 9600 bps
  • Data bits: 1
  • Checkout: none
  • Flow Control: none

Instructie opbouw:

Seriële commando’s:


We use the AD module keys, instead of the traditional method of matrix keyboard connection, it is to take advantage of increasingly powerful MCU AD functionality, Our module default configuration 2 AD port, 20 key resistance distribution.

Here comes the most simple way to use this module.

Versie 1 (DFPlayer mini)

YX5200-24SS chip: MP3 decoding serial chipThe YX5200 is an MP3 chip that provides a serial port, which is a perfect integrated hard decoding of MP3 and WMV. Simultaneously The software supports TF card driver and supports FAT16 and FAT32 file systems. Complete the broadcast with a simple serial command Put the specified music, and how to play music, etc., without the cumbersome underlying operation, easy to use, stable and reliable It is the biggest feature of this product. In addition, the chip is also a deeply customized product, designed for USB card readers, USB sound A low-cost solution developed in the field of cards and fixed voice playback

8002 chip: Versterker
The 8002 is an audio power amplifier primarily designed for demanding applications in low-power portable systems. It is capable of delivering 3 watts of continuous average power to an 3Ω BTL load with less than 10% distortion (THD) from a 5VDC power supply. the 8002 does not require output coupling capacitors or bootstrap capacitors, and therefore is ideally suited for mobile phone and other low voltage applications where minimal power consumption is a primary requirement.the 8002 features a low-power consumption shutdown mode.the 8002 contains advanced pop & click circuitry which eliminates noise which would otherwise occur during turn-on and turn-off transitions. The 8002 is unity-gain stable and can be configured by external gain-setting resistors.

FN5201-24SS chip: MP3 decoding serial chip (kloon?)
8002 chip: Versterker

Подключение DF Player mini к Arduino

Для занятия нам понадобятся следующие детали:

  • плата Arduino Uno / Arduino Nano / Arduino Mega;
  • модуль DF Player mini;
  • SD карта или флэшка;
  • динамик;
  • провода «папа-мама».

На приведенной ниже схеме представлено подключение DFplayer mini Arduino Nano. Также на приведенной схеме проиллюстрировано, как подключить к звуковому модулю USB порт, чтобы проигрывать звуки флэшки. После сборки схемы, сохраните на Flash-карте несколько звуковых файлов в формате: «0001.mp3», «0002.mp3», «0003.mp3» в папке «mp3». Все файлы и скетч можно скачать одним архивом чуть ниже.

Схема подключения модуля DF Player Mini mp3 к Arduino Nano

После сборки схемы загрузите следующий скетч

Внимание! Перед загрузкой отключите последовательный порт UART (порты RX и TX) на Ардуино. Иначе компьютер не определит микроконтроллер и программа не загрузится

Скачать скетч, библиотеку DFPlayer_Mini_Mp3.h и звуковые файлы можно одним архивом здесь.

Сегодня будем изучать такую интересную вещь как аудиоплеер. Есть такой модуль для Ардуино, DFPlayer. Но прелесть этого модуля в том, что он может работать и без Ардуино. Для сборки достаточно только MicroSD карты от 2 до 32 Gb, двух кнопок и динамика. Питается всё это от 3,3-5 вольт.

Применять можно как в разных поделках будильниках, музыкальных шкатулках, так и в более серьёзных проектах, таких как сигнализации, оповещении и многих других. На MicroSD карту можно записать огромное количество файлов и обращаться к любому из них по запросу из скетча. Для работы с Ардуино нужна библиотека DFPlayer-Mini-mp3.zip скачать можно с этого сайта. Если вы хотите собрать плейер без Ардуино, то и библиотека не нужна. Просто подключаете модуль по этой схеме и слушаете музыку. Правда в такой конструкции есть недостатки.

  1. Нельзя включить запись, например 12, можно только пролистывать до нужной записи нажимая кнопку Следующая/Предыдущая. Короче, только по порядку.
  2. Нельзя запустить случайное проигрывание, опять только по порядку
  3. Можно прослушивать только по одной записи. Одна проиграла, плейер выключился. Снова нажали он включился и стала воспроизводиться следующая запись.

Подготовка карты MicroSD Карта должна быть от 2 до 32 Gb и отформатирована в FAT16 или FAT32 Создаём папку mp3 (это обязательно) и переносим туда ваши записи. Записи должны начинаться с 0001 0002 0003 итд. После цифр могут быть любые название напр. 0001-ABBA-concert.mp3

Описание контактов модуля DFPLayer:

Номер вывода Название Описание вывода Описание
1 VCC Питание Питание постоянного тока от 3 до 5 Вольт
2 RX UART serial input
3 TX UART serial output
4 DAC_R Audio output right channel Выход на усилитель, правый канал
5 DAC_L Audio output left channel Выход на динамик, со встроенного усилителя до 3W
9 IO1 Trigger port 1 Короткое нажатие | (длительное нажатие – уменьшение громкости)
10 GND Ground Выход на динамик, со встроенного усилителя до 3W
11 IO2 Trigger port 2 Короткое нажатие (длительное нажатие – увеличение громкости)
12 ADKEY1 AD port 1 Trigger play first segment
13 ADKEY2 AD port 2 Trigger play fifth segment
15 USB- USB- DM USB Port
16 Busy Playing Status Low means playingHigh means no

НА Модуле есть два каскада выходного сигнала. Выход на внешний усилитель(DAC_R и DAC_L стерео) и Выход на динамик(SPK_1 и SPK_2 моно режим)

Список функций DFPlayer Mini:

  • mp3_play (); // Запуск воспроизведения
  • mp3_play (5); // Воспроизвести файл “mp3/0005.mp3”
  • mp3_next (); // Следующий трек
  • mp3_prev (); // Предыдущий трек
  • mp3_set_volume (uint16_t volume); // Уровень громкости 0

mp3_set_EQ (); // Эквалайзер 0

5 (0 – Normal, 1 – Pop, 2 – Rock, 3 – Jazz, 4 – Classic, 5 – Bass)

mp3_pause (); // пауза
mp3_stop (); // остановить воспроизведение
mp3_random_play (); // Воспроизвести в случайном порядке.
void mp3_get_state (); //send get state command
void mp3_get_volume ();
void mp3_get_u_sum ();
void mp3_get_tf_sum ();
void mp3_get_flash_sum ();
void mp3_get_tf_current ();
void mp3_get_u_current ();
void mp3_get_flash_current ();
void mp3_single_loop (boolean state); //set single loop
void mp3_DAC (boolean state);

Подключение к Ардуино будет описано в следующей статье блога (подписывайтесь что бы не пропустить).

А сейчас рассмотрим, как собрать без Ардуино.

Есть два способа, Простой и более сложный. Рассмотрим простой. Нам понадобится сам модуль плеера, MicroSD карта, две кнопки и динамик.

Управление плейером.

  • Длительное нажатие кнопки S1 – Громкость меньше
  • Короткое нажатие кнопки S1 – Следующая запись
  • Длительное нажатие кнопки S2 – Громкость больше
  • Короткое нажатие кнопки S2 – Предыдущая запись

Более сложный режим

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *