When I connect my nano board to USB (+ external 5VDC supply), it runs as I expect, I can hear the relay switching on/off at the correct time.
When I disconnect the USB, and let the nano run on a (cheap) 5VDC supply, the program enters my "if" statement as if the conditions were true all the time.
Hints to why it does that?
#define zapRelay 7 // relay connected to pin 7
#define echoPin 4 // Echo Pin
#define trigPin 3 // Trigger Pin
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
void setup()
{
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(zapRelay, OUTPUT); // sets the digital pin as output
}
void loop()
{
//-----------------------------------ultrasound begin
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
Serial.println("-1");
}
else {
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
}
//Delay 50ms before next reading.
delay(50);
//-----------------------------------ultrasound end
if(distance < 10)
{
Serial.println("Zap");
digitalWrite(zapRelay, HIGH); // sets the relay pin high
Serial.println("Zap ON");
delay(500); //
digitalWrite(zapRelay, LOW);
Serial.println("Zap OFF");
delay(5000);
}
}