Published on

Day 2 Assignment Solutions

Table of Contents

Assignment 1 Solution

We divide the solution in 3 parts:

  1. Initialise (in setup)
  2. Detecting wherther the visitor enters or exits.
  3. Printing the output.

Part 1

We initialise the count variable

int count = 0;

Now Initialise the sensor pins as Input

pinMode(2, INPUT);  //Sensor 1
pinMode(3, INPUT);  //Sensor 2

Begin Serial communication with baud rate 9600.

Serial.begin(9600);

Part 2

So when the visitor is entering first the Sensor1 would detect it and after few milliseconds Sensor2 would detect it. So, as the Sensor1 detects we create a while loop and wait till the Sensor2 detects the person.

//if Sensor1 detects obstacle
if (digitalRead(2) == LOW){
    while (digitalRead(3) == HIGH)
    {
      //Do nothing
      //Wait for sensor2 to detect
    }

Now we increase the count by 1 as the person is entering

count = (count + 1 );  //Increase the count by 1

Follow the same for detecting exit.

  1. Interchange Sensor 1 and 2
  2. decrease the count

Part 3

Add this to both the IFs of entry and exit. We first print whether "In" or "Out"

Serial.println("In");

Next we print the number of people and wait for a second using delay

Serial.print("Number of people: ");
Serial.println(count);
delay(1000);

Now setup the electronics and the output is ready! The final code would look like this.

void setup() {
  int count = 0;
  pinMode(2, INPUT);  //Sensor 1
  pinMode(3, INPUT);  //Sensor 2
  Serial.begin(9600);

}

void loop(){
  if (digitalRead(2) == LOW){
    while (digitalRead(3) == HIGH)
    {
      //Do nothing
      //Wait for sensor2 to detect
    }
    count = (count + 1 );  //Increase the count by 1
    Serial.println("In");
    Serial.print("Number of people: ");
    Serial.println(count);
    delay(1000);
  }
  if (digitalRead(3) == LOW){
    while (digitalRead(2) == HIGH)
    {
      //Do nothing
      //Wait for sensor1 to detect
    }
    count = (count - 1);  //Decrease the count by 1
    Serial.println("Out");
    Serial.print("Number of people: ");
    Serial.println(count);
    delay(1000);
  }
}

Bonus Solution

Initialise the LED as output in setup. Then, add the below code at the end of the loop. This will turn on the light if there is someone inside and turn off if the room is empty.

if(count>0){
  digitalWrite(4,HIGH);
}
else{
  digitalWrite(4,LOW);
}

Assignment 2 Solution