Hi everybody.
I've come to enjoy this forum, but only as a reader until now. But here's a code hurdle I just can't figure out (might be I've just stared too long at the code to think clearly).
Basically, what I'm doing is building a distributed system of 16 units, each with a minimal arduino (based on the uDuino over at instructables with power supply as shown in ITP's breadboard arduino), an LED as output and an LDR as input.
What I want is to let every unit have three different states:
- Normal: as long as you get input often enough (as in the neighbouring unit is in normal state) you keep blinking normally.
- Agitation: If the input for some reason is not coming often enough (as in someone or something blocks the light from the neighbour) you start to blink more and more rapidly "trying to reconnect".
- Mimic: If the input is coming too rapidly (as in the neighbour is in the agitated state) you start getting influenced and start blinking rapidly as well.
I hope that makes sense.
I've managed to get the two first states working satisfactorily, but continue to struggle with the last one.
Here's the code for the first two states:
int motorPin = 7;
int LDRpin = 0;
int LEDpin = 13;
long lastLDR = 0;
int val = 0;
int threshold = 100;
int lastLED = 0;
int stress = 4000;
int mimic = 1000;
int value1 = LOW; // previous value of the LED
long time1 = millis();
long time2 = millis();
long interval1 = 3000; // interval at which to blink (milliseconds)
long interval2 = 500;
void setup()
{
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);
pinMode(motorPin, OUTPUT);
}
void loop()
{
unsigned long now = millis();
val = analogRead (LDRpin);
if (val > threshold){
lastLDR = millis();
}
// ** defines the timing used to turn LED on and off, based on LDR input
if (now - lastLDR < stress && now - lastLDR > mimic){
interval1 = 3000;
interval2 = 500;
}
else if (now - lastLDR > stress){
if (interval1 > 250){
interval1 = interval1 - 0.001;
}
if (interval2 > 30){
interval2 = interval2 - 0.005;
}
}
// Serial.println (now - lastLDR);
//if (val > threshold){
// Serial.println (val);
//}
// ** makes the LED blink according to timing
if (now - time1 > interval1){
time1 = now;
digitalWrite (LEDpin, HIGH);
}
else if (now - time1 > interval2 && now - time1 < interval1){
digitalWrite (LEDpin, LOW);
}
}
My first solution was to do something like this:
if (now - lastLDR < mimic){
interval1 = now - lastLDR;
interval2 = 100;
}
But the problem is that lastLDR updates as long as it gets input over the threshold, and the input lasts for up to 500ms, thus returning 0 and occasionally 4294967295. This upsets the behaviour.
So, any suggestions?
I would appreciate any help!
Cheers,
Kjetil.