DFPlayer wifi pour ESP32

Bonjour, pour mon projet de fin d'étude je recherche à faire un klaxon musical avec un ESP32, un DFPlayer et un haut-parleur. J'aimerais contrôler plusieurs sons depuis un serveur web hébergé sur l'ESP32. Ma difficulté est de compiler 2 codes différents pour concrétiser mon projet mais j'ai peu de connaissances en Arduino IDE.

Voici le premier code qui sert à allumer des LED en wifi

// Load Wi-Fi library
#include <WiFi.h>

// Replace with your network credentials
const char* ssid = "vvvvvvxxxxxx";
const char* password = "vvvvvvxxxxxx";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";

// Assign output variables to GPIO pins
const int output26 = 26;
const int output27 = 27;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output26, OUTPUT);
  pinMode(output27, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output26, LOW);
  digitalWrite(output27, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected() && currentTime - previousTime <= timeoutTime) {  // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /26/on") >= 0) {
              Serial.println("GPIO 26 on");
              output26State = "on";
              digitalWrite(output26, HIGH);
            } else if (header.indexOf("GET /26/off") >= 0) {
              Serial.println("GPIO 26 off");
              output26State = "off";
              digitalWrite(output26, LOW);
            } else if (header.indexOf("GET /27/on") >= 0) {
              Serial.println("GPIO 27 on");
              output27State = "on";
              digitalWrite(output27, HIGH);
            } else if (header.indexOf("GET /27/off") >= 0) {
              Serial.println("GPIO 27 off");
              output27State = "off";
              digitalWrite(output27, LOW);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 26  
            client.println("<p>GPIO 26 - State " + output26State + "</p>");
            // If the output26State is off, it displays the ON button       
            if (output26State=="off") {
              client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 27  
            client.println("<p>GPIO 27 - State " + output27State + "</p>");
            // If the output27State is off, it displays the ON button       
            if (output27State=="off") {
              client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

2-ème code pour contrôler le DFPlayer

#include "SoftwareSerial.h"
#include "DFPlayer_Mini_Mp3.h"

SoftwareSerial mySerial(1, 3); // RX, TX

void setup() {
    mySerial.begin(9600);
    mp3_set_serial(mySerial);
    mp3_set_volume(15);       // fixe le son (30 maximum)
    mp3_set_EQ(0);            // equalizer de 0 à 5
}

void loop() {
    mp3_play();  // joue mp3/0001.mp3
    delay(5000); // pause de 5 secondes

Toute aide est la bienvenue.

Salut !
Je n'ai encore jamais touché au wifi sur ESP32, ni au DFplayer, mais en parcourant (très) rapidement ton code, j'ai vu un truc bizarre (je ne sais pas si c'est fait exprès) :

non signé ? en programmation, on dit unsigned. Ta ligne donnera donc : unsigned long tempscourant = millis().


[Source]. Je cite :

Les variables sont écrites dans un programme sous la forme suivante: <type> <nom> = <valeur>;

Cela donne donc :

const unsigned long tempsAttente = 2000; // j'ai rajouté un unsigned

(j'ai modifié le nom le nom de la variable, car on ne peut pas mettre autre chose que le tiret du bas (_) dans un nom, et il ne peut pas y avoir d'espace).


"tandi que", n'existe pas. Il y a if, si c'est un test que tu voulais faire...


J'imagine que tu voulais écrire quelque chose ?


qu'est ce qu'une "boucle vide" ? Un for ? Un while ?


:warning: attention, je n'ai jamais touché le wifi, je peux me tromper. Mais je mets ma main au feu que ton code ne compile pas. j'attends l'avis des experts du forum pour voir si j'ai raison :warning:
Au plaisir de pouvoir t'être utile :wink:
Cordialement
Pandaroux007

Bonjour,

On dirait que ton code a été traduit, y compris les variables.
Ca ne peut pas compiler, reprends le code originel.

Oui effectivement je n'avais pas remarqué que le code avait été traduit désolé. J'ai remis le code non traduit

Bonjour ioko

Je me suis prêté à l'exercice, avec la bibliothèque DFRobotDFPlayerMini.h.
La communication entre l'ESP32 et DFPlayer se fait par le Serial2.
image

Selon ce schéma:
image

La carte SD est organisée ainsi:
image

Et les boutons de la page Web jouent en alternance 2 MP3
image

Ca se passe ici:

						if (header.indexOf("GET /26/on") >= 0) {
							Serial.println("GPIO 26 on");
							output26State = "on";
							digitalWrite(output26, HIGH);
							mp3FolderPlay(1, 0);
							} else if (header.indexOf("GET /26/off") >= 0) {
							Serial.println("GPIO 26 off");
							output26State = "off";
							digitalWrite(output26, LOW);
							mp3FolderPlay(2, 0);
							} else if (header.indexOf("GET /27/on") >= 0) {
							Serial.println("GPIO 27 on");
							output27State = "on";
							digitalWrite(output27, HIGH);
							mp3FolderPlay(3, 0);
							} else if (header.indexOf("GET /27/off") >= 0) {
							Serial.println("GPIO 27 off");
							output27State = "off";
							digitalWrite(output27, LOW);
							mp3FolderPlay(4, 0);

C'est la fonction mp3FolderPlay(int mp3Num, int playTime) qui joue le MP3.

Le programme complet:

// Load Wi-Fi library
#include <WiFi.h>
#include <DFRobotDFPlayerMini.h>     // https://github.com/DFRobot/DFRobotDFPlayerMini

// Replace with your network credentials
const char* ssid = "vvvvvvxxxxxx";
const char* password = "vvvvvvxxxxxx";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";

// Assign output variables to GPIO pins
const int output26 = 26;
const int output27 = 27;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

//------------------------------------- DFPlayer
#define dfSerial Serial2     // Liaison avec DFPlayer

DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);


void setup()
{
	Serial.begin(115200);
	dfSerial.begin(9600);     // Liaison avec DFPlayer

	// Initialize the output variables as outputs
	pinMode(output26, OUTPUT);
	pinMode(output27, OUTPUT);
	// Set outputs to LOW
	digitalWrite(output26, LOW);
	digitalWrite(output27, LOW);

	// Connect to Wi-Fi network with SSID and password
	Serial.print("Connecting to ");
	Serial.println(ssid);
	WiFi.begin(ssid, password);
	while (WiFi.status() != WL_CONNECTED) {
		delay(500);
		Serial.print(".");
	}
	// Print local IP address and start web server
	Serial.println("");
	Serial.println("WiFi connected.");
	Serial.println("IP address: ");
	Serial.println(WiFi.localIP());
	server.begin();

	//--------------------------------- DFPlayer
	
	
	if (!myDFPlayer.begin(Serial2)) {  //Use softwareSerial to communicate with mp3.
		Serial.println(F("dfSerial to begin:"));
		Serial.println(F("1.Please recheck the connection!"));
		Serial.println(F("2.Please insert the SD card!"));
		while(true);
	}
	Serial.println(F("DFPlayer Mini online."));
	
	myDFPlayer.setTimeOut(500); //Set serial communictaion time out 500ms
	
	//----Set volume----
	myDFPlayer.volume(20);  //Set volume value (0~30).
	myDFPlayer.volumeUp(); //Volume Up
	myDFPlayer.volumeDown(); //Volume Down
	myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);
	myDFPlayer.outputDevice(DFPLAYER_DEVICE_SD);
}

void loop()
{
	WiFiClient client = server.available();   // Listen for incoming clients

	if (client) {                             // If a new client connects,
		currentTime = millis();
		previousTime = currentTime;
		Serial.println("New Client.");          // print a message out in the serial port
		String currentLine = "";                // make a String to hold incoming data from the client
		while (client.connected() && currentTime - previousTime <= timeoutTime) {  // loop while the client's connected
			currentTime = millis();
			if (client.available()) {             // if there's bytes to read from the client,
				char c = client.read();             // read a byte, then
				Serial.write(c);                    // print it out the serial monitor
				header += c;
				if (c == '\n') {                    // if the byte is a newline character
					// if the current line is blank, you got two newline characters in a row.
					// that's the end of the client HTTP request, so send a response:
					if (currentLine.length() == 0) {
						// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
						// and a content-type so the client knows what's coming, then a blank line:
						client.println("HTTP/1.1 200 OK");
						client.println("Content-type:text/html");
						client.println("Connection: close");
						client.println();
						
						// turns the GPIOs on and off
						if (header.indexOf("GET /26/on") >= 0) {
							Serial.println("GPIO 26 on");
							output26State = "on";
							digitalWrite(output26, HIGH);
							mp3FolderPlay(1, 0);
							} else if (header.indexOf("GET /26/off") >= 0) {
							Serial.println("GPIO 26 off");
							output26State = "off";
							digitalWrite(output26, LOW);
							mp3FolderPlay(2, 0);
							} else if (header.indexOf("GET /27/on") >= 0) {
							Serial.println("GPIO 27 on");
							output27State = "on";
							digitalWrite(output27, HIGH);
							mp3FolderPlay(3, 0);
							} else if (header.indexOf("GET /27/off") >= 0) {
							Serial.println("GPIO 27 off");
							output27State = "off";
							digitalWrite(output27, LOW);
							mp3FolderPlay(4, 0);
						}
						
						// Display the HTML web page
						client.println("<!DOCTYPE html><html>");
						client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
						client.println("<link rel=\"icon\" href=\"data:,\">");
						// CSS to style the on/off buttons
						// Feel free to change the background-color and font-size attributes to fit your preferences
						client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
						client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
						client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
						client.println(".button2 {background-color: #555555;}</style></head>");
						
						// Web Page Heading
						client.println("<body><h1>ESP32 Web Server</h1>");
						
						// Display current state, and ON/OFF buttons for GPIO 26
						client.println("<p>GPIO 26 - State " + output26State + "</p>");
						// If the output26State is off, it displays the ON button
						if (output26State=="off") {
							client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
							} else {
							client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
						}
						
						// Display current state, and ON/OFF buttons for GPIO 27
						client.println("<p>GPIO 27 - State " + output27State + "</p>");
						// If the output27State is off, it displays the ON button
						if (output27State=="off") {
							client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
							} else {
							client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
						}
						client.println("</body></html>");
						
						// The HTTP response ends with another blank line
						client.println();
						// Break out of the while loop
						break;
						} else { // if you got a newline, then clear currentLine
						currentLine = "";
					}
					} else if (c != '\r') {  // if you got anything else but a carriage return character,
					currentLine += c;      // add it to the end of the currentLine
				}
			}
		}
		// Clear the header variable
		header = "";
		// Close the connection
		client.stop();
		Serial.println("Client disconnected.");
		Serial.println("");
	}
}


void mp3FolderPlay(int mp3Num, int playTime)     //play specific mp3 in SD:/MP3/0004.mp3; File Name(0~65535)
{
	myDFPlayer.playMp3Folder(mp3Num);
	
	delay((playTime));
}

Je te laisse regarder l'intégration de DFPlayer dans ton programme.

A toi de jouer!

A+
Cordialement
jpbbricole

Merci. Si j'ai bien compris, lorsque j'appuie sur le bouton ON du GPIO26, la musique 1 se lance, et lorsque je l'éteins en mode OFF, cela lance la musique 2 et la même chose pour la GPIO27. Si c'est bien ça, je n'entends aucun son sortir de mon haut-parleur.

Oui, tu as bien compris :wink:
Dans la console à 115200, au démarrage de l'ESP, as-tu ce message?

WiFi connected.
IP address: 
nnn.nnn.nnn.nnn
DFPlayer Mini online.

Si non, il y a une affaire de carte SD ou de câblage.

Si oui, sur ta carte as-tu un répertoire mp3 dans lequel il y a 4 fichiers MP3 nommés:
0001.mp3
0002.mp3
0003.mp3
0004.mp3

Autrement, mets ce qu'il y a dans la console, au démarrage, sur le forum (copier/coller) pas de copie d'écran.

A+
Cordialement
jpbbricole

J'ai trouvé mon erreur. J'avais mis les fichiers directement à la racine de la carte SD au lieu de les mettre dans un répertoire.
Merci beaucoup pour l'aide.
J'ai également d'autres points sur lesquels j'aimerais obtenir de l'aide. Sur la page web, si je veux changer "GPIO 26 - State ON" par "ON (nom du son) - OFF (nom du son)", est-ce dans les lignes ci-dessous ?

// Display current state, and ON/OFF buttons for GPIO 26
client.println("<p>GPIO 26 - State " + output26State + "</p>");
// If the output26State is off, it displays the ON button
if (output26State=="off") {
  client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
   } else {
   client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
						}

Mon autre question concerne le DFPlayer. J'ai l'impression que mes deux broches de haut-parleur ne fonctionnent plus, et je ne sais pas pourquoi. Ducoup je me branche sur les pins DAC_R et DAC_1 qui n'ont pas d'amplificateur

Bonjour ioko

Ce répertoire mp3 est nécessaire à la fonction de play utilisée mp3FolderPlay

regardes l'exemple FullFunction.ino où sont détaillées toutes les façons de faire.

Cordialement
jpbbricole

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.