Created
July 5, 2016 23:25
-
-
Save ShawnHymel/09265d8e08f5a50558a5f7c285bbdab0 to your computer and use it in GitHub Desktop.
Use 2 LEDs to create a photo interrupter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define LED_N_SIDE 2 | |
#define LED_P_SIDE 3 | |
#define EMITTER 12 | |
#define LED 13 | |
#define CAL_N 100 | |
// Global variables | |
unsigned int threshold = 0; | |
void setup() { | |
unsigned int avg_off = 0; | |
unsigned int avg_on = 0; | |
Serial.begin(9600); | |
pinMode(LED, OUTPUT); | |
pinMode(EMITTER, OUTPUT); | |
// Calibrate | |
digitalWrite(EMITTER, HIGH); | |
for ( int i = 0; i < CAL_N; i++ ) { | |
avg_on += readLight() / CAL_N; | |
} | |
digitalWrite(EMITTER, LOW); | |
for ( int i = 0; i < CAL_N; i++ ) { | |
avg_off += readLight() / CAL_N; | |
} | |
// Set threshold to half way between emitter ON and OFF | |
threshold = ((avg_off - avg_on) / 2) + avg_on; | |
digitalWrite(EMITTER, HIGH); | |
Serial.print("avg_on = "); | |
Serial.println(avg_on); | |
Serial.print("avg_off = "); | |
Serial.println(avg_off); | |
Serial.print("threshold = "); | |
Serial.println(threshold); | |
} | |
void loop() { | |
unsigned int light = readLight(); | |
Serial.println(light); | |
if ( light > 4000 ) { | |
digitalWrite(LED, HIGH); | |
} else { | |
digitalWrite(LED, LOW); | |
} | |
} | |
int readLight() { | |
unsigned int j; | |
// Apply reverse voltage to charge capacitance | |
pinMode(LED_N_SIDE,OUTPUT); | |
pinMode(LED_P_SIDE,OUTPUT); | |
digitalWrite(LED_N_SIDE,HIGH); | |
digitalWrite(LED_P_SIDE,LOW); | |
// Isolate N side of the diode | |
pinMode(LED_N_SIDE,INPUT); | |
digitalWrite(LED_N_SIDE,LOW); // turn off internal pull-up resistor | |
// Count how long it takes the LED to discharge | |
for ( j = 0; j < 30000; j++) { | |
if ( digitalRead(LED_N_SIDE)==0) break; | |
} | |
return j; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment