Skip to content

Instantly share code, notes, and snippets.

@Lukelectro
Created June 30, 2022 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lukelectro/0a860ba7c25d232eac0d14435188c714 to your computer and use it in GitHub Desktop.
Save Lukelectro/0a860ba7c25d232eac0d14435188c714 to your computer and use it in GitHub Desktop.
/*
simple example for optical distance sensor with IR LED and BPW40
LED has 470R series resistor and is connected to pin given as IRLED (Pin 8 / PB0)
BPW40 is wired with collector to +5V, emitor to 1k8 to ground.
Emitor of BPW40 is capacitively coupled with 100 nF to pin given as BPW40 (pin A1, PC1)
That pin also has a 100k resistor to ground
(D8) + 5V
| |
470R |
| c
V (bpw40) 100n
- e---------||---0-----> input pin (A1)
| | |
| 1k8 100k
| | |
GND GND GND
LED and BPW40 are pointed in the same direction. Reflection is used to measure distance. More reflection assumes closer object.
Object could also be 'more reflective' instead of closer, so to measure distance use a uniformly reflective object e.g. brown/grey cardboard.
AC coupling eliminates DC noise (daylight)
Resistors values are 'what was on hand'. Other values might work even better. (Higher LED current). Tune to taste.
cc-by-sa 2022 Lucas, www.eluke.nl
*/
const char IRLED = 8; // pin for IR led for distance sensor (Pin 8 is PB0)
const char BPW40 = A1; // pin for fotodiode of distance sensor (A1 is PC1)
const int tickmillis = 25; // how fast/slow the loop ticks, in miliseconds
// Make this NOT match a harmonic of your local mains frequency so synchonous detection eliminates mains hum.
// 25 should be ok.
void setup() {
pinMode(IRLED, OUTPUT);
Serial.begin(19200);
}
void loop() {
// put your main code here, to run repeatedly:
static unsigned int prevmillis=0, nowmillis=0, sample;
nowmillis=millis();
if((nowmillis-prevmillis)>tickmillis){
prevmillis=nowmillis;
// pulse IR led and synchonously read reflecion from capacitvely coupled fotodiode
// (Synchronous detection / rectification)
digitalWrite(IRLED,HIGH);
distance = analogRead(BPW40);
digitalWrite(IRLED,LOW);
Serial.println(sample); // plot with Arduino Serial Plotter
}
// TODO: optionally average out samples further, or directly use as 'distance' measurement (dist = (dist + sample) << 1 )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment