Problem with encoder library and the audio shield

Status
Not open for further replies.
I was using the encoder library with no problems, now, every time that I enable the sgtl5000 my encoder start to have erratic behavior, like going backwards or skipping numbers. I believe that the audio shield is messing up with the interrupts. I'm using 8 encoders, on pins 2,3,4,5,6,7,18,9,10,19,12,20,14,15,16,17. I'm building a synth and I'm using the Teensy 3.2
Although it compiles, I'm getting this message:

Code:
In file included from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Encoder/Encoder.h:41:0,
                 from /Users/gustavosilveira/Dropbox/Arduino (sketches)/GuitarSynth/guitarSynth11_debug/guitarSynth11_debug.ino:74:
/Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Encoder/utility/direct_pin_read.h:7:0: warning: "PIN_TO_BASEREG" redefined
 #define PIN_TO_BASEREG(pin)             (portInputRegister(digitalPinToPort(pin)))
 ^
In file included from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/SD/SD_t3.h:50:0,
                 from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/SD/SD.h:2,
                 from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Audio/play_sd_raw.h:32,
                 from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Audio/Audio.h:99,
                 from /Users/gustavosilveira/Dropbox/Arduino (sketches)/GuitarSynth/guitarSynth11_debug/guitarSynth11_debug.ino:1:
/Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/SD/utility/ioreg.h:46:0: note: this is the location of the previous definition
 #define PIN_TO_BASEREG(pin)             (portOutputRegister(pin))
 ^
In file included from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Encoder/Encoder.h:41:0,
                 from /Users/gustavosilveira/Dropbox/Arduino (sketches)/GuitarSynth/guitarSynth11_debug/guitarSynth11_debug.ino:74:
/Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Encoder/utility/direct_pin_read.h:8:0: warning: "PIN_TO_BITMASK" redefined
 #define PIN_TO_BITMASK(pin)             (digitalPinToBitMask(pin))
 ^
In file included from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/SD/SD_t3.h:50:0,
                 from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/SD/SD.h:2,
                 from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Audio/play_sd_raw.h:32,
                 from /Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/Audio/Audio.h:99,
                 from /Users/gustavosilveira/Dropbox/Arduino (sketches)/GuitarSynth/guitarSynth11_debug/guitarSynth11_debug.ino:1:
/Applications/Arduino 1.8.3.app/Contents/Java/hardware/teensy/avr/libraries/SD/utility/ioreg.h:47:0: note: this is the location of the previous definition
 #define PIN_TO_BITMASK(pin)             (1)
 ^

