This is an addendum to an earlier post, but it's a fresh topic because it's more general, I believe. I'm doing my best to get a handle on looping and conditionals and I'm hopeful that this bit of code will represent the correct objective.
// some code at beginning of loop() containing ping.fire() and allocation to variable toShift
while(toShift < 36 && toShift > 0) // toShift is value from ultrasonic sensor, trigger camera 1 under 36"
{
digitalWrite(cam_1, HIGH); // This block triggers auto-focus
delay(camDelay); //
digitalWrite(cam_1, LOW); // This block triggers shutter
delay(camDelay); // camDelay is about 1/4 second, slow enough for auto focus, fast enough for good lighting conditions
cam2Flag = 1; // cam2Flag set to trip 2nd cam when loop done
ping.fire(); // read distance again to exit while loop when appropriate.
int toShift = ping.inches(); //
}
while(toShift > 36 && cam2Flag == 1) // after distance is exceeded and after cam1 is tripped
{
for (int i = 0; i < 4; i++) // fire camera 4 times if distance remains open and if camera 1 has tripped
{
digitalWrite(cam_2, HIGH); // same as above
delay(camDelay); //
digitalWrite(cam_2, LOW); //
delay(camDelay); //
ping.fire(); // check distance to stop cam2 triggers if distance is less than 36"
int toShift = ping.inches(); //
}
cam2Flag = 0; // reset flag for cam2, don't fire if camera 1 isn't tripped first
}
The project is two cameras, a Ping))) ultrasonic sensor and a digital display. The digital display is working properly and was the bulk of the code, so it's omitted here.
When an object comes into range of the sensor, but greater than 36" away, nothing happens. I'm hoping that the cam2Flag properly represents that condition.
When an object comes within 36" of the sensor, camera one trips every half second until it moves away, at which point, the original condition is met, but the flag for camera 2 is set, causing the second while( ) loop to execute.
If my understanding is correct, the inclusion of the ping.fire() code is what provides an exit from the first while( ) loop and also from the second while( ) loop.
The second while( ) loop is to cause camera two to trigger four times and return control to the main loop. If the distance returned by the sensor is less than 36", control returns immediately to the main loop, regardless of the 4x counter. It appears that if such a circumstance arises, the cam2 flag does not get reset. Considering that the reason to exit the second loop is based on the distance line being crossed, the cam2 flag would become set during the first loop anyway.
Is this how the code appears to function as written?