Elizandro:
Now I uploaded your code, but it does the same mine does.
2 relays are always turned on when both LDR´s get the same amount of light, but both should be turned off.
And if one LDR gets shadow, relays 1 & 2 turn off and 3 & 4 turn on. But if the second LDR recieves shadow, 1 & 2 turn on and 3 & 4 off, but 1 & 2 stay on if the second LDR recieves sunlight again.
Oh, right. Dude, think. Where in this code doe it deal with the condition where both relays are getting the same amount of light? That's right - nowhere. If you want that behaviour, then you have to out it in:
const byte sens1 = A0;
const byte sens2 = A1;
void setup()
{
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, HIGH);
}
void loop()
{
int val1 = analogRead(sens1);
int val2 = analogRead(sens2);
if (val1 > val2)
{
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
}
else if (val1 < val2)
{
digitalWrite(9, HIGH);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
}
else {
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
}
}
The problem with this code, however, is that it will only turn off the relays if both inputs A0 and A1 are exactly the same. This probably isn't helpful, because its 1 in 1024.
So what you need is some slop:
// not sure how much slop you need - you will have to experiment
const int SLOP = 10;
void loop()
{
int val1 = analogRead(sens1);
int val2 = analogRead(sens2);
if (val1 - val2 > SLOP)
{
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
}
else if (val1 - val2 < -SLOP)
{
digitalWrite(9, HIGH);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
}
else {
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
}
}
Your other problem is hysteresis. If one sensor is juuuust SLOP more than the other, your relays will chatter at that boundary. To fix this, once the relay has gone one way, we make it a little "sticky", a little more likely to stay in that position. This means that we don't need that slop factor.
// not sure how much hysteresis you need - you will have to experiment
const int HYSTERESIS = 10;
int hysteresis = 0;
void loop()
{
int val1 = analogRead(sens1);
int val2 = analogRead(sens2);
if (val1 - val2 + hysteresis > 0 )
{
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
hysteresis = HYSTERESIS;
}
else if (val1 - val2 + hysteresis < 0)
{
digitalWrite(9, HIGH);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
hysteresis = -HYSTERESIS;
}
else {
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
hysteresis = 0;
}
}