MAX98357 I2S Amplifier Module Wiki - DFRobot

Introduction

This I2S digital amplifier based on the MAX98357 I2S Class D amplifier module works great with microcontrollers with I2S audio outputs like ESP32 and can be applied to projects like IoT nodes, smart home devices, Bluetooth audio players, and so on. The module supports 3.3V-5V power supply. And it can output over 2.5W of power when driven by 5V and a 4Ω speaker. Besides, it allows users to set different modes (off, left channel, right channel, and mixed) by changing the resistance on the SD port. The product defaults to be mixed mode. Featuring a small size, this I2S amplifier comes with stamp holes that enable it to be directly plugged into or mounted on a PCB and breadboard. Also, it is designed with PH2.0 and stamp holes for connecting speakers, flexible and convenient to use.

Features

Application

Board Overview

Board Overview

Pin Function Remark
SPK- Speaker negative 4Ω/8Ω <3W
VCC Power input DC 3.3V-5V
GND Ground
NC Not connected pin
SD Turn off amplifier, adjust sound channel Refer to 4.1.2(SD Mode Description)
GAIN Adjust amplifier gain Default to 9dB/Refer to 4.1.1 Gain Control Description
SPK+ Speaker positive 4Ω/8Ω <3W
DIN Digital input signal
BCLK Bit clock input Bit Clock Input
LRC Frame clock Left/right clock of I2S and LJ mode. Synchronized clock in TDM mode

Special Pin Function

4.1.1 Gain Control(Gain)

SD Mode

Channel setting

pin

Specification

Module Parameter

Chip Audio-relevant Parameters

Product Dimension

Dimension

Tutorial 1 - Play music via Bluetooth

Requirements

Connection Diagram

Connection 1

Description:

I2S Module VCC to ESP32-E 3V3
I2S Module GND to ESP32-E GND
I2S Module LRC to ESP32-E 26/D3
I2S Module BCLK to ESP32-E 25/D2
I2S Module DIN to ESP32-E 14/D6
I2S Module SPK+ to Speaker power +
I2S Module SPK- to Speaker power -

Sample Code

Enable ESP32-E Bluetooth function, create a Bluetooth node named bluetoothAmplifier, and use a phone with Bluetooth function to connect that node to play music.

#include <DFRobot_MAX98357A.h>
DFRobot_MAX98357A amplifier;  

void setup(void)
{
  Serial.begin(115200);//Set serial rate to 115200
  while( !amplifier.begin(/*btName=*/"bluetoothAmplifier", /*bclk=*/GPIO_NUM_25, /*lrclk=*/GPIO_NUM_26,/*din=*/GPIO_NUM_14) ){
    Serial.println("Initialize failed !");//No I2S pin signal detected, init failed 
    delay(3000);
  }
  Serial.println("Initialize succeed!");//I2S pin signal detected, init succeeded  
}

void loop(void)
{
  delay(3000);
}

Result

Open Arduino IDE, select board as "FireBeetle2 ESP32-E" and set upload rate to 921600

Set upload rate

Copy the codes to Arduino IDE, and burn into FireBeetle2 ESP32-E.

Copy codes

Turn on the mobile phone Bluetooth and connet to the bluetoothAmplifier node, then play muisc.

Connect Bluetooth

Tutorial 2 - Play music from SD card

Requirements

Connection Diagram

Connection 2

Description:

I2S Module VCC to ESP32-E 3V3
I2S Module GND to ESP32-E GND
I2S Module LRC to ESP32-E 26/D3
I2S Module BCLK to ESP32-E 25/D2
I2S Module DIN to ESP32-E 14/D6
SD card module 5V to ESP32-E VCC
SD card module GND to ESP32-E GND
SD card module MOSI to ESP32-E 23/MOSI
SD card module SS to ESP32-E 4/D12
SD card module SCL to ESP32-E 18/SCK
SD card module MISO to ESP32-E 19/MISO
I2S Module SPK+ to Speaker power +
I2S Module SPK- to Speaker power -

Sample Code

Connect to SD card module, then the music in the SD card can be played. Press RST button to play from the beginning,

#include <DFRobot_MAX98357A.h>

DFRobot_MAX98357A amplifier;   

