Подредактировать программу индикатора звука vu метра

Барс
Offline
Зарегистрирован: 26.08.2020

 Добрый день.Светодиодный драйвер HT16K33. Есть рабочая наработка программы не могу добавить пиковые всплески (отскок двух светодиодов с зависанием, так же нужно разбить шкалу на децибелы, задействовать 14 выходов под светодиоды и два выхода на переменную активацию правый, левый канал по очереди. Шкала -20 до +6дб.

andriano
andriano аватар
Offline
Зарегистрирован: 20.06.2015

Барс, здесь никого не интересует, можете ли Вы что-то куда-то добавить или нет. Главное - чтобы Вы могли сформулировать более или менее вменяемое ТЗ.

Барс
Offline
Зарегистрирован: 26.08.2020

Не совсем понятно, что не понятно, в общем нужно доработать либо написать заново.

b707
Offline
Зарегистрирован: 26.05.2017

не понятно, что имеется в виду под "есть готовая программа" - если в ней нет ни пиков. ни разбивки шкалы. ни даже выходов под светодиоды и каналы... а что же там есть тогда?

Это случаем не АлексаГайвера код надо переделывать? - для его поделок как раз характерно, что вроде код есть, но если что поменять -  переписывать надо все

Барс
Offline
Зарегистрирован: 26.08.2020

Нет, может только лишнее что

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
#include <FastLED.h>
# define  PEAK_FALL  2000                // Скорость падения точки пика [20]
# define TOP ( peakToPeak + 2) // Allow dot to go slightly off scale [(N_PIXELS + 2)]


// Include the Matrix code for display
Adafruit_8x16matrix matrix = Adafruit_8x16matrix();
int leftPin = A0, rightPin = A1;                          // left audio in on analog 0, right on analog 1
int brightnessPin = A6, sensitivityPin = A7;              // potentiometers for brightness and sensitivity on analog 4 and 5

int showPeaksPin = 7;                                     // switch to toggle peaks on or off on digital pin 7
int momentarySwitch = false;                              // set false for an on/off toggle switch

const int maxScale = 14;
const int redZone = 3 ;

const int ValueWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int leftValue = 0,  rightValue = 0, maxReadValue = 0;
int leftAnalogValue = 0, rightAnalogValue = 0;
uint8_t volCountLeft = 0 ; // счетчик кадров для хранения данных прошлых томов
unsigned int volLeft[ValueWindow]; // сбор предыдущих объемных проб
int lvlLeft = 0; // Текущий "демпфированный" уровень звука
int minLvlAvgLeft = 0 ; // для динамической настройки графика low & high
int maxLvlAvgLeft = 512;

uint8_t volCountRight = 0 ; // счетчик кадров для хранения данных прошлых томов
unsigned int volRight[ValueWindow]; // коллекция предыдущих объемных образцов
int lvlRight = 0; // Текущий "демпфированный" уровень звука
int minLvlAvgRight = 0 ; // для динамической настройки графика low & high
int maxLvlAvgRight = 512;

int prevLeftValue = 0, prevRightValue = 0;
int prevLeftAnalogValue = 0, prevRightAnalogValue = 0;

//int dropDelay = 4;   // держите время перед падением светодиодов                                    // hold time before dropping the leds
//float dropFactor = .92; // значение для сбрасывания светодиодов
//int startupAnimationDelay = 5;
//int peakTimeNoDropDelay = 250;                            // peak hold time when not dropping the peaks (set droppingPeak true or false)
//int peakTimeFirstDropDelay = 130;                         // peak hold time when dropping the first peak
//int peakTimeDropDelay = 7;                                // peak hold time when dropping the rest of the peaks
//float peakDropFactor = .93;                               // value for dropping the peaks
//int droppingPeakFade = false;                             // display the dropping peak fading to black or not
//int bouncingPeaksNumOfLeds = 2;                           // how many leds to bounce up (max)
//int bouncingPeakDelay = 4;                                // delay between peak bounce updates
//int bouncingPeakCounterInc = 10;                          // increase counter for each bounce update. note: it uses a 0-180 sin function for the bouncing
// setup other variables, user editable

int minValue = 10;                                        // min analog input value
int maxValue = 350;                                       // max analog input value (0-1023 equals 0-5V)
int sensitivityValue = 128;                               // 0 - 255, initial value (value read from the potentiometer if useSensorValues = true)
int maxSensitivity = 2 * 255;                             // let the 'volume' go up to 200%!
int ledBrightness = 30;                                   // 0 - 255, initial value (value read from the potentiometer if useSensorValues = true)
int sensorDeviationBrightness = 1;                        // eliminate fluctuating values
int overflowDelay = 20;                                   // overflow hold time
// peak settings
//int displayPeaks = true;                                  // value will be set by the switch if useSensorValues = true
//int droppingPeak = true;                                  // display dropping peaks or not. note: displayPeaks has to be true
//int bouncingPeaks = true;                                 // display bouncing peaks or not. note: displayPeaks has to be true
// initialize other variables needed for the sketch//
//float sensitivityFactor;

int brightnessValue, prevBrightnessValue;
float ledFactor, ledFactor_div_numOfSegments;




int i, j;
int dropLeft, dropRight;
int leftDropTime, rightDropTime;
int leftPeak = 0, rightPeak = 0;
int leftPeakTime = 0, rightPeakTime = 0;
int leftFirstPeak = true, rightFirstPeak = true;
int readShowPeaksPin, prevReadShowPeaksPin;
int leftPeakBouncing = false, rightPeakBouncing = false;
int leftPeakBounce = 0, rightPeakBounce = 0;
int prevLeftPeakBounce = 0, prevRightPeakBounce = 0;
int leftPeakBounceCounter = 0, rightPeakBounceCounter = 0;
int leftPeakBounceDelayCounter = 0, rightPeakBounceDelayCounter = 0;
void setup()
{
  Serial.begin(9600);
  Serial.println("16x8 LED Matrix Test");
  matrix.begin(0x70);  // pass in the address
}


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 = 1024;
 

 
  while (millis() - startMillis < ValueWindow)
  {
    leftValue = analogRead(leftPin );
    if (leftValue < 1024)  // toss out spurious readings
    {
      if (leftValue > signalMax)
      {
        signalMax = leftValue;  // save just the max levels
      }
      else if (leftValue < signalMin)
      {
        signalMin = leftValue; } // save just the min levels
    volLeft[volCountLeft] = leftValue; // Save sample for dynamic leveling
     volCountLeft = ++volCountLeft % ValueWindow;
      // Calculate bar height based on dynamic min/max levels (fixed point):
uint16_t height = TOP * (lvlLeft - minLvlAvgLeft) / (long)(maxLvlAvgLeft - minLvlAvgLeft);
      }


    }

    rightValue = analogRead(rightPin);
    if (rightValue < 1024)  // toss out spurious readings
    {
      if (rightValue > signalMax)
      {
        signalMax = rightValue;  // save just the max levels
      }
      else if (rightValue < signalMin)
      {
        signalMin = rightValue;  // save just the min levels
    volRight[volCountRight] = rightValue; // Save sample for dynamic leveling
    volCountRight = ++volCountRight % ValueWindow;
      // Calculate bar height based on dynamic min/max levels (fixed point):
 uint16_t height = TOP * (rightValue - signalMin) / (long)(signalMax - signalMin); 
      }
    }
  
 

  peakToPeak = signalMax - signalMin;

  // map 1v p-p level to the max scale of the display
  int displayPeak = map(peakToPeak * 10, 0, 1023, 0, maxScale);

 

  // draw the new sample
  for (int i = 0; i <= maxScale; i++)
  {
    if (i >= displayPeak)  // blank these pixels
    {
      matrix.drawPixel(0, i, 0);
    }
    else if (i < redZone) // draw in green
    {
      matrix.drawPixel(0, i, LED_GREEN);
  
    
    }
    else // Red Alert!  Red Alert!
    {
      matrix.drawPixel(0, i, LED_RED);
    }
  }
 

  matrix.writeDisplay();  // write the changes we just made to the display
 // Serial.println( displayPeak);
} uint16_t auxReading( uint8_t peakToPeak) {

  
  uint16_t height = 0;} /*
    Function for dropping the peak
  */
  uint8_t peakLeft, peakRight;
  void dropPeak( uint8_t peakToPeak ) {

    static uint8_t dotCountLeft, dotCountRight;
int CountLeft = leftValue;
    if (leftValue == 0) {
      if (++dotCountLeft >= PEAK_FALL) { // fall rate
        if (peakLeft > 0 ) peakLeft--;
        dotCountLeft = 0;
      }
    } else {
      if (++dotCountRight >= PEAK_FALL) { // fall rate
        if (peakRight > 0 ) peakRight--;
        dotCountRight = 0;
      }
    }
 matrix.drawPixel(0, i, LED_GREEN); 
 Serial.println(  leftValue); // write the changes we just made to the display 
 matrix.writeDisplay(); } // write the changes we just made to the display

то,