I am working on a music project that uses multiple R144-GP2Y0A02YK 0F IR distance sensors. Basically what it does so far is read the sensor value (which returns values in the 1-500 range. If my hand is over it, it will play a midi note but as long as I dont remove my hand from the sensor's usable airspace, then it will output pitch bend data to bend the note as my hand moves up and down. When my hand is removed, it shuts off the note.
The problem I'm having is that I get bouncing between note on and off when my hand is held right at the upper or lower limits of the range.
I tried taking multiple readings and averaging them but it still bounces. I tried adding a small delay but still the problem persists. If any of you that use variable sensors can give me a good programming approach to resolve this, I would really appreciate it. BTW let me know if I posted this to the wrong area. Im new to the board and wasn't sure if this should go in the programming area instead...
Here is the code for stage 1 of my project. It was written for the MEGA2560 so that I could debug using a second serial line out to the serial monitor:
code
int sensor1 = 19;
int prevsensor1 = 19;
int sound1 = 30;
int velocity1 = 127;
int note1 = 50;
int pitch1 = 64;
int prevpitch1 = 0;
int onoff1 = 0;
int ch = 1;
int pitchdif1 = 0;
void setup()
{
Serial2.begin(31250); //Initialize MIDI serial communication
Serial.begin(9600); //Serial Monitor baud for debugging
// the followig serial writes are do add chorus delay and reverb to the midi notes
Serial2.write(0xB1);
Serial2.write(0x5E);
Serial2.write(30);
Serial2.write(0xB1);
Serial2.write(0x5B);
Serial2.write(100);
Serial2.write(0xB1);
Serial2.write(0x5D);
Serial2.write(80);
}
void loop()
{ //Serial.println("LOOPAROUND");
// Check sensor and filter results
//filter by averaging then c0nstraining output (150-450)
sensor1= (analogRead(A0)+analogRead(A0)+analogRead(A0)+analogRead(A0))/4;
constrain(sensor1, 50, 450);
Serial.println(sensor1);
if (sensor1 < 150 || sensor1 >450) //OUT OF RANGE
{
velocity1 = 0;
playMidiNote(note1,velocity1,1,sound1);
onoff1 = 0;
}
else // IN RANGE
{
if (onoff1 == 0)
{
velocity1 = 127;
playMidiNote(note1, velocity1, ch, sound1);
pitchdif1 = sensor1;
onoff1 = 1;
}
if (onoff1 == 1)
{
pitch1 = 64+(pitchdif1/4)-(sensor1/4);
constrain(pitch1, 5, 120);
Serial2.write(0xE1);
Serial2.write(127);
Serial2.write(pitch1);
delay(35);
}
}
}
void playMidiNote(byte note, int velocity, int ch, int snd) // subroutine for playing note
//Plays a midi note on ch
{
Serial2.write(192+ch); //code to call change of sound
Serial2.write(snd); //code to set new sound to sound #41
Serial2.write(144+ch);// code to call up note change
Serial2.write(note);// specifies which note
Serial2.write(velocity); //sets volume for the note 0-127
delay(35);
}