How do I code the arduino for automatic light control?

I am a college student , and I am trying to make an automatic light control system using arduino and ultrasonic sensors . I have to turn on the light if the natural light is not present and there are 1 or more then 1 people in the room .
I am a beginner . Therefore I am not getting how to program. Therefore I tried to download sketch from internet , but I am not getting some terms.
Here is the program which I have downloaded . Please explain me what is this? And how can I use it in arduino?

people_counter.ino (2.58 KB)

#include <NewPing.h>

int us1Pin = 13;
int us2Pin = 2;
int relayPin = 12;

#define MAX_DISTANCE 150



class USSensor {
public:
  USSensor(int trigPin, int echoPin, String aName) {
    trig = trigPin;
    echo = echoPin;
    sonar = new NewPing(trigPin, echoPin, MAX_DISTANCE);
    isActivated = false;
    name = aName;
    time = 0;
  }
  
  void update() {
    updateSensor();
    if (value < 100) {
      setActive(true);
    } else {
      if (millis() - time > 500) {
        setActive(false);
      } 
    }
  }
  
  void reset() {
    setActive(false);
    time = 0;
  }
  
  void setActive(boolean state) {
    if (!isActivated && state) {
      time = millis();
    }
    if (isActivated != state) {
      isActivated = state;
      Serial.print(name + ": ");
      Serial.println(state);
    }
  }
  
  boolean wasActive() {
    return (time != 0) && !isActivated;
  }
  
  int lastActive() {
    return millis() - time;
  }
  
private:
  int trig;
  int echo;
  int led;
  String name;
  boolean isActivated;
  unsigned long time;
  float value;
  NewPing *sonar;
  
  void updateSensor() {
    
    delay(25);
    unsigned int uS = sonar->ping();
    value = uS / US_ROUNDTRIP_CM;
    
//    delay(5);
//    pinMode(trig, OUTPUT);
//    digitalWrite(trig, LOW);
//    delayMicroseconds(50);
//    digitalWrite(trig, HIGH);
//    delayMicroseconds(200);
//    digitalWrite(trig, LOW);
//    pinMode(echo, INPUT);
//    int pulseLen = pulseIn(echo, HIGH);
//    float currentValue = pulseLen / 29.387 /2; // [voloshyn] convert into cm
//    if (value == 0.0f) value = currentValue;
//    else value = (value + currentValue) / 2;
//    value = pulseLen / 29.387 /2; // [voloshyn] convert into cm
  }
};

int peopleInRoom = 0;
USSensor *A;
USSensor *B;

void setup() {
  Serial.begin(9600);
  A = new USSensor(us1Pin, us1Pin, "A");
  B = new USSensor(us2Pin, us2Pin, "B");
  pinMode(relayPin, OUTPUT);
}

void loop() {
  
    A->update();
    B->update();
    
    if (A->wasActive() && B->wasActive()) {
      int a_time = A->lastActive();
      int b_time = B->lastActive();
      if (a_time < 5000 && b_time < 5000) {
        if (a_time > b_time) {
          peopleInRoom++;
        } else {
          peopleInRoom--;
        }
        Serial.print("People in room: ");
        Serial.println(peopleInRoom);
      }
      A->reset();
      B->reset();
    }

    if (peopleInRoom < 0) { // [voloshyn] in case when someone was already in the room when system was activated
      peopleInRoom = 0;
    }
    
    if (peopleInRoom > 0) {
      digitalWrite(relayPin, HIGH);
    } else {
      digitalWrite(relayPin, LOW);
    }
}

Before you begin writing code, you need to understand that an ultrasonic sensor measures distance.

How does 20 centimeters relate to the number of people in a room?

If someone is 20 cm away from the sensor it will count that someone has entered the room .
But I am not getting what is US1 and US2 pin in the code. I know about trigger pin and echo pin but I don’t know if it is trigger pin or echo pin . Please help me.

people_counter.ino (2.58 KB)

Can you explain me in easy way. How it is overrated.? And how can I code simply this program.

  int lastActive() {
    return millis() - time;
  }

millis() returns an unsigned long. time is an unsigned long. Why does this function return an int? A signed int, at that.

The whole reason for using NewPing is to eliminate blocking code. Using delay() in that class completely defeats that purpose. Stop doing that!

Just how are the sensors arranged, relative to each other? The ultrasonic sensor can't tell the difference between a person in the room, and a piece of furniture. So, the fact that it sees something doesn't mean that it saw a person. In fact, people make lousy reflectors of the wave that the sensor is measuring the round-trip time of.

(deleted)

I have make a code , please tell me what mistake I have done?