Code (in order to compile you'll have to comment the "line" class, on lines 72-74):

Code:
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

// GUItool: begin automatically generated code
AudioSynthWaveformDc     dc2;            //xy=3305,4372.5
AudioSynthWaveform       waveform1;      //xy=3332,4065.5
AudioSynthWaveform       waveform4;      //xy=3334,4200.5
AudioSynthWaveform       waveform3;      //xy=3336,4160.5
AudioSynthWaveform       waveform2;      //xy=3337,4119.5
AudioSynthWaveform       filterFreqMod;  //xy=3473,4298.5
AudioEffectEnvelope      envelope3;      //xy=3516,4372.5
AudioMixer4              mixer1;         //xy=3562,4132.5
AudioMixer4              mixer4;         //xy=3706.5000553131104,4260.5000648498535
AudioFilterStateVariable filter1;        //xy=3871,4139.5
AudioSynthWaveform       AMod;           //xy=3976,4334.5
AudioSynthWaveformDc     dc1;            //xy=3986,4402.5
AudioEffectMultiply      multiply1;      //xy=4109,4219.5
AudioMixer4              mixer2;         //xy=4150,4343.5
AudioEffectEnvelope      envelope1;      //xy=4347,4221.5
AudioMixer4              mixer3;         //xy=4512,4240.5
AudioOutputI2S           i2s1;           //xy=4701,4240.5
AudioOutputUSB           usb1;           //xy=4708,4300.5
AudioConnection          patchCord1(dc2, envelope3);
AudioConnection          patchCord2(waveform1, 0, mixer1, 0);
AudioConnection          patchCord3(waveform4, 0, mixer1, 3);
AudioConnection          patchCord4(waveform3, 0, mixer1, 2);
AudioConnection          patchCord5(waveform2, 0, mixer1, 1);
AudioConnection          patchCord6(filterFreqMod, 0, mixer4, 0);
AudioConnection          patchCord7(envelope3, 0, mixer4, 1);
AudioConnection          patchCord8(mixer1, 0, filter1, 0);
AudioConnection          patchCord9(filter1, 0, multiply1, 0);
AudioConnection          patchCord10(AMod, 0, mixer2, 0);
AudioConnection          patchCord11(dc1, 0, mixer2, 1);
AudioConnection          patchCord12(multiply1, envelope1);
AudioConnection          patchCord13(mixer2, 0, multiply1, 1);
AudioConnection          patchCord14(envelope1, 0, mixer3, 0);
AudioConnection          patchCord15(mixer3, 0, i2s1, 0);
AudioConnection          patchCord16(mixer3, 0, i2s1, 1);
AudioConnection          patchCord17(mixer3, 0, usb1, 0);
AudioConnection          patchCord18(mixer3, 0, usb1, 1);
AudioControlSGTL5000     sgtl5000_1;     //xy=4471,4405.5
// GUItool: end automatically generated code


/////////////////////////////////////////////
// PWM bit shifter
// You can choose the latch pin yourself.
const int ShiftPWM_latchPin = 8;

// ** uncomment this part to NOT use the SPI port and change the pin numbers. This is 2.5x slower **
#define SHIFTPWM_NOSPI
const int ShiftPWM_dataPin = 11;
const int ShiftPWM_clockPin = 13;

// If your LED's turn on if the pin is low, set this to true, otherwise set it to false.
const bool ShiftPWM_invertOutputs = true;

// You can enable the option below to shift the PWM phase of each shift register by 8 compared to the previous.
// This will slightly increase the interrupt load, but will prevent all PWM signals from becoming high at the same time.
// This will be a bit easier on your power supply, because the current peaks are distributed.
const bool ShiftPWM_balanceLoad = false;
/////////////////////////////////////////////

/////////////////////////////////////////////
// line - creates a smooth line between one value and the other
line portamentoLine; //create a line for portamento
line filterLine; //cretaes a line for the cuttof
line volumeLine; //cretaes a line for the volume

#include <ShiftPWM.h>   // include ShiftPWM.h after setting the pins!
#include <Encoder.h>  //makes all the work for you on reading the encoder
#include <Multiplexer4067.h> // Multiplexer CD4067 library >> https://github.com/sumotoy/Multiplexer4067
//#include <AnalogSmooth.h> // Smooths the analog input (avarages)

/////////////////////////////////////////////
// Multiplexer
Multiplexer4067 multiplexer = Multiplexer4067(0, 1, 22, 21, A10);

/////////////////////////////////////////////
// Oscilators
int minFreq = 40;
int maxFreq = 2000;

// OSCs
const int oscN = 4;
int oscWaveForm[oscN] = {WAVEFORM_SAWTOOTH, WAVEFORM_SQUARE, WAVEFORM_TRIANGLE, WAVEFORM_SINE}; // 0 = Saw; 1 = square; 2 = tri; 3 = sine
float oscOctave[oscN][3] = {{1, 2, 4}, {1, 2, 4}, {1, 2, 4}, {0.5, 0.25}}; //Use this numbers to multipky the frequencies, so you get different octaves
float oscFreq[oscN] = {300, 300, 300, 300};
int oscLastFreq[oscN] = {300, 300, 300, 300};
float oscLevel[oscN] = {0.1, 0.1, 0.1, 0.1};
float oscPwm[oscN] = {0.5, 0.5, 0.5, 0.5};
int oscOctaveIndex[oscN] = {0, 0, 0, 0};

/////////////////////////////////////////////
//line
byte glide = 1;
int portamentoLineTime = 10;
int filterLineTime = 20;
int volumeLineTime = 10;

/////////////////////////////////////////////
//Filter
int filterFreq = 15000;
float filterQ = 0.7; //from 0.7-5.0
float filterOctaves = 2;
//boolean filterMoved = false;

/////////////////////////////////////////////
// filterFreqMod
int filterLFOosc = WAVEFORM_SINE;
float filterLFOfreq = 2;
float filterLFOlevel = 1;

/////////////////////////////////////////////
// amplitude modulation
int AMODosc = WAVEFORM_SINE;
float AMODfreq = 7;
float AMODlevel = 0;
boolean ampModOnOff = false;

/////////////////////////////////////////////
//dc
int dcLevel = 1 + AMODlevel; //dc is used to invert the level of the AM

/////////////////////////////////////////////
// mixers
float mixer1Gain[oscN] = {0.5, 0, 0, 0};
//mixer 3 - final mix
float mixer3Gain[oscN] = {0.7, 0, 0, 0};
// Amp modulation mix
float mixer2Gain[oscN] = {0, 1, 0, 0};
// mixers
float mixer4Gain[oscN] = {0, 0, 0, 0}; // Filter's LFO - Filter's ADSR


//// feedback delay mixer 1
//float fdMixer1Gain1 = 0.7; // wet signal
//float fdMixer1Gain0 = 1 - fdMixer1Gain1; // dry signal
////mixers out LR
//float mixerOutGain = 0.6;
////mixer out mono
//float mixerOutMonoGain = 1;

/////////////////////////////////////////////
// note on/off
boolean noteIsPlaying = false; // stores if the note ins playing or not

/////////////////////////////////////////////
// delay
int delayTime = 100; // milisseconds

/////////////////////////////////////////////
// Leds
const byte ledNum = 24; // total number of leds used
unsigned char maxBrightness = 255;
unsigned char pwmFrequency = 75;
unsigned int numRegisters = 3;
unsigned int numOutputs = numRegisters * 8;
unsigned int numRGBLeds = numRegisters * 8 / 3;
unsigned int fadingMode = 0; //start with all LED's off.
byte encoderLed[ledNum] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23};

