When you are testing buttons within a loop that runs repeatedly, there's no need for lengthy monolithic delays like wait1Msec(15), and no need to store and test start times, like time = time1[T1] and time1[T1] - time > 50.
Instead, you can change your loop so it takes at least some small time (as via wait1Msec(1) in following code sample), and add a holdoff counter that inhibits sensor testing during probable bounce periods.
string last;
long bumpCount = 0;
byte holdoff=0, isbump=0;
task main() {
while (SensorValue(go) != 1) {
string presses = bumpCount;
if(presses != last) {
writeDebugStreamLine(presses);
}
last = presses;
wait1Msec(1);
if (holdoff) { // Ignore bump sensor during holdoff
--holdoff;
} else {
if (SensorValue(bump)) {
if (isbump==0) {
++bumpCount; // Count a new closure
holdoff = 40; // Start a holdoff period
}
isbump = 1; // We detected bump is on
} else {
isbump = 0; // We detected bump is off
}
}
}
}
The code shown above acts as follows:
• Initially, bumpCount, holdoff, and isbump are zero, to indicate we haven't counted any bumps, are not inhibiting bump sensing, and think the bump sensor is off.
• Under initial conditions and while the bump sensor is off, we will pass through the outer while loop, each time waiting a millisecond, then taking the else branch of if (holdoff) and the else branch of if (SensorValue(bump)), so will repeatedly set isbump = 0, thus maintaining initial conditions.
• When the bump sensor goes on, we take the first branch of if (SensorValue(bump)). From initial conditions, isbump==0 so we increment bumpCount and set holdoff = 40. Lastly, set isbump = 1 to reflect sensor state.
• During the next 40 milliseconds or so (that is, during the holdoff period) we repeatedly decrement holdoff, while ignoring the bump sensor, which may bounce a number of times or not, as it pleases, but we don't care.
• After the holdoff period, SensorValue(bump) may still be true. But since isbump==0 is false, we don't change bumpCount.
• If the bump sensor opens after the holdoff, isbump will go zero, restoring two of the initial conditions. If it opens during the holdoff and stays open, the same thing happens at the end of the holdoff.