Back to Parent

Code
// Setup Variables
# define Start_Byte 0x7E
# define Version_Byte 0xFF
# define Command_Length 0x06
# define End_Byte 0xEF
# define Acknowledge 0x00 //Returns info with command 0x41 [0x01: info, 0x00: no info]
# define micPin A5

int volume;
int micReading;
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;

// Wrote by Ype Brada
void execute_CMD(byte CMD, byte Par1, byte Par2) // Excecute the command and parameters
{
    // Calculate the checksum (2 bytes)
    int16_t checksum = -(Version_Byte + Command_Length + CMD + Acknowledge + Par1 + Par2);
    // Build the command line
    byte Command_line[10] = { Start_Byte, Version_Byte, Command_Length, CMD, Acknowledge, Par1, Par2, checksum >> 8, checksum & 0xFF, End_Byte};
    //Send the command line to the module
    for (byte k=0; k<10; k++)
    {
        Serial1.write( Command_line[k]);
        }
    }

    /****************************************
    Example Sound Level Sketch for the 
    Adafruit Microphone Amplifier
    ****************************************/

void setup () {
    Serial.begin(9600);
    Serial1.begin(9600);
    execute_CMD(0x3F, 0, 0); // Send request for initialization parameters
    // Wait until initialization parameters are received
    while (Serial1.available()<10)
    // Pretty long delays between successive commands needed
    delay(10);
    // Initialize sound to very low volume. Adapt according used speaker and wanted volume
    execute_CMD(0x06, 0, 30);
    // Set the volume (0x00~0x30)
    }

void loop () {
  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level

  unsigned int signalMax = 0;
  unsigned int signalMin = 4096;

  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
     sample = analogRead(micPin);
     if (sample < 4096)  // toss out spurious readings
     {
        if (sample > signalMax)
        {
           signalMax = sample;  // save just the max levels
        }
        else if (sample < signalMin)
        {
           signalMin = sample;  // save just the min levels
        }
     }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
 //  double volts = (peakToPeak * 5.0) / 4096;  // convert to volts

  // Serial.println(peakToPeak);
    if (peakToPeak < 120) {
      execute_CMD(0x0D,0,1);
      delay(3000);
    }
    else {
      execute_CMD(0x11, 0, 0x00);
    }
}
Victoria Yong, Wei Wei (2019) - https://learn.adafruit.com/adafruit-microphone-amplifier-breakout/measuring-sound-levels Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0