/////////////////////////////////////////////
// Encoders
const int encoderN = 8; //number of encoders
const int encoderNPins = encoderN * 2; //number of pins used by the encoders
const int banksN = 2; //number of banks
//this array stores the two pins of every encoder
Encoder encoder[encoderN] = {{2, 3}, {4, 5}, {6, 7}, {18, 9}, {10, 19}, {12, 20}, {14, 15}, {16, 17}};
int lastEncoderValue[banksN][encoderN] = {127};
int encoderValue[banksN][encoderN] = {127};

/////////////////////////////////////////////
//Buttons
const byte buttonN = 1;
const byte totalButtons = encoderN + buttonN;

byte buttonPin[totalButtons] = {0, 1, 2, 3, 4, 5, 6, 7, 14};
int buttonVal[totalButtons] = {0};
int buttonCState[totalButtons] = {0}; // estado atual da porta digital
int buttonPState[totalButtons] = {0}; // estado previo da porta digital

/////////////////////////////////////////////
// Ribbon
const byte ribbonN = 4;
byte ribbonPin[ribbonN] = {8, 9, 10, 11};
int ribbonVal[ribbonN] = {0};
float ribbonFreq[ribbonN] = {659.256, 493.883, 391.995, 293.665}; // frequencies of each ribbon

/////////////////////////////////////////////
// Potentiometers
const int NPots = 2; // *coloque aqui o numero de entradas analogicas utilizadas
const int potPin[NPots] = {12, 13}; // *neste array coloque na ordem desejada os pinos das portas analogicas utilizadas
float potCState[NPots] = {0}; // estado atual da porta analogica
float potPState[NPots] = {0}; // estado previo da porta analogica
int potVar = 0; // variacao entre o valor do estado previo e o atual da porta analogica

