Coding help for a rookie

Hi,
I am a rookie to Arduino. I just got UNO yesterday and started coding this afternoon and of course I am having troubles with the code as it does not completely works as I wish. So, I am counting on an experts help. Here is the issue.
I have two 5V NPN NO photoelectric switches and a 5V relay I want to activate. I want that once one of the switches turns to NC even for a brief time, the relay must be activated until the second (not previously triggeted switch) is just or even briefly turned to NC. Of course it should work the same no matter which of the two switches is triggered first.
With rather simple code (see below) i manneged to the the proper operation but only if NC state of secondly triggered sensor is present less than 1s. If it signal from seconf switch is present for more than 1s, the set does not work on and relay is activated endesly.
Unfortunately my short presence in coding has not got me enough skills to fix this bug. Can I count on your help or at least directions on how to fix it?
Thank s alot.
Bye,
Andrej

#define sensor1 2
#define sensor2 3
#define relay 4

bool sensor1Triggered = false;
bool sensor2Triggered = false;

void setup() {
  pinMode(sensor1, INPUT);
  pinMode(sensor2, INPUT);
  pinMode(relay, OUTPUT);
}

void loop() {
    //Check if sensor1 is triggered 
  if (digitalRead(sensor1) == LOW && sensor1Triggered == false){
    sensor1Triggered = true;  
    digitalWrite(relay, HIGH);
  }
   if (digitalRead(sensor2) == LOW && sensor1Triggered == true){
    sensor1Triggered = false;
     sensor2Triggered = false;
     delay(1000);
     digitalWrite(relay, LOW);
   }
 //Check if sensor2 is triggered 
  if (digitalRead(sensor2) == LOW && sensor2Triggered == false){
    sensor2Triggered = true;  
    digitalWrite(relay, HIGH);
  }
   if (digitalRead(sensor1) == LOW && sensor2Triggered == true){
    sensor2Triggered = false;
     sensor1Triggered = false;
     delay(1000);
     digitalWrite(relay, LOW);
   }
} 

Thank you for properly posting your sketch.


Why are you delaying before operating the relay ? :thinking:

Always show us a good schematic of your proposed circuit. Show us a good image of your ‘actual’ wiring. Give links to components.

To make debugging easier, I recommend reading the pins once at the top of the loop function, assigning the results to variables, and testing the variables.

consider


const byte PinRelay     = 4;
const byte PinSensor [] = { 2, 3 };
const unsigned Nsensor = sizeof (PinSensor);

enum { Off = HIGH, On = LOW };

#define Timeout 5000

void loop ()
{
    unsigned long msec = millis ();

    for (unsigned n = 0; n < Nsensor; n++)  {
        int m = Nsensor-1-n;

        if (LOW == digitalRead (PinSensor [n]))  {
            Serial.print (n);
            Serial.print (" triggered ");

            digitalWrite (PinRelay, On);

            while (millis () - msec < Timeout)  {
                byte sensor = digitalRead (PinSensor [m]);
                if (LOW == sensor)  {
                    Serial.print (" ");
                    Serial.print (m);
                    Serial.print (" ");
                    Serial.print (sensor);
                    break;
                }
            }

            digitalWrite (PinRelay, Off);
            Serial.println (" done");
            delay (1000);       // wait for things to clear
        }
    }
}


// -----------------------------------------------------------------------------
void setup()
{
    Serial.begin (9600);

    for (unsigned n = 0; n < Nsensor; n++)
        pinMode (PinSensor [n], INPUT_PULLUP);

    pinMode (PinRelay, OUTPUT);
    digitalWrite (PinRelay, Off);
}

@gcjr Greg,

have

you

ever considered that a user that writes in his very first sentence

could have a very hard time by analysing and understanding a code like the one you are posting??

@aveternik

So there are two different cases

both cases starting at sensor1 and sensor2 untriggered

case 1

  • sensor1 gets triggered=> switch on relay
  • keep relay on until sensor2 gets triggered
    .
    .

case 2

  • sensor2 gets triggered=> switch on relay
  • keep relay on until sensor1 gets triggered

your code uses a line delay(1000)
what was the reason to add this line of code?
Do you want the relay beeing on for a minimum of 1second before switching off?

You should define more precise what are the conditions to set back your system to the mode of "relay beeing switched off but beeing ready = waiting for one sensor to trigger and if triggered then to switch relay on"

Your code does what you have described:
if one of the two switched is triggered switch on relay

sensor1 triggers=>switch relay on
sensor 2 triggers => wait 1 second switch relay off and reset flag-variables to false
after the 1 second delay
if sensor2 is still triggered => switch relay on

So just looking at the triggered state beeing triggered or untriggered is not sufficient.

You should describe the real application behind the logic to make it easier to understand.
There is a high change that having if-conditions that analyse state-change will solve the problem
state-change means
change from untriggered to triggered
change from triggered to untriggered

You haven't described precise enough your wanted functionality to be sure that
checking for the state-change from triggered to untriggered is that thing that shall put back the system into
"relay beeing switched off but beeing ready = waiting for one sensor to trigger and if triggered then to switch relay on"

