Skip to content

Instantly share code, notes, and snippets.

@mbrav
Created September 29, 2015 20:14
Show Gist options
  • Save mbrav/640e3266f380738098a5 to your computer and use it in GitHub Desktop.
Save mbrav/640e3266f380738098a5 to your computer and use it in GitHub Desktop.
A simpler way of calibrating a light sensor.
// Michael Braverman
// Lab Class
// 29 September 2015
// Pins
const int ledPin = 11;
const int lightPin = A0;
// States and numbers of the sensors and buttons
int lightVar;
boolean pressed = false;
boolean switchState;
// Variables for the photoresistor
int light = 9999;
int dark;
// Variables for fading
boolean fadeUp = true;
int fadeLevel = 0;
// Timer for the setup
int setupTimer = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(13, OUTPUT);
pinMode(lightPin, INPUT);
Serial.begin(115200);
Serial.println("-------------------------------------------------");
Serial.println("Wave your hand over the sensor to calibrate");
// Calibrate the photoresistor
while (setupTimer < 20000) {
lightVar = analogRead(lightPin);
if (light > lightVar) {
light = lightVar;
}
if (dark < lightVar) {
dark = lightVar;
}
// Make the LED Flash
if(setupTimer % 1000 == 0) {
switchState = !switchState;
}
digitalWrite(13, switchState);
setupTimer++;
}
Serial.println("LIGHT SENSOR CALIBRATED!");
Serial.print("Light = ");
Serial.println(light);
Serial.print("Dark = ");
Serial.println(dark);
Serial.println("STARTING THE PROGRAM!");
}
void loop() {
lightVar = analogRead(lightPin);
// Trigger if the light sensor senses a value higher than
// half distance between the darkest and the ligthest value
if (lightVar <= light + (dark - light)/2) {
fadeUp = true;
} else {
fadeUp = false;
}
// Fading code
if (fadeUp == true) {
if (fadeLevel != 255) {
fadeLevel++;
}
} else {
if (fadeLevel != 0) {
fadeLevel--;
}
}
// Set the outputs to their according values
analogWrite(ledPin, fadeLevel);
digitalWrite(13, switchState);
delay(5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment