Advertisement
Mihalytch

IR Sensor arduino

Mar 12th, 2014
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. // Simple Proximity Sensor using Infrared
  2.  
  3.  int IRpin = A5;               // IR photodiode on analog pin A0
  4.  int IRemitter = 5;            // IR emitter LED on digital pin 2
  5.  int ambientIR;                // variable to store the IR coming from the ambient
  6.  int obstacleIR;               // variable to store the IR coming from the object
  7.  int value[10];                // variable to store the IR values
  8.  int distance;                 // variable that will tell if there is an obstacle or not
  9.  int prevDistance = -1;
  10.  
  11.  int brightness = 0;
  12.  
  13.  const int measurementsCount = 2;
  14.  int brightnessArr[measurementsCount];
  15.  int currentPoint = 0;
  16.  
  17.  void setup() {
  18.    Serial.begin(9600);         // initializing Serial monitor
  19.    pinMode(IRemitter,OUTPUT);  // IR emitter LED on digital pin 2
  20.    digitalWrite(IRemitter,LOW);// setup IR LED as off
  21.  }
  22.  
  23.  void loop() {
  24.    distance = readIR(5);
  25.    
  26.    brightness = map(distance, 0, 150, 0, 150);
  27.    
  28.    analogWrite(10, brightness);
  29.  
  30.    delay(10);
  31.  }
  32.  
  33.  int readIR(int times) {
  34.    int x, r;
  35.    
  36.    for(x=0; x<times; x++) {
  37.      digitalWrite(IRemitter,LOW);    // turning the IR LEDs off to read the IR coming from the ambient
  38.      delay(2);                       // minimum delay necessary to read values
  39.      ambientIR = analogRead(IRpin);  // storing IR coming from the ambient
  40.      
  41.      digitalWrite(IRemitter,HIGH);   // turning the IR LEDs on to read the IR coming from the obstacle
  42.      delay(2);                       // minimum delay necessary to read values
  43.      obstacleIR = analogRead(IRpin); // storing IR coming from the obstacle
  44.      
  45.      value[x] = ambientIR-obstacleIR;
  46.    }
  47.  
  48.    for(int x=0;x<times;x++){         // calculating the average based on the "accuracy"
  49.      distance+=value[x];
  50.    }
  51.    
  52.    return(distance/times);           // return the final value
  53.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement