Practical: 8
AIM: Interface IR sensor to Arduino.
(1) Write a program to detect obstacles using an IR sensor and display count of obstacles on
7-segment display.
#include <Arduino.h>
const int irSensorPin = 16; // Pin connected to IR sensor output
const int segPins[] = {5, 4, 0, 2, 14, 12, 13}; // Segment pins (A to G)
int obstacleCount=0;
// Segment encoding for digits 0-9
const byte digits[10][7] = {
   {1, 1, 1, 1, 1, 1, 0}, // 0
   {0, 1, 1, 0, 0, 0, 0}, // 1
   {1, 1, 0, 1, 1, 0, 1}, // 2
   {1, 1, 1, 1, 0, 0, 1}, // 3
   {0, 1, 1, 0, 0, 1, 1}, // 4
   {1, 0, 1, 1, 0, 1, 1}, // 5
   {1, 0, 1, 1, 1, 1, 1}, // 6
   {1, 1, 1, 0, 0, 0, 0}, // 7
   {1, 1, 1, 1, 1, 1, 1}, // 8
   {1, 1, 1, 1, 0, 1, 1} // 9
};
void setup() {
  Serial.begin(115200);
  pinMode(irSensorPin, INPUT);
  for (int i = 0; i < 7; i++) {
    pinMode(segPins[i], OUTPUT);
  }
}
void displayDigit(int num) {
  for (int i = 0; i < 7; i++) {
    digitalWrite(segPins[i], digits[num][i] ? LOW : HIGH); // LOW turns on the segment
  }
}
     void loop() {
    // Read the value from the IR sensor
    int sensorValue = digitalRead(irSensorPin);
    // Check if the sensor is detecting an obstacle
    if (sensorValue == LOW) { // Assuming LOW means obstacle detected
      Serial.println("No of Obstacle Detected");
      obstacleCount++;
      Serial.println(obstacleCount);
    } else {
      Serial.print("No of Obstacle Detected");
      Serial.println(obstacleCount);
    }
    displayDigit(obstacleCount);
    if(obstacleCount==9)
    {
      obstacleCount=0;
    }
    // Delay to avoid flooding the serial monitor
    delay(1000); // Adjust the delay as needed
}
(2) Use two IR sensor and make a circuit for object counter / vehicle counter. Display count
on 7-segment display.
int inputPin = 13; // choose input pin (for Infrared sensor)
int val = 0; // variable for reading the pin status
int count = 0;
void setup()
{
  Serial.begin(9600);
  pinMode(inputPin, INPUT); // declare Infrared sensor as input
}
void loop()
{
  int val = digitalRead(inputPin); // read input value
  if (val == HIGH)
  {
     Serial.println("obstacle not detected");
  }
  else
  {
     Serial.print("obstacle detected:");
     Serial.println(count);
     count = count + 1;
     if (count == 10)
       {
         count = 0;
       }
  }
  delay(500);