int midiCState[NPots] = {0}; // Current state of the midi value
int midiPState[NPots] = {0}; // Previous state of the midi value

unsigned long TIMEOUT = 300; //* Amount of time the potentiometer will be read after it exceeds the varThreshold
int varThreshold = 6; //* Threshold for the potentiometer signal variation
boolean potMoving = true; // If the potentiometer is moving
unsigned long PTime[NPots] = {0}; // Previously stored time
unsigned long timer[NPots] = {0}; // Stores the time that has elapsed since the timer was reset

/////////////////////////////////////////////
// debounce
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 20;    // the debounce time; increase if the output flickers

/////////////////////////////////////////////
// Midi values
int midiMax = 254;
int midiCh = 1;
int note = 36;

/////////////////////////////////////////////
// for the encoder banks
int Bank = 0;
int lastBank = 0;



/////////////////////////////////////////////
// setup
void setup() {

  Serial.begin(115200);
Serial.println("START");
  multiplexer.begin(); // initialize o multiplexer

  /////////////////////////////////////////////
  // Leds
  // Sets the number of 8-bit registers that are used.
  ShiftPWM.SetAmountOfRegisters(numRegisters);
  // SetPinGrouping allows flexibility in LED setup.
  // If your LED's are connected like this: RRRRGGGGBBBBRRRRGGGGBBBB, use SetPinGrouping(4).
  ShiftPWM.SetPinGrouping(1); //This is the default, but I added here to demonstrate how to use the funtion
  ShiftPWM.Start(pwmFrequency, maxBrightness);
  //ShiftPWM.SetAll(0);

  //  for (int i = 0; i < encoderN; i++) {
  //    ShiftPWM.SetRGB(i, encoderValue[Bank][i], 0, 255 - encoderValue[Bank][i]);
  //  }

  /////////////////////////////////////////////
  // Encoders
  for (int i = 0; i < encoderN; i++) {
    encoder[i].write(127);
  }

  for (int z = 0; z < banksN; z++) {
    for (int i = 0; i < encoderN; i++) {
      lastEncoderValue[z][i] = {127};
      encoderValue[z][i] = {127};
    }
  }

  for (int i = 0; i < encoderN; i++) { //write leds to the previous bank values
    ShiftPWM.SetRGB(i, encoderValue[Bank][i], 0, 255 - encoderValue[Bank][i]);
  }

  /////////////////////////////////////////////
  // Audio stuff

  AudioMemory(120);
  sgtl5000_1.enable(); //starts sgtl5000
  sgtl5000_1.volume(0.9); //headphones level
  sgtl5000_1.lineOutLevel(30); //line level 13-31
  //  sgtl5000_1.audioPostProcessorEnable();
  //  sgtl5000_1.surroundSoundEnable(); // enables surround
  //  sgtl5000_1.surroundSound(7, 3); // how much surround 0-7


  //start osc 1
  //  setOsc1(4); // 1 = saw; 2 = sqr; 3 = tri; 4 = sin; 5 = pulse
  //  blSaw1.begin(osc1level, osc1freq, osc1);
  //  blSaw1.begin(osc1freq, osc1level);

  //start oscs
  waveform1.begin(oscLevel[0], (oscFreq[0]*oscOctave[0][oscOctaveIndex[0]]), oscWaveForm[0]);
  waveform2.begin(oscLevel[1], (oscFreq[1]*oscOctave[1][oscOctaveIndex[0]]), oscWaveForm[1]);
  waveform3.begin(oscLevel[2], (oscFreq[2]*oscOctave[2][oscOctaveIndex[0]]), oscWaveForm[2]);
  waveform4.begin(oscLevel[3], (oscFreq[3]*oscOctave[3][oscOctaveIndex[0]]), oscWaveForm[3]);

  //start filterFreqMod
  filterFreqMod.begin(filterLFOlevel, filterLFOfreq, oscWaveForm[3]);

  //start amplitude modulation
  AMod.begin(AMODlevel, AMODfreq, oscWaveForm[3]);

  //dc - for controllinf ampMod amplitude
  dc1.amplitude(dcLevel);
  dc2.amplitude(1.0);

  //start mixer 1 - for OCSs
  for (int i = 0; i < oscN; i++) {
    mixer1.gain(i, mixer1Gain[i]);
  }
  //start mixer 2 - amp mod
  for (int i = 0; i < oscN; i++) {
    mixer2.gain(i, mixer2Gain[i]);
  }
  //start mixer 3 - atenuates signal from filter
  for (int i = 0; i < oscN; i++) {
    mixer3.gain(i, mixer3Gain[i]);
  }
  //start mixer 4 - LFO and ADSR for the filter
  for (int i = 0; i < oscN; i++) {
    mixer4.gain(i, mixer4Gain[i]);
  }


  //  //filter
  filter1.octaveControl(filterOctaves);
  filter1.frequency(filterFreq);

  // MIDI IN
  //  usbMIDI.setHandleControlChange(OnControlChange);
  //  usbMIDI.setHandleNoteOn(OnNoteOn);
  //  usbMIDI.setHandleNoteOff(OnNoteOff);
  //  usbMIDI.setHandleVelocityChange(OnVelocityChange);

  // Envelelope - Sound envelope
  envelope1.attack(5);
  envelope1.decay(5);
  envelope1.sustain(1);
  envelope1.release(5);

  // Envelelope - Filter envelope
  envelope3.attack(200);
  envelope3.decay(100);
  envelope3.sustain(1);
  envelope3.release(5);

  //Line
  volumeLine.begin();
  filterLine.begin();

  setWaveform(0);
Serial.println("END");
}

/////////////////////////////////////////////
// loop
void loop() {
//Serial.println("LOOP");
  updateButtons();
  updateEncoders();  
  updateRibbons();
  updatePotentiometers();

  //volumeLine.update();

  //  filterLine.update();
  //  filter1.frequency(filterLine.getCurrentValue());

}

/////////////////////////////////////////////
// POTENTIOMETERS
void updatePotentiometers() {

  for (int i = 0; i < NPots; i++) { // Loops through all the potentiometers

    //    float analog = analogRead(multiplexer.readChannel(potPin[i])); //reads analog pin
    //    float analogSmooth = as10.smooth(analog); //smooths analog pin
    //    potCState[i] = analogSmooth;

    potCState[i] = multiplexer.readChannel(potPin[i]); // Reads the pot and stores it in the potCState variable
    midiCState[i] = map(potCState[i], 0, 1023, 0, 127); // Maps the reading of the potCState to a value usable in midi


    potVar = abs(potCState[i] - potPState[i]); // Calculates the absolute value between the difference between the current and previous state of the pot

    if (potVar > varThreshold) { // Opens the gate if the potentiometer variation is greater than the threshold
      PTime[i] = millis(); // Stores the previous time
    }

    timer[i] = millis() - PTime[i]; // Resets the timer 11000 - 11000 = 0ms

    if (timer[i] < TIMEOUT) { // If the timer is less than the maximum allowed time it means that the potentiometer is still moving
      potMoving = true;
    }
    else {
      potMoving = false;
    }

    if (potMoving == true) { // If the potentiometer is still moving, send the change control

      if (midiPState[i] != midiCState[i]) { //sends midi cc
        usbMIDI.sendControlChange(11 + i, midiCState[i], midiCh);
      }
      if (potCState[i] != potPState[i]) { // for using with the synth
                
        //prints data if pot moves
        Serial.print("Joytick ");
        Serial.print(i);
        Serial.print(": ");
        Serial.print((int)potCState[i]);
        Serial.print("  ");
        Serial.println();
      }

      potPState[i] = potCState[i]; // Stores the current reading of the potentiometer to compare with the next
      midiPState[i] = midiCState[i];

    }

  }
}