best regards Stefan

if he does, he can ask questions.

2 Likes

Sure theoretically the user can. But there is a psychological component you seem to not consider.

To you personally this code is a peace of cake and you seem to be unable to imagine that for a newcomer your code is so advanced and with zero explanation that the picture about you that you create inside the head of the newcomer with this code is "nerdy nerd"
which will scare the user too much to ask about your code.

Of course this is arduino.cc at the end of the day.

not a piece of cake, but it's not that complicated, just organized differently. the reader specified "what" he/se wants the code to do. they can spend some time trying to understand it, ask questions or ignore it.

i do. see above

1 Like

My view is that we all make assumptions on what is acceptable (based indeed on our experience and culture) and should expect honest feedback. A forum is meant for conversation style discussion so @gcjr expectation to get questions even from a rookie is not so far fetched in my opinion.

to give you an example of such assumptions and/or cognitive dissonance, when I read your posts such as

or

As I've been around for some time and seen your posts, I know your intent is genuine and you want to make your point clearer but my gut perception when I see such text is more like you are yelling (same as with capitals) or if you were irritated and I see that as an agressive communication style. This feeling could be shared by others, including newbies when you answer.

➜ your use of bold or larger font has also a "psychological component" you seem "not to consider" in your communication style :slight_smile:

2 Likes

Hello aveternik
How are you?
Did you find here a proper solution for your course project yet?

Hi,
Sorry for late reponse. I had to attend some outdoor activity.
Anyway, I added the schematics to the original post. The actual wiring is the same.
The application will be used to turn on or off the led strips installed in each one of the staircase. I had it done until recently by psyhical timer relay but it happened last week that a child got distracted in the middle of the night at the the mid of the staircase and of course after a while the light turned off in he was trapped in the dark calling for a mom to save him. Poor kid :slight_smile:
However, I decided to fix that and I finally got what I have wanted for quite some time. Arduino and some coding time :slight_smile:
Anyway, I need to have these sensors work like a 2 way control switch. If one triggers the relay, the other one turns it off. In reality, when the one at the botton of straicase moves to NC, the ligh must not go out before the one on the top moves to NC. It must work the same if you are going down. Please note that the sensor is almost always in NO position. It goes to NC only when your leg passed by, then it goes to NO again.

About the code, the delay function is there only for the reason, that i secure the time for the leg to move out of the filed of the sensor before the relay moved to off. If I dont do that, then the relay cannot know what to do as the going would ask relay to move on HIGH and LOW state of the sensor, like this:

 if (digitalRead(sensor2) == LOW && sensor1Triggered == true){
    sensor1Triggered = false;
     sensor2Triggered = false;
     digitalWrite(relay, LOW);
     //delay(1000);
   }
 //Check if sensor2 is triggered 
  if (digitalRead(sensor2) == LOW && sensor2Triggered == false){
    sensor2Triggered = true;  
    digitalWrite(relay, HIGH);

GCJR, currently i do not understand your code. I will try it first, then study and ask questions about mysteries (for me) you got there .

this code does not work properly...it works only if sensor 1 is firstly triggered. Sensor 2 can never be triggered first. And Relay moves every 5 seconds w/o sensor being activated.

works for me when i test is using the buttons and LEDs on a Multifunction shield

are you sure both of your buttons work?

i added a reset after 5 second

You're powering the relay and both sensors from the Arduino 5V output; what are the current needs of both the sensors and the relay?

Yes, both sensors are fine...my code works except if the object is in the field of second sensor for more than 1s. In that case, relay is firstly deactivated and after 1s it is activated again and then you need to deactivate it by 1 sensor.

sensor, 2x 100mA
relay, 71mA

once installed for actual operation, all 4 components will be powered by separete AC/DC 5V source.

sounds like your code is immediately retriggering after the 2nd sensor resets the relay because the sensor is still active.

do you need additional logic to wait for both sensors to be not active after the relay is reset?

Sounds like spurious behaviour when the relay is turned off, if I read your description correctly. I can see probable cause.

Your relay likely has no transient suppression diode. If that is the case, when your coil is shut off, you probably get a significant pulse of energy back into the 5V power, disrupting your Arduino. This is sure to give you grief longer-term. If you're able to solder, put a diode across the coil pins of the relay, with the band of the relay at the + side. You're running your Arduino on the hairy edge - total current draw will be loading your USB significantly; your 5V rail may be as low as 4.5-4.7 VDC(check with a meter), so the transient pulse from the relay is a big problem.

However, I'd suggest using an LED instead of the relay until you move off the USB power.

Developing as you are, using your USB 'because it's convenient to do so' with a plan to change conditions 'in the real', will cause you grief. 'Oh, it's okay, my real final circuit will be better' is a plan to fail, IMHO. Case in point, you're likely struggling right now with a problem you'd never see if you were powering that relay, and the sensors, with an external supply.

Just some free advice. BTDT. Relays can be a pain to work with, when they introduce a random Murphy factor.

There are probably more reasons why your code does not yet work like you want.
Still this is true about the code that you have posted above in post # 1

best regards Stefan

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.