Controlling relay with HC-SR04 Ultrasonic Distance Sensor

Hi guys,

I am trying to control a 8 channel relay with with two ultrasonic distance sensors. Basically what I want to do is have one sensor on top of my stair and one at the bottom. If for eg. downstairs sensor detects distance is >70 then it will turn on the relays (1,2,3,4,5,6,7,8,9,10,11,12,13) each relay will turn on one after the other with delay of 500ms and then at the end all will stay on for 5 sec. If the top sensor will detect distance >70 then it will turn on the relays (13,12,11,10,9,8,7,6,5,4,3,2,1).

Basically this code is close enough to what I am trying to do.

/*
 * Arduino code to control 16 channel relay with Arduino UNO
 * 
 * Written by Ahmad Shamshiri for Robojax.com on Sunday Oct 08, 2018 
 * at 10:35 in Ajax, Ontario, Canada
 * Watch video instruction for this code: https://youtu.be/Q9aBI4ELKC4
 * 
 * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.* 
 * This code has been download from Robojax.com
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


const int controlPin[16] = {2,3,4,5,6,7,8,9,10,11,12,A0,A1,A2,A3,A4}; // define pins

const int triggerType = LOW;// your relay type
int loopDelay = 1000;// delay in loop
int tmpStat =1;


void setup() {
  for(int i=0; i<16; i++)
  {
    pinMode(controlPin[i], OUTPUT);// set pin as output
    if(triggerType ==LOW){
      digitalWrite(controlPin[i], HIGH); // set initial state OFF for low trigger relay
    }else{
       digitalWrite(controlPin[i], LOW); // set initial state OFF for high trigger relay     
    }
  }
  
  Serial.begin(9600);// initialize serial monitor with 9600 baud
}

void loop() {

  for(int i=0; i<16; i++)
  {

   channelControl(i,tmpStat,200);// turn each relay ON for 200ms

    
  }
  if(tmpStat)
  {
    tmpStat=0;
  }else{
    tmpStat=1;
  }
 Serial.println("===============");
 //channelControl(6,1, 2000); // turn relay 7 ON for 2 seconds
 //channelControl(6,0, 5000); // turn relay 7 OFF for 5 seconds
 //channelControl(9,1, 3000); // turn relay 10 OFF forC ever

 delay(loopDelay);// wait for loopDelay ms
          
}

/*
 * funciton: channelControl
 * turns ON or OFF specific relay channel
 * @param relayChannel is integer value channel from 0 to 15
 * @param action is 1 for ON or 0 for OFF
 * @param t is time in melisecond
 */
void channelControl(int relayChannel, int action, int t)
{
  int state =LOW;
  String statTXT =" ON";
  if(triggerType == LOW)
  {    
    if (action ==0)// if OFF requested
    {
      state = HIGH;
      statTXT = " OFF";
    }
    digitalWrite(controlPin[relayChannel], state);
    if(t >0 )
    {
      delay(t);
    }
       Serial.print ("Channel: ");
       Serial.print(relayChannel); 
       Serial.print(statTXT);
       Serial.print(" - "); 
       Serial.println(t);        
  }else{
    if (action ==1)// if ON requested
    {
      state = HIGH;     
    }else{
      statTXT = " OFF";    
    }
    digitalWrite(controlPin[relayChannel], state);
    if(t >0 )
    {
      delay(t);
    }
       Serial.print ("Channel: ");
       Serial.print(relayChannel); 
       Serial.print(statTXT);
       Serial.print(" - "); 
       Serial.println(t);    
  }

}

But this is on a loop and I would want it to run once when the sensor detects someone.

This is another code I found that that uses the sensor to turn on one relay.

#define trigPin 6 //Define the HC-SE04 triger on pin 6 on the arduino
#define echoPin 5 //Define the HC-SE04 echo on pin 5 on the arduino

#define bulb 9 //Define the relay signal on pin 9 on the arduino

void setup()

{

Serial.begin (9600); //Start the serial monitor

pinMode(trigPin, OUTPUT); //set the trigpin to output

pinMode(echoPin, INPUT); //set the echopin to input

pinMode (bulb, OUTPUT); //set the bulb on pin 9 to output

}

void loop()

{

int duration, distance; //Define two intregers duration and distance to be used to save data

digitalWrite(trigPin, HIGH); //write a digital high to the trigpin to send out the pulse

delayMicroseconds(500); //wait half a millisecond

digitalWrite(trigPin, LOW); //turn off the trigpin

duration = pulseIn(echoPin, HIGH); //measure the time using pulsein when the echo receives a signal set it to high

distance = (duration/2) / 29.1; //distance is the duration devided by 2 becasue the signal traveled from the trigpin then back to the echo pin, then divide by 29.1 to convert to centimeters

if (distance < 13) //if the distance is less than 13 CM

{

Light(); //execute the Light subroutine below

}

Serial.print(distance); //Dispaly the distance on the serial monitor

Serial.println(" CM"); //in centimeters

delay(500); //delay half a second

}

void Light() //Start the Light subroutine

{ digitalWrite(bulb, HIGH); //turn on the light

delay (15000); //wait 15 seconds

digitalWrite(bulb, LOW); //turn off the light

}

Is there anyway to make one out of it to do what I have in mind ?

Yes, there is a way...

YOU combine them together in an attempt to get the code to do what you want. If you run into problems, you post YOUR attempt (using code tags) along with any errors and describe what the code is doing vs. what you would like it to do.

Then people help you...

Here was my attempt when I tried to do it.

