Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Simple Proximity Sensor using Infrared
- int IRpin = A5; // IR photodiode on analog pin A0
- int IRemitter = 5; // IR emitter LED on digital pin 2
- int ambientIR; // variable to store the IR coming from the ambient
- int obstacleIR; // variable to store the IR coming from the object
- int value[10]; // variable to store the IR values
- int distance; // variable that will tell if there is an obstacle or not
- int prevDistance = -1;
- int brightness = 0;
- const int measurementsCount = 2;
- int brightnessArr[measurementsCount];
- int currentPoint = 0;
- void setup() {
- Serial.begin(9600); // initializing Serial monitor
- pinMode(IRemitter,OUTPUT); // IR emitter LED on digital pin 2
- digitalWrite(IRemitter,LOW);// setup IR LED as off
- /*
- for (int i = 0; i < measurementsCount; i++) {
- brightnessArr[i] = 0;
- }*/
- }
- void loop() {
- distance = readIR(5); // calling the function that will read the distance and passing the "accuracy" to it
- if (distance>=0 && distance!=prevDistance) {
- brightness = map(distance, 0, 150, 0, 150);
- analogWrite(10, brightness);
- prevDistance = distance;
- }
- /*
- if (prevDistance != distance) {
- // Serial.println(distance); // writing the read value on Serial monitor
- prevDistance = distance;
- brightness = map(distance, 0, 80, 0, 150);
- brightnessArr[currentPoint] = brightness;
- currentPoint = (currentPoint + 1) % measurementsCount;
- int val = delta();
- Serial.println(val);
- if (val > 30) {
- analogWrite(10, 254);
- } else {
- analogWrite(10, 30);
- }
- }
- */
- delay(10);
- }
- int delta() {
- int value = 0;
- for (int i = 1; i < measurementsCount; i++) {
- value += abs(brightnessArr[i-1] - brightnessArr[i]);
- }
- return value;
- }
- int readIR(int times) {
- int x, r;
- for(x=0; x<times; x++) {
- digitalWrite(IRemitter,LOW); // turning the IR LEDs off to read the IR coming from the ambient
- delay(2); // minimum delay necessary to read values
- ambientIR = analogRead(IRpin); // storing IR coming from the ambient
- digitalWrite(IRemitter,HIGH); // turning the IR LEDs on to read the IR coming from the obstacle
- delay(2); // minimum delay necessary to read values
- obstacleIR = analogRead(IRpin); // storing IR coming from the obstacle
- value[x] = ambientIR-obstacleIR;
- }
- for(int x=0;x<times;x++){ // calculating the average based on the "accuracy"
- distance+=value[x];
- }
- return(distance/times); // return the final value
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement