HI everyone,
im having an issue using constrain that is starting to drive me crazy
Here is a pitchbend subroutine that I created for a Midi-CV interface that Im building.
int lastVoltage; //stores the DAC val for the note being played (0-65535)
int bendRange =3; //range of notes for pitchbend
void pitchBend (int channel, int bend) {
write_dac(SETUP_INTERNAL_REGISTER, 0, 1);
int voltage = map (bend, -8192, 8191, (0 - (bendRange * NoteScale)), (bendRange * NoteScale) );//
int bendvoltage = lastVoltage + voltage;
write_dac(WRITE_UPDATE_N, 0, bendvoltage);
}
int lastVoltage is the value for the note being played and int "voltage" is a map of the midi pitch bend range (-8192-8192) to int bendRange(3 notes) multiplied by float "NoteScale", which is 1092.25 (DAC max value of 65535 divided by 60 ( max number of notes =5 octaves@ 1v per octave)).
This works well; very smooth pitch bending, except on the highest and lowest notes where "bendVoltage" can excede the DAC range which is 0-65535.
This "confuses" the DAC and results in a very non-musical jump in pitch to the lowest note (0)If i bend up on the highest note and visa versa. I want to limit int "bendVaue", so that that it just stops when it reaches the min /max DAC range of 0-65535. For example, if i am already playing the highest note (65535=5v ) and bend up, the bend value/note played will just stay at 65535 =no bending. I thought that it would be a simple fix by just using constrain to keep bendVoltage within that range like this:
void pitchBend (int channel, int bend) {
write_dac(SETUP_INTERNAL_REGISTER, 0, 1);
int voltage = map (bend, -8192, 8191, (0 - (bendRange * NoteScale)), (bendRange * NoteScale) );//
int bendvoltage = lastVoltage + voltage;
bendvoltage=constrain(bendvoltage,0,65535);
write_dac(WRITE_UPDATE_N, 0, bendvoltage);
}
but frustratingly this actually makes things worse causing the pitch to jump over pretty much the whole keyboard range...about one octave in the middle tracks properly, but applying PBend to any note above or below
causes the note to jump to the opposite direction intended.
Ive even tried replacing the constrain line with:
if (bendvoltage >= 65535) {bendvoltage=65535;}
if (bendvoltage <= 0) {bendvoltage=0;}
...but that has the same results.
Ive spent the better part of the day trying to understand why and trying everything I can think to achieve the same results... with little luck. Im starting to feel stupider the more i think about it. This should be super simple basic stuff. What am I missing here?
The full code is too large to post, but Im only using the midi library... i cant think of any reason or instance that would cause constrain to give results outside of the limits...clearly Im overlooking something tho.
Any help or insight is greatly appreciated.