String musicList[100];   // SD card music playlist 
void setup(void)
{
  Serial.begin(115200);
  while ( !amplifier.initI2S(/*_bclk=*/GPIO_NUM_25, /*_lrclk=*/GPIO_NUM_26, /*_din=*/GPIO_NUM_14) ){
    Serial.println("Initialize I2S failed !");
    delay(3000);
  }
  while (!amplifier.initSDCard(/*csPin=*/GPIO_NUM_4)){
    Serial.println("Initialize SD card failed !");
    delay(3000);
  }
  Serial.println("Initialize succeed!");
  amplifier.scanSDMusic(musicList);
  printMusicList();
  amplifier.setVolume(5);
  amplifier.closeFilter();
  amplifier.openFilter(bq_type_highpass, 500);
  amplifier.SDPlayerControl(SD_AMPLIFIER_PLAY);
  delay(5000);   
  if(musicList[1].length()){
    Serial.println("Changing Music...\n");
    amplifier.playSDMusic(musicList[1].c_str());
  }else{
    Serial.println("The currently selected music file is incorrect!\n");
  }
}
void loop()
{
  parseSerialCommand();
  delay(500);
}
void printMusicList(void)
{
  uint8_t i = 0;
  if(musicList[i].length()){
    Serial.println("\nMusic List: ");
  }else{
    Serial.println("The SD card audio file scan is empty, please check whether there are audio files in the SD card that meet the format!");
  }

  while(musicList[i].length()){
    Serial.print("\t");
    Serial.print(i);
    Serial.print("  -  ");
    Serial.println(musicList[i]);
    i++;
  }
}
void parseSerialCommand(void)
{
  String cmd;   
  float value;   
  if(Serial.available()){   
    cmd = Serial.readStringUntil('-');   

    if(cmd.equals("hp")){   
      Serial.println("Setting a High-Pass filter...\n");
      value =Serial.parseFloat();
      amplifier.openFilter(bq_type_highpass, value);
    }else if(cmd.equals("lp")){   
      Serial.println("Setting a Low-Pass filter...\n");
      value =Serial.parseFloat();
      amplifier.openFilter(bq_type_lowpass, value);
    }else if(cmd.equals("closeFilter")){   
      Serial.println("Closing filter...\n");
      amplifier.closeFilter();
    }else if(cmd.equals("vol")){
      Serial.println("Setting volume...\n");
      value =Serial.parseFloat();
      amplifier.setVolume(value);
    }else if(cmd.equals("start")){   
      Serial.println("starting amplifier...\n");
      amplifier.SDPlayerControl(SD_AMPLIFIER_PLAY);
    }else if(cmd.equals("pause")){   
      Serial.println("Pause amplifier...\n");
      amplifier.SDPlayerControl(SD_AMPLIFIER_PAUSE);
    }else if(cmd.equals("stop")){   
      Serial.println("Stopping amplifier...\n");
      amplifier.SDPlayerControl(SD_AMPLIFIER_STOP);
    }else if(cmd.equals("musicList")){   
      Serial.println("Scanning music list...\n");
      amplifier.scanSDMusic(musicList);
      printMusicList();
    }else if(cmd.equals("changeMusic")){   
      cmd = musicList[Serial.parseInt()];
      if(cmd.length()){
        Serial.println("Changing Music...\n");
        amplifier.playSDMusic(cmd.c_str());
      }else{
        Serial.println("The currently selected music file is incorrect!\n");
      }

    }else{   
      Serial.println("Help : \n \
      Currently available commands (format: cmd-value):\n \
        Start playback: e.g. start-\n \
        Pause playback: e.g. pause-\n \
        Stop playback: e.g. stop-\n \
        Print music list: e.g. musicList-\n \
        Change songs according to the music list: e.g. changeMusic-1\n \
        Set and open high-pass filter: e.g. hp-500\n \
        Set and open low-pass filter: e.g. lp-15000\n \
        Close filter: e.g. closeFilter-\n \
        Set volume: e.g. vol-5.0\n \
      For the detailed meaning, please refer to the code comments of this demo.\n");   
    }
    while(Serial.read() >= 0);   
  }
}

Result

Open Arduino IDE, select board as "FireBeetle2 ESP32-E" and set upload rate to 921600

Set upload rate

Copy the codes into Arduino IDE, burn into FireBeetle2 ESP32-E, the music files the SD card will be played automatically.

Play music from SD

API Function

/**
   * @fn begin
   * @brief Init function
   * @param btName - Created Bluetooth device name
   * @param bclk - I2S communication pin number, serial clock (SCK), aka bit clock (BCK)
   * @param lrclk - I2S communication pin number, word select (WS), i.e. command (channel) select, used to switch between left and right channel data
   * @param din - I2S communication pin number, serial data signal (SD), used to transmit audio data in two's complement format
   * @return true on success, false on error
   */
  bool begin(const char *btName="bluetoothAmplifier", 
             int bclk=GPIO_NUM_25, 
             int lrclk=GPIO_NUM_26, 
             int din=GPIO_NUM_27);

  /**
   * @fn initI2S
   * @brief Initialize I2S
   * @param _bclk - I2S communication pin number, serial clock (SCK), aka bit clock (BCK)
   * @param _lrclk - I2S communication pin number, word select (WS), i.e. command (channel) select, used to switch between left and right channel data
   * @param _din - I2S communication pin number, serial data signal (SD), used to transmit audio data in two's complement format
   * @return true on success, false on error
   */
  bool initI2S(int _bclk, int _lrclk, int _din);

  /**
   * @fn initBluetooth
   * @brief Initialize bluetooth
   * @param _btName - The created Bluetooth device name
   * @return true on success, false on error
   */
  bool initBluetooth(const char * _btName);

  /**
   * @fn initSDCard
   * @brief Initialize SD card
   * @param csPin The number of the cs pin for spi communication of SD card module
   * @return true on success, false on error
   */
  bool initSDCard(uint8_t csPin=GPIO_NUM_5);

/*************************** Function ******************************/

  /**
   * @fn scanSDMusic
   * @brief Scan the music files in WAV format in the SD card
   * @param musicList - The music files in WAV format scanned from the SD card. Type: character string array.
   * @return None
   * @note Only support English for path name of music files and WAV for their format currently.
   */
  void scanSDMusic(String * musicList);

  /**
   * @fn playSDMusic
   * @brief Play music files in the SD card
   * @param Filename - music file name, only support the music files in .wav format currently
   * @note Music file name must be an absolute path like /musicDir/music.wav
   * @return None
   * @note Only support English for path name of music files and WAV for their format currently.
   */
  void playSDMusic(const char *Filename);

  /**
   * @fn SDPlayerControl
   * @brief SD card music playback control interface
   * @param CMD - playback control command: 
   * @n SD_AMPLIFIER_PLAY: start to play music, which can be played from the position where you paused before
   * @n   If no music file is selected through playSDMusic(), the first one in the playlist will be played by default.
   * @n   Playback error may occur if music files are not scanned from SD card in the correct format (only support English for path name of music files and WVA for their format currently)
   * @n SD_AMPLIFIER_PAUSE: pause playback, retain the playback position of the current music file
   * @n SD_AMPLIFIER_STOP: stop playback, end the current music playback
   * @return None
   */
  void SDPlayerControl(uint8_t CMD);

  /**
   * @fn getMetadata
   * @brief Get "metadata" through AVRC command
   * @param type - The type of metadata to be obtained, and the parameters currently supported: 
   * @n     ESP_AVRC_MD_ATTR_TITLE   ESP_AVRC_MD_ATTR_ARTIST   ESP_AVRC_MD_ATTR_ALBUM
   * @return The corresponding type of "metadata"
   */
  String getMetadata(uint8_t type);

  /**
   * @fn getRemoteAddress
   * @brief Get address of Bluetooth device remotely
   * @note The address will be obtained after the module is paired with the remote Bluetooth device and successfully communicates with it based on the Bluetooth AVRCP protocol.
   * @return Return the array pointer storing the address of the remote Bluetooth device
   * @n Return None when the module does not connect to the remote device or failed to communicate with it based on the Bluetooth AVRCP protocol.
   * @n AVRCP(Audio Video Remote Control Profile)
   */
  uint8_t * getRemoteAddress(void);

  /**
   * @fn setVolume
   * @brief Set volume
   * @param vol - Set volume, the range can be set to 0-9
   * @note 5 for the original volume of audio data, no increase or decrease
   * @return None
   */
  void setVolume(float vol);

  /**
   * @fn openFilter
   * @brief Enable audio filter
   * @param type - bq_type_highpass: enable high-pass filtering; bq_type_lowpass: enable low-pass filtering
   * @param fc - Threshold of filtering, range: 2-20000
   * @note For example, setting high-pass filter mode and the threshold of 500 indicates to filter out the audio signal below 500; high-pass filter and low-pass filter will work simultaneously.
   * @return None
   */
  void openFilter(int type, float fc);

  /**
   * @fn closeFilter
   * @brief Disable the audio filter
   * @return None
   */
  void closeFilter(void);

  /**
   * @fn reverseLeftRightChannels
   * @brief Reverse left and right channels, When you find that the left
   * @n  and right channels play opposite, you can call this interface to adjust
   * @return None
   */
  void reverseLeftRightChannels(void);

FAQ

For any questions, advice or cool ideas to share, please visit the DFRobot Forum.

More Documents