#include<LiquidCrystal.h>
LiquidCrystal lcd(1312,11,10,9,8);
#define trigPin1 6 //Define the HC-SE04 triger on pin 6 on the arduino
#define echoPin1 5 //Define the HC-SE04 echo on pin 5 on the arduino
#define trigPin2   // Define the HC-SE04 triger on pin   on the arduino
#define echoPin2   //Define the HC-Se04 echo on pin   on the arduino 
#define bulb 9 //Define the relay signal on pin 9 on the arduino
int count=0;
int a; // to store time of the signal cut of HC-SE04 1
int b; // to storetime of the signal cut of HC-SE04 2
void IN()
{
 count++;
 lcd.clear();
 lcd.print("PERSON IN ROOM:");
 lcd.setCursor(0,1);
 lcd.print(count);
 delay(1000); // wait for 1 second
}
void OUT
{
 count--;
 lcd.clear();
 lcd.print("PERSON IN ROOM:");
 lcd.setCursor(0,1);
 lcd.print(count);
 delay(1000); // wait for 1 second
}
void setup()

{

Serial.begin (9600); //Start the serial monitor
lcd.begin(16,2); // 16 shows the no.of columns and 2 is the no. of rows
lcd.print("VISITOR COUNTER"); // it prints visitor counter
delay(2000); //wait for 2 seconds
pinMode(in, INPUT);
pinMode(out, INPUT);
pinMode(bulb,OUTPUT);
lcd.clear();
lcd.print("PERSON IN THE ROOM:");
lcd.setCursor(0,1);
lcd.print(count);
pinMode(trigPin1, OUTPUT); //set the trigpin to output

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

pinMode(trigPin2, OUTPUT); //set the trigpin2 to output

pinMode(echoPin2, INPUT); //set theechopin2 to input

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

}

void loop()

{

int duration1, distance1, duration2, distance2; //Define two intregers duration and distance to be used to save data

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

delayMicroseconds(500); //wait half a millisecond

digitalWrite(trigPin1, LOW); //turn off the trigpin1

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

distance1 = (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

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

delayMicroseconds(500); // wait half a milisecond

digitalWrite(trigPin2, LOW); // turn off the trigpin2

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

distance2 = (duration/2) /29.1; //distance is the duration devided by 2 because the signal travelled from the trigpin then back to the echo pin, then devide by 29.1 to convert to centimeters

if (distance1 < 45 && distance2 <45) //if the distance is less than 45 CM

{

if( a<b)
{
 IN();
}
else if(b<a)
{
 OUT();
}
if (count>=1)
{
 Light();
}
else if (count<=o)
{
 LightOff();

}

}

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

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

delay(500); // dealy half a second 

Serial.print(distance2); // Display the distance2 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

}
void LightOff()
{
 digitalWrite(bulb, LOW); // turn off the light  
}

please tell me what mistake I have done?

Where to begin?

You made a statement, and used the wrong punctuation.
You failed to capitalize the first word in the sentence.

You FAILED to post code correctly. If this the level of attention you pay to all of your studies, you might as well ask your professor to fail you now and move on to basket weaving.

You FAILED to use arrays for things that belong together, like echo pin numbers, trigger pin numbers, etc.

You used meaningless names for global variables. No one can guess what the hell a and b are supposed to contain.

You used meaningless names for functions. IN() and OUT are useless names. AND, you forgot the damned parentheses on the OUT function.

count is another meaningless name. You are counting something, to the name of the variable should reflect that.

You FAILED to read the documentation on the functions you used. pulseIn() does NOT return an int.

You FAILED to create a function to read the ultrasonic sensors. Instead, you copied and pasted the code, and maybe failed to make a required change to the pasted copy.

You FAILED to assign values to a and b, and yet you expect them to not be 0.

You FAILED to properly indent your code, so that the structure is apparent.

Finally, you slammed a bunch of paper down, and asked "what's wrong with this" without giving a clues as to whether it compiled, whether it called you a sissy, or exactly what the problem is.

I am a beginner of arduino coding , It is my first project and I am trying to learn it. I have made another one. If anyone can tell if it is right or wrong? I am using LDR for natural light control and Ultrasonic sensors to sense someone has entered in the room.
Here is the code.

const int trigPin1 = 9;
const int echoPin1 = 10;

const int trigPin2 = 11;
const int echoPin2 = 12;
const int bulb = 7;
const int LDRpin1 = 5;
const int LDRpin2 = 6;
// defines variables
long duration1;
int distance1;

long duration2;
int distance2;
long count=0;
int LDRvalue1 = 0;
int LDRvalue2 = 0;
void setup() {
Serial.begin(9600); // Starts the serial communication

pinMode(trigPin1, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin1, INPUT); // Sets the echoPin as an Input
pinMode(trigPin2, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin2, INPUT); // Sets the echoPin as an Input
pinMode(bulb, OUTPUT);
}
void loop() {
measure1();
measure2();
Serial.print("Distance from sensor 1: ");
Serial.print(distance1);
Serial.print("    ");
// Prints the distance on the Serial Monitor
Serial.print("Distance from sensor 2: ");
Serial.println(distance2);


if(distance1<60)
{Serial.println("first sensor detected");
  for(int i=0;i<30000;i++)
     {measure2();
        if(distance2<60)
           { Serial.println("second sensor detected");    count++; return;}
        delay(1);
        
     

  Serial.println(count);  
     }
    
}

measure1();
measure2();

if(distance2<60)
{Serial.println("second sensor detected");
  for(int j=0;j<30000;j++)
     {measure1();
        if(distance1<60)
           { Serial.println("first sensor detected");count--;return;}
        delay(1);
        
     
     
     Serial.println(count);
     }
}
 LDRvalue1 = digitalRead(LDRpin1);
     LDRvalue2 = digitalRead(LDRpin2);
     if (count<= 0 )
     {
      count=0;
      digitalWrite (bulb, LOW);
     }
     if ((count >0) && (LDRvalue1=1) && (LDRvalue2=1))
     {
      digitalWrite(bulb, HIGH);
     }
    else if ((count >0) && (LDRvalue1=1) && (LDRvalue2=0))
     {
      digitalWrite(bulb, HIGH);
     }
      else if((count>0) && (LDRvalue1=0) && (LDRvalue2=1))
      {
        digitalWrite(bulb, HIGH);
     LDRvalue1 = digitalRead(LDRpin1);
     LDRvalue2 = digitalRead(LDRpin2);
     if (count<= 0 )
     {
      count=0;
      digitalWrite (bulb, LOW);
     }
     if (count >0 && LDRvalue1!=0 && LDRvalue2!=0)
      {
      digitalWrite(bulb, HIGH);
     }
     }
LDRvalue1 = digitalRead(LDRpin1);
     LDRvalue2 = digitalRead(LDRpin2);
     if (count<= 0 )
     {
      count=0;
      digitalWrite (bulb, LOW);
     }
     }

  


void measure1()
{// Clears the trigPin
digitalWrite(trigPin1, LOW);
delayMicroseconds(10);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration1 = pulseIn(echoPin1, HIGH);
// Calculating the distance
distance1= duration1*0.034/2;
// Prints the distance on the Serial Monitor

}

void measure2()
{// Clears the trigPin
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration2 = pulseIn(echoPin2, HIGH);
// Calculating the distance
distance2= duration2*0.034/2;

}

Guide me to learn arduino and complete my project.

Hi,
Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Is this a college project for a class?
If so you must have resources, lecturers, teachers, tutors, lab techs that can give you hands on advice.

I would be looking for experts in your college to get some of your answers, showing your teachers that you are asking questions from local available sources can only look good for you.

We can help you with your code, but not write it for you.
The fact that you have downloaded your code from another source does not help, the other source is not here to help or tell you if the code actually worked of what hardware was used.

You will be better off, developing your own code, in stages to get familiar with the code and the Arduino environment.
Don't try and write your code all at once
Write bits of code for each Input and Output of your project, then when you have codes that work and you can control, you can begin to combine the one at a time.

I know it sounds laborious and long, but in the end you will know more about coding Arduino and more about your code that YOU have written when you are debugging.

Writing a mass of code and getting it to work, very very very rarely works, especially someone else code that you have no idea as to how it functions.

We can help you write your code in stages.

Tom.... :slight_smile:

No it is not class project. There is only one profesor in our college who know how to code arduino but he is also confused in it.
And I have to submit my project after 3 days. Therefore I was trying to code full in one try.

(deleted)

No I have tried to code myself with the help of my college profesor and friends but they are confused in it because it counts people more then one when only one people enter in the room . I am trying to code the program from last week but due to my exams and submission I cannot give appropriate time to it.
That’s it.

(deleted)

Then help me and give me the hint how can I solve my problem with coding.

(deleted)

The first paragraph of reply #10 gives you your first hint of how to get help, but you ignored it.

Before everyone gets too upset, do you actually know how your sensor works? If so, you should be able to explain in a few sentences. Once you can do that you will have the answer to your main program problem.

Paul

To start with, you have a lot more code than you need. Functions CAN take arguments. Function CAN return values. You should have ONE function to measure distance, that takes the trigger and echo pins as arguments, and returns a distance. distance1 and distance2 should NOT be global variables.

  { Serial.println("first sensor detected");

Nonsense. The sensor might have detected something. It was not what was detected, though.

  // Prints the distance on the Serial Monitor

Really? I’m glad you put that comment there. I was really struggling to understand what Serial.print() did.

for (int i = 0; i < 30000; i++)
    { measure2();
      if (distance2 < 60)
      {
        Serial.println("second sensor detected");
        count++;
        return;
      }
      delay(1);



      Serial.println(count);
    }

So, where are the comments to describe what the hell this is doing? Why do you comment the obvious stuff, but not comment the cryptic, probably wrong, stuff?