Back to Parent

#define SENSORPIN1 1 //Defining entry side IR break beam sensor pin
#define SENSORPIN2 2 //Defining exit side IR break beam sensor pin
#define LEDPIN 3 //Defining the LED pin

int sensorState1 = 0; //Variable to store the entry side IR break beam sensor reading; 1 is unbroken, 0 is broken
int sensorState2 = 0; //Variable to store the exit side IR break beam sensor reading;  1 is unbroken, 0 is broken
int state = 0; //Variable to store the state of light; 1 is ON, 0 is OFF
int numPeople = 0; //Variable to store the number of people in the room

void setup() {
  
  pinMode(LEDPIN, OUTPUT); //Defining the light as an output
  digitalWrite(LEDPIN, LOW); //Initially the light stays off
  pinMode(SENSORPIN1, INPUT_PULLUP); //Setting the entry IR break beam sensor as a pull up input
  pinMode(SENSORPIN2, INPUT_PULLUP); //Setting the exit IR break beam sensor as a pull up input
 
}
 
void loop(){
  
  sensorState1 = digitalRead(SENSORPIN1); //Reading the entry IR break beam sensor 
  sensorState2 = digitalRead(SENSORPIN2); //Reading the exit IR break beam sensor
    
    if (sensorState1==0) { //Checking if the entry beam is broken
        numPeople++; //Increasing the number of people in the room
        state = 1; //Setting the light state to ON
        delay(1000); //Delay to prevent misreading of exit beam
    }
    
    if (sensorState2==0) { //Checking if the entry beam is broken
        if (numPeople==0) { //Checking the number of people in the room
            return; //If no one is in the room, the function does nothing
        } else { //If the number of people is non zero
            numPeople--; //Reduce the number of people in the room
        }
        state = 0; //Setting the light state to OFF
        delay(1000); //Delay to prevent misreading of exit beam
    }
    
    if (state==1) { //Checking if the light state is ON
        digitalWrite(LEDPIN, HIGH); //If yes, we turn on the light
    } else { //If not, then the state is OFF
        if (numPeople>0) { //If the number of people in the room is non zero
            state=1; //The light state is changed to ON
        } else { //If the number of people in the room is zero
            digitalWrite(LEDPIN, LOW); //We turn off the light
        }
    }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0