I am relatively new to coding in C, but I am working on a MIDI project. I have a working project that uses a potentiometer to send a three byte MIDI cc message to control traktor pro. It is in a constant loop, and I am worried that it will flood my computer with MIDI messages. How what can i do to my code to only send a MIDI message when i change the value on the potentiometer. Here is just a sample of a basic program to read a potentiometer.
I did not check the code, but it looks right. What should I add to this sample to only serial print the potentiometerVal when it changes. Please help me on this. I have everything working with several potentiometers and I am able to control traktor seamlessly. I just feel like I will overload my computer when I add around 25 potentiometers and 25 buttons. Thank you.
Are you using the Serial as the interface to the computer? If so, it runs at a significantly lower rate than MIDI -- IIRC, MIDI runs at 32 kbps or so.
If the Serial class is blocking (which I think it is?) then there is no risk that you will "flood" the MIDI wire with more than it can "take." However, as already suggested, you should check what the last value sent was, and only send a new value if the value read is different from the previous value.
Another useful mechanism is to use a time step. Remember when last you sent a message, and only send a message if X time has passed (say, 10 milliseconds).
So, something like:
unsigned long lastTime = 0;
unsigned int lastValue = 0xfffeU; // force a send initially
void loop()
{
unsigned long now = millis();
if (now - lastTime >= 10) {
unsigned int value = read_and_calculate_your_value();
if (value != lastValue) {
lastTime = now;
lastValue = value;
send_midi_controller_bytes(value);
}
}
}
I tried the code, but it only would stop displaying the 0-1023 values if the potentiometer was 0, or all the way to the left, or 1023, all the way to the right. Any value in between would flood the serial terminal. Any ideas? Below is the code.
int NewVal = 0;
int OldVal = 0;
int potentiometerPin = A0;
void setup(){
Serial.begin(9600);
}
void loop(){
NewVal = analogRead (potentiometerPin); // left this out by accident
Do you get the same numbers coming out? Or do they vary by a little?
Try slowing down the processing some simulating the reading of a lot more stuff:
int NewVal = 0;
int OldVal = 0;
int potentiometerPin = A0;
void setup(){
Serial.begin(9600);
}
void loop(){
for (byte x = 0; x<51; x=x+1){
if (x== 22){ // random selection
delay(1); // little pause
NewVal = analogRead (potentiometerPin); // take a new reading, read it twice so has time to settle
NewVal = analogRead (potentiometerPin); //
if(NewVal == OldVal){
// no change? do nothing
}
else{
OldVal = NewVal; // store the new reading
Serial.println(NewVal);
}
}
else{
delay(1); // simulate reading other channels
}
//pause for the other channels
} // end channel cycling
} // end void