Homesense day #3 – Rest In Peace (my friendly neighbor)

Last time I went to Darja’s place I lost my glasses, so reading this post requires a little indulgence.
There’s no need to write a lot, Darja already gave us an excellent post .

I made a little circuit with an electret microphone and a simple operational amplifier. Something like this.
Darja plugged it in an analog pin, and then… it became more complicated.
Extracting the “noise level” from the sound sample isn’t that simple to understand. The signal wave oscillates between 0 and 5v, around 2.5v. What we want to find is the average of a sample of peaks during a specified amount of time.
Ideally, we would need a standard deviation computation. But we cheat to release a bit of load on the MCU.
To do so we collect 10 values a fast as possible, sort them and calculate the difference between both extremities. That’s all.

The code should be self-explanatory.


#include <string.h>
#include <stdio.h>

int noiseDetectorPin = 0;
signed int noiseLevel;
int ledPins[6] = { 11,10,9,6,5,3 };

int levelMax = 450;
int step;

void setup()
{

  for (int i=0; i<6; i++)
  {
    pinMode(ledPins[i], OUTPUT);
    blink(ledPins[i]);
  }
  Serial.begin(115200);

}


void loop()
{
  noiseLevel = sensor_mean_deviation(noiseDetectorPin);
  step = map(noiseLevel, 0,levelMax, 0,5 );

  Serial.println(step);
  
  for (int i=0; i < 6; i++)
  {
    analogWrite(ledPins[i], 0);
  }
  
  for (int i=0; i < step; i++)
  {
    int intensity = 0;
    if (i == step - 1)
    {
      intensity = map(noiseLevel, 0,levelMax, 0,255); // noiseLevel is proportional to levelMax, doesn't matter if it's a fraction or not.
    }
    else
    {
      intensity = 255;
    }
    analogWrite(ledPins[i], intensity);
  }
  
  blink(13);

}

void print_noise_level()
{
  Serial.print(noiseLevel);
  for (int i = 0; i < noiseLevel/2; i++ )
  {
    Serial.print("#");
  }
  Serial.println();
}

void blink(int led)
{
  digitalWrite(led, HIGH);
  delay(50);
  digitalWrite(led, LOW);
  delay(50);
}

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int sensor_mean_deviation(int sensor_pin)
{
  int values[10];

  for (int i=0; i<10; i++)
  {
    values[i] = analogRead(sensor_pin);
  }

  qsort (values, 10, sizeof(int), compare);

  return values[9] - values[0];
}

Published by

TO

Complex AI owner