#define trigPin 6 //Define the HC-SE04 triger on pin 6 on the arduino
#define echoPin 5 //Define the HC-SE04 echo on pin 5 on the arduino
const int controlPin[8] = {4,5,6,7,8,9,10,11}; // define pins

const int triggerType = LOW;// your relay type
int loopDelay = 1000;// delay in loop
int tmpStat =1;


void setup()

{

Serial.begin (9600); //Start the serial monitor

pinMode(trigPin, OUTPUT); //set the trigpin to output

pinMode(echoPin, INPUT); //set the echopin to input



for(int i=0; i<8; i++)
  {
    pinMode(controlPin[i], OUTPUT);// set pin as output
    if(triggerType ==LOW){
      digitalWrite(controlPin[i], HIGH); // set initial state OFF for low trigger relay
    }else{
       digitalWrite(controlPin[i], LOW); // set initial state OFF for high trigger relay     
    }

}

void loop()

[color=red]{[/color]
 for(int i=0; i<8; i++)
  {
    pinMode(controlPin[i], OUTPUT);// set pin as output
    if(triggerType ==LOW){
      digitalWrite(controlPin[i], HIGH); // set initial state OFF for low trigger relay
    }else{
       digitalWrite(controlPin[i], LOW); // set initial state OFF for high trigger relay     
    }
  }


int duration, distance; //Define two intregers duration and distance to be used to save data

digitalWrite(trigPin, HIGH); //write a digital high to the trigpin to send out the pulse

delayMicroseconds(500); //wait half a millisecond

digitalWrite(trigPin, LOW); //turn off the trigpin

duration = pulseIn(echoPin, HIGH); //measure the time using pulsein when the echo receives a signal set it to high

distance = (duration/2) / 29.1; //distance is the duration devided by 2 becasue the signal traveled from the trigpin then back to the echo pin, then divide by 29.1 to convert to centimeters

if (distance < 13) //if the distance is less than 13 CM

{

Light(); //execute the Light subroutine below

}

Serial.print(distance); //Dispaly the distance on the serial monitor

Serial.println(" CM"); //in centimeters

delay(500); //delay half a second

}

void Light() {

  for(int i=0; i<16; i++)
  {

   channelControl(i,tmpStat,200);// turn each relay ON for 200ms

    
  }
  if(tmpStat)
  {
    tmpStat=0;
  }else{
    tmpStat=1;
  }
 Serial.println("===============");
 //channelControl(6,1, 2000); // turn relay 7 ON for 2 seconds
 //channelControl(6,0, 5000); // turn relay 7 OFF for 5 seconds
 //channelControl(9,1, 3000); // turn relay 10 OFF forC ever

 delay(loopDelay);// wait for loopDelay ms
          
}

/*
 * funciton: channelControl
 * turns ON or OFF specific relay channel
 * @param relayChannel is integer value channel from 0 to 15
 * @param action is 1 for ON or 0 for OFF
 * @param t is time in melisecond
 */
void channelControl(int relayChannel, int action, int t)
{
  int state =LOW;
  String statTXT =" ON";
  if(triggerType == LOW)
  {    
    if (action ==0)// if OFF requested
    {
      state = HIGH;
      statTXT = " OFF";
    }
    digitalWrite(controlPin[relayChannel], state);
    if(t >0 )
    {
      delay(t);
    }
       Serial.print ("Channel: ");
       Serial.print(relayChannel); 
       Serial.print(statTXT);
       Serial.print(" - "); 
       Serial.println(t);        
  }else{
    if (action ==1)// if ON requested
    {
      state = HIGH;     
    }else{
      statTXT = " OFF";    
    }
    digitalWrite(controlPin[relayChannel], state);
    if(t >0 )
    {
      delay(t);
    }
       Serial.print ("Channel: ");
       Serial.print(relayChannel); 
       Serial.print(statTXT);
       Serial.print(" - "); 
       Serial.println(t);    
  }

}

error :

In function 'void setup()':

sketch_mar16c:35:1: error: a function-definition is not allowed here before '{' token

{

^

sketch_mar16c:146:1: error: expected '}' at end of input

}

^

exit status 1
a function-definition is not allowed here before '{' token

Where does the setup() function end ?

void setup()

{

Serial.begin (9600); //Start the serial monitor

pinMode(trigPin, OUTPUT); //set the trigpin to output

pinMode(echoPin, INPUT); //set the echopin to input



for(int i=0; i<8; i++)
  {
    pinMode(controlPin[i], OUTPUT);// set pin as output
    if(triggerType ==LOW){
      digitalWrite(controlPin[i], HIGH); // set initial state OFF for low trigger relay
    }else{
       digitalWrite(controlPin[i], LOW); // set initial state OFF for high trigger relay     
    }

}

There I think, The rest is running a loop. Honestly have the arduino for few days so I don`t really know whats going on.

Try Auto Formatting your code in the IDE. The closing } should now be on the left margin

Click to the right of the opening { of setup() and the IDE will put a box round the corresponding closing } Scroll down and find it

Check that there are the same number of { and } in your code

UKHeliBob:
Try Auto Formatting your code in the IDE. The closing } should now be on the left margin

Click to the right of the opening { of setup() and the IDE will put a box round the corresponding closing } Scroll down and find it

Check that there are the same number of { and } in your code

Tried Auto Formatting, I still shows me the same error :confused:

What I am trying to do is this

Is there a different way I can go about it ? or just keep trying to mess around until I get it.

Auto Format will not fix your code, just format it better.

Check those pairs of { and }