Can you please look at my code below, Im trying to call a relay when the distance from the ultrasonic sensor is below 2m (2000). Everything works but whenever the distance is below 2000 the relay doesn't turn on.
Thanks, Shayne
// defines pins numbers
const int trigPin = 37;
const int echoPin = 36;
// defines variables
#define RELAY_ON 0
#define RELAY_OFF 1
#define Relay 5
long duration;
int distance;
void RelayOn()
{
digitalWrite(Relay, RELAY_ON);
}
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
digitalWrite(Relay, RELAY_OFF);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
if (distance < 2000)
{
RelayOn;
}
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
Sorry I forgot to mention that I have an 8ch external relay board.
Pin 5 is connected to one of the relays on the external board which looks for a 0 (on) or a 1 (off).
I will look into turning the relay off afterwards but wanted to get the relay functioning 1st.
I have had all 8 relays working fine in another program but not this one
My other program simply turns the 8 relays on in turn and then back off which works fine.
This is my 1st attempt at trying to turn pin 5 (relay) on with an 'if' statement. Have I gone about it the right way or can I do it differently?
I wanted to call a function in case I decide to turn different relays on at different distances.
What you wrote was perfectly valid C, which is why the compiler didn't complain (it may have given a warning, but warnings are suppressed so as not to scare the noobs).
What your code said was "if distance is less than 2000, examine the pointer to the function RelayOn to see if it is non-zero, then discard that result". The compiler probably optimised that whole section away, because it achieves nothing useful.