////////////////////////////////////////////
//read ribbons
void readRibbons() {

  for (int i = 0; i < ribbonN; i++) {
    ribbonVal[i] = multiplexer.readChannel(ribbonPin[i]);
    //Serial.print(ribbonVal[i]); Serial.print("  ");
  }
  //Serial.println();
}

////////////////////////////////////////////
//update ribbons
void updateRibbons() {
  //float oscLastFreq;

  readRibbons();

  for (int i = 0; i < ribbonN; i++) {

    if (ribbonVal[i] > 10) {
      
      // chooses the frequency and multiply by the correct octave
      waveform1.frequency(map(ribbonVal[i], 0, 1023, ribbonFreq[i] * oscOctave[0][oscOctaveIndex[0]], (ribbonFreq[i] * 2.5)*oscOctave[0][oscOctaveIndex[0]]));
      waveform2.frequency(map(ribbonVal[i], 0, 1023, ribbonFreq[i] * oscOctave[1][oscOctaveIndex[1]], (ribbonFreq[i] * 2.5)*oscOctave[1][oscOctaveIndex[1]]));
      waveform3.frequency(map(ribbonVal[i], 0, 1023, ribbonFreq[i] * oscOctave[2][oscOctaveIndex[2]], (ribbonFreq[i] * 2.5)*oscOctave[2][oscOctaveIndex[2]]));
      waveform4.frequency(map(ribbonVal[i], 0, 1023, ribbonFreq[i] * oscOctave[3][oscOctaveIndex[3]], (ribbonFreq[i] * 2.5)*oscOctave[3][oscOctaveIndex[3]]));


      //just gives a note On if it got a note off before
      // this way it doesn't play a thousand note ons
      if (noteIsPlaying == false) {

        envelope1.noteOn();
        envelope3.noteOn();
        //oscLastFreq = ribbonVal[i];
        // Serial.println(oscLastFreq);
        noteIsPlaying = true;
        Serial.println("note on");
      }
    }
  }

  if ((ribbonVal[0] < 5) && (ribbonVal[1] < 5) && (ribbonVal[2] < 5) && (ribbonVal[3] < 5)) {
    if (noteIsPlaying == true) {
      //waveform1.frequency(oscLastFreq);
      //Serial.println(oscLastFreq);

      envelope1.noteOff();
      envelope3.noteOff();
      noteIsPlaying = false;
      Serial.println("note off");
    }
  }

}

////////////////////////////////////////////
//read encoder buttons
void readButtons() {

  for (int i = 0; i < totalButtons; i++) {
    buttonVal[i] = multiplexer.readChannel(buttonPin[i]);

    if (i == 8) { //inverts the joystick button value
      buttonVal[i] = 1023 - buttonVal[i];
    }
  }

  //Serial.println(buttonVal[8]);

  for (int i = 0; i < totalButtons; i++) {
    if (buttonVal[i] > 1000) {
      buttonCState[i] = HIGH;
    }
    else {
      buttonCState[i] = LOW;
    }
  }

}

/////////////////////////////////////////////
// read buttons
void updateButtons() {

  readButtons();

  for (int i = 0; i < totalButtons; i++) {

    if ((millis() - lastDebounceTime) > debounceDelay) {

      if (buttonCState[i] != buttonPState[i]) {
        lastDebounceTime = millis();

        if (buttonCState[i] == HIGH) {

          if (i < encoderN) { //encoder buttons
            Serial.print("Button: "); Serial.print(i + 1); Serial.println(" On");
            usbMIDI.sendNoteOn(note + i, 127, midiCh); // envia NoteOn(nota, velocity, canal midi)
            // Serial.print("Note: "); Serial.print(note + i); Serial.println(" On");
            buttonPState[i] = buttonCState[i];
          }
          if (i == 8) { //joystick button
            changeBank();
            buttonPState[i] = buttonCState[i];
          }

        }
        else {

          usbMIDI.sendNoteOn(note + i, 0, midiCh);
          Serial.print("Button: "); Serial.print(i + 1); Serial.println(" Off");
          //  Serial.print("Note: "); Serial.print(note + i); Serial.println(" Off");
          buttonPState[i] = buttonCState[i];
        }
      }
    }

  }

}

////////////////////////////////////////////
//read encoder values
void readEncoders() { //read encoder

  for (int i = 0; i < encoderN; i++) {
    encoderValue[Bank][i] = encoder[i].read();
  }
}

////////////////////////////////////////////
//write encoder values
void updateEncoders() { //do whatever needs to be done with the encoder values

  readEncoders();

  for (int i = 0; i < encoderN; i++) {
    if (encoderValue[Bank][i] != lastEncoderValue[Bank][i]) {

      ShiftPWM.SetRGB(i, encoderValue[Bank][i], 0, 255 - encoderValue[Bank][i]);

      checkEncoderValue(i); //check if it's > than 255, or < then 0
      sendCC(i);
      printEncoderValue(i);
      writeEncoderValue(i);
      lastEncoderValue[Bank][i] = encoderValue[Bank][i];
    }
  }

}

////////////////////////////////////////////
//sends encoder's midi cc
void sendCC(byte i)  {

  usbMIDI.sendControlChange(i, map(encoderValue[Bank][i], 0, 255, 0, 127), Bank + 1);

}

////////////////////////////////////////////
//check if it's > than 255, or < then 0
void checkEncoderValue(int i) {

  if (encoderValue[Bank][i] > 254) {
    encoderValue[Bank][i] = 254;
    encoder[i].write(254);
  }
  if (encoderValue[Bank][i] < 1) {
    encoderValue[Bank][i] = 1;
    encoder[i].write(1);
  }
}

void writeEncoderValue(byte i) {

  // float encoderValueTemp = float(encoderValue[i]);

  if (Bank == 0) {
    if(i<4) {
      mixer1Gain[i] = mapfloat(encoderValue[0][i], 1, 255, 0, 1);
      mixer1.gain(i, mixer1Gain[i]);
      Serial.print("Gain: ");
      Serial.println(mixer1Gain[i]);
    }
  }

}


////////////////////////////////////////////
//print encoder values in the serial monitor
void printEncoderValue(byte i) {
  Serial.print("Bank: "); Serial.print(Bank); Serial.print("  ");
  Serial.print("Encoder "); Serial.print(i); Serial.print(": ");
  Serial.println(encoderValue[Bank][i]);
}

////////////////////////////////////////////
// Changes the bank of the encoders
void changeBank() {

  Bank = !Bank;

  Serial.print("Bank: ");
  Serial.println(Bank);

  //  switch (Serial.read()) {
  //    case '0':
  //      Bank = 0;
  //      Serial.print("Bank: ");
  //      Serial.println(Bank);
  //      break;
  //    case '1':
  //      Bank = 1;
  //      Serial.print("Bank: ");
  //      Serial.println(Bank);
  //      break;
  //    case '2':
  //      Bank = 2;
  //      Serial.print("Bank: ");
  //      Serial.println(Bank);
  //      break;
  //    default:
  //      Serial.print("*Invalid number*");
  //      break;
  //  }

  for (int i = 0; i < encoderN; i++) {
    encoder[i].write(encoderValue[Bank][i]);
  }

  for (int i = 0; i < encoderN; i++) { //write leds to the previous bank values
    ShiftPWM.SetRGB(i, encoderValue[Bank][i], 0, 255 - encoderValue[Bank][i]);
  }

}

/////////////////////////////////////////////
// sets the waveform
int setWaveform (int a) {
  int waveForm = 0;
  
  switch (a) {
    case 0:
      waveForm = WAVEFORM_SAWTOOTH;
      break;
    case 1:
      waveForm = WAVEFORM_SQUARE;
      break;
    case 2:
      waveForm = WAVEFORM_TRIANGLE;
      break;
    case 3:
      waveForm = WAVEFORM_SINE;
      break;
  }

  return waveForm;
}

/////////////////////////////////////////////
// Map float function
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
 
Status
Not open for further replies.
Back
Top