Paso 2: El código
// Lightning
//
// Credits to Rob Tillaart for the lightning simulation code. I don't remember now
// in which forum I (Google) found this code but I think the timing is spot on.
//
// I expanded on the lightning code to trigger a hacked Radio Shack recording module
// when a photo resistor detects darkness below threshold. Hey, it's a cheap form of
// motion detection for a Halloween prop.
//
// Credits to David A Mellis
// and Tom Igoe for the sensor calibration public domain code at
// http://arduino.cc/en/Tutorial/Calibration
//
//
#define BETWEEN 2579
#define DURATION 43
#define TIMES 7 #define SENSORPIN A0
#define TRIGGERPIN 7
#define FLASHPIN 13
unsigned long lastTime = 0;
unsigned long triggerTime = 0;
int waitTime = 0;
int sensorValue = 0;
boolean lightning = false;
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value
int sensorThreshold = 0;
void setup()
{
Serial.begin(115200);
Serial.println("lightning 0.0");
pinMode(FLASHPIN, OUTPUT);
pinMode(TRIGGERPIN, OUTPUT);
pinMode(SENSORPIN, INPUT);
delay(1000);
// Calibrate
//
// Sensor readings during the first five seconds of the sketch
// execution define the minimum and maximum of expected values
// attached to the sensor pin.
// This allows the circuit to be used in a variety of lighting conditions
// by exposing the sensor to the brightest and darkest values to be seen
// from it's resting position.
//
while (millis() < 5000) {
sensorValue = analogRead(SENSORPIN);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}
}
void loop()
{
if (millis() - triggerTime > 15000) {
sensorValue = analogRead(SENSORPIN);
// apply the calibration to the sensor reading
// sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
Serial.println(sensorMin);
Serial.println(sensorMax);
Serial.println(sensorThreshold);
Serial.print("Sensor value: ");
Serial.println(sensorValue);
sensorThreshold = (sensorMax - sensorMin) * 2 / 3;
if (sensorValue < sensorThreshold) {
digitalWrite(TRIGGERPIN, HIGH);
triggerTime = millis();
delay(500);
digitalWrite(TRIGGERPIN, LOW);
lightning = true;
}
else
{
lightning = false;
}
}
if (millis() - waitTime > lastTime) // time for a new flash
{
// adjust timing params
lastTime += waitTime;
waitTime = random(BETWEEN);
for (int i=0; i< random(TIMES); i++)
{
// Serial.println(millis());
if (lightning)
digitalWrite(FLASHPIN, HIGH);
delay(20 + random(DURATION));
digitalWrite(FLASHPIN, LOW);
delay(10);
}
}
// do other stuff here
}