I have a simple while loop set up in the Setup routine.
I want it to execute a loop until the value of startpoint is changed to 1. The initial value is set to 0.
If I code the loop as "while (startpoint=0)" the loop does not execute. However, if I change the condition to "while (startpoint !=1)" the loop executes as expected.
Can anyone explain why the latter works and the former doesn't? I expect it has something to do with the precision of the value 0.
Thanks
// ---------------------------------------------------------------------------
// Ultrasouind motion control - using an ultrasound HC-SR04 to control a servo based on hand positions
// ---------------------------------------------------------------------------
#include <NewPing.h>
#include <Servo.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 20 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
Servo myservo;
int iterations=7;
int pos = 90;
int prevpos = 90;
int currpos = 0;
int posdelta = 0;
int midpoint = 0;
unsigned int startpoint = 0;
float duration, distance, prevdistance;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
myservo.attach(9); //attach servo to pin 9
// zero servos
myservo.write(prevpos); // set default position (neutral)
// hold hands in position approx 4" away for 4 seconds to set midpoint; turn on green light when stable
Serial.println ("");
Serial.println ("RED");
Serial.println (startpoint);
while (startpoint != 1)
{
duration = sonar.ping_median (iterations); // read duration
distance = (duration/2)*0.0343; // calculate distance
Serial.print ("Setup distance: ");
Serial.println (distance);
delay (2000);
if (distance >= 8 && distance <= 12) // in start position
{
// turn on yellow light; wait
Serial.println ("YELLOW");
delay (4000);
}
if (distance >= 8 && distance <= 12) // still in start position
{
Serial.println ("GREEN");
startpoint = 1; // turn on green light; set start position
}
}
}
void loop ()
{
}