Simulating a PLC ladder diagram on arduino

thanks a huge bunch, that really clarify everything....

btw is there any way i make a function or sub rutine that can simplify doing the keep funtion.

like

keep( (maybe a name for the memory slot),maybe S, maybe R, );

for instant 
keep(m1,I1,I2)
where as m1 is the memory address for the keep funtion, I1 is the set and I2 is the reset function

There are obvious similarities between the behaviour described by your ladder diagrams and the behaviour described by the Arduino imperative code and I suspect that your conceptual design skills will carry across well. However, I would urge you to write your sketches directly in C++ rather than try to 'write' them as a ladder diagram and then convert. You have clearly understood the basic concepts of variables holding values, and functions containing code that can be called. This is more than some people have when they start Arduino programming.

^^This. There are lots of examples in the IDE to look through that will help. Do you have a particular project in mind?

wildbill, thanks for the reply.
i basically have any particular project in mind but i really keen on using my knowledge in PLC programming into arduino,
i think i have get the keep function figured out.
could you verify this out?

int keep(boolean S, boolean R)
{
  int result;
  if (S== HIGH & R==LOW)
  {
    result = HIGH;
   }
   else 
   {
    result = LOW;
    }
   return result;
}

the only reason for me to use PLC way of programming is that it is something i fully understand, and i know that arduino is more then capable of handling this task due to most of PLC programming is done base on Boolean logic.

is Zatalian way of doing is much simpler?
ii really do like to have a keep function....

how about this?

int keep( int S, int R,)
int result;
if (S && !R) {result =1;}
else {result =0;}
return result;

I'd strongly recommend that you let the ladder diagram stuff go - it'll hamper your understanding of existing code and it'll baffle anyone you go to for help (such as here). For better or worse, the two languages are very different and in my opinion at least, trying to force one to be the other is not going to go well. It could be done that way, but I can see no reason to do so and lots of reasons not to.

I'm not familiar with the thing you call a 'keep' but the behaviour you're describing could be coded like this:

// a high (I1) and a low (I2) with make the output high (keep1)
// however the low (I3) will make it the output low
// in the code below, true corresponds to logic high and false corresponds to logic low

boolean I1, I2, I3, result;
if(I3)
{
    if(I1 && !I2)
    {
        result = true;
    }
    else
    {
        result = false;
    }
}
else
{
    result = false;
}

There are more concise ways to code that calculation, but they are harder to get your head around. For example:

result = I3 && (I2 && !I3);

This 'keep' logic may make sense as a way to build logical behaviour in a PLC, but unless your goal is to make the microcontroller emulate a PLC I wouldn't expect to use this type of thing very often - usually, logical expressions can be expressed much more simply than this. I wouldn't use I1, I2, I3 as variable names either - I'd use names that indicate the purpose of the variables.

Just thinking that this may have already been done in a way so a little googling came up with a few.

Here is one that looked OK.

The original purpose of the PLC ladder logic programming method was to allow the then existing power electrical engineers and technicians to program a PLC application with just the knowledge and experience they used in designing and building power and control relay cabinets. These first came out in the mid to late 1970s. It made heavy use of a primitive CRT based GUI format where they defined 'coils' output and 'contacts' inputs coorosponding to real digital inputs and outputs, and could if required 'wire' them to internal function blocks like counters, shift registers, timers, etc.

Today there is little reason to limit ones self to just creating such ladder logic applications, and most modern PLC offer an alternate 'higher level' programming language to support user created programs. The biggest advantage to using PLCs are there very rugged and reliable construction rather then their ability of being able to be programmed in 'ladder logic'. If one was going to emulate a PLC system with an arduino board it would be pretty dumb in my opinion to not just program the application directly in the arduino C/C++ sketch language, rather then trying to implement a ladder logic interrupter 'programmer'/runtime emulator. Lots of work to do that with little payback benefits, just learn to program in C/C++. :wink:

Lefty

yes retrolefty. i am pretty much sure that if i try programming arduino with the skill i use to program a plc will be an overkill and well defeat the purpose of using arduino right.... urm well for me maybe the thought that i could use the same kind of logic i use for plc can be implement into arduino will be a tremendous help... when i first learn programming a plc, the teacher tell me went progrmming a PLC you only need to know 6 basic things and the rest would be extra for you to create a good enough program for your Machine to run. those 6 basic things are
--| |-- a normally open contact
--||-- a normally close contact
--( )-- a coil or output
a keep function
a timer function
and last but not least is the counter function.

i work as an asistance engineer for the past 2 years and only recently resign so i could continue my study.
anyway while i was working, i have lots of friends that are great PLC programmer dont know a thing about C or any other kind of programming. so what i'm trying to do is to emulate a PLC ladder diagram inside arduino so that most (if not all my programmer friend ) to start using Arduino. this is just a warm up so they know the capability of Arduino and maybe make them more intrigue to learn more about arduino?

i been thinking for the past few night and it seems that i may have found a way to emulate the keep function.
A keep function is just an equivalent to an Rs flip flop or to many electrician or people that know how to keep a relay on with hard wiring is called latch.

the basic for any latch in hard wiring is:
I1 I2 M1
---| |---||------( )
M1i |
---| |-|

let say I1 and I2 are momentary push button, the I1 connection is the normally open while I2 is the normally close part of the switch that we are care about. M1 coil is the coil of a relay and M1i is one of the relay contact.
the operation goes that if someone push button I1, the circuit will be completed and current will flow . ( consider that the left side of the diagram is maybe 12V/5V/24/240V(live) for that matter and the right side is the ground/neutral). this will cause the relay coil(M1) to be energize and one of the relay contact will be close (M1i).Now the current will flow trough the (M1i) and down to the coil thus keeping the relay in the energize state (latch).....
to turn of this latch is as easy as pressing the I2 button, cause it cut the flow of current.
what happen if both the I1 and I2 button being press at the same time?
well because I2 is the one controlling the current flow, the coil will not be energies.in most way this make the circuit have some form of safety features.

how to emulate keep or latch inside arduino in term of programming?
i personally like to use the term keep but due to maybe making the wrong message across so i would use the second most use term to describe this behavior that is Latch.

 int latch(boolean s, boolean r)
{
  boolean result = LOW;
  if ( (s== HIGH || result == HIGH) && r==LOW)
  { 
    result = HIGH;
   }
  if (r == HIGH)
  {
    result =LOW;
  }
 return result;
}

If you want this result value to persist after your calculation then it needs to be a static variable, or declared outside the function. All the variables declared inside the function are discarded once the function returns.

Again, though, this is a very contrived way to evaluate expressions in an Arduino and I do not think you will be doing your co-workers any favors if you encourage them to design their Arduino sketches as if they were PLC programs. Using 'C' and C++ code you have far more flexibility and can produce far simpler solutions than you would achieve with the PLC approach you're using. Better IMO to describe the behaviour you're trying to achieve and then write it directly in 'C'/C++.

There are hundreds of different programming languages and types of computer and controller and the value comes from knowing what they're capable of and how to use them most effectively - not how to make them all look and behave like the first thing you learned.

sorry for my last code. i have try the code, i can compile well but cant be execute according to the principle that talk before.
this is the one that work after i have spend time making it and testing it to be working well.

this is just an example:

/* 
 trying to set arduino latch funtion 

 connect pin 2 to a momentary push botton and the other leg to ground
pin2 -----./.----gnd
    ./. is a momentary switch
    repeat connection on pin3
    since most arduino have a LED connected to pin 13, i will use this to varify the code
*/
boolean result = LOW;
void setup()
{
  pinMode(2,INPUT); //setting pin 2 as input
  digitalWrite(2,HIGH);// activating pin 2 internal pull up
  pinMode(3,INPUT);// setting pin 3 as input 
  digitalWrite(3,HIGH);//activating pin 3 internal pull up
  pinMode(13, HIGH);// setting pin 13 as output
}

void loop()
{
  int Set = !digitalRead(2);
  int Reset =!digitalRead(3);
  int K=latch(Set,Reset);
  digitalWrite(13,K);
}


int latch(boolean s, boolean r)
{
  if ( (s== HIGH || result == HIGH) && r==LOW)
  { 
    result = HIGH;
   }
  if (r == HIGH)
  {
    result =LOW;
  }
 return result;
}

A keep function (or SetReset, or ResetSet, ...) is a function with a memory... You can't program it with local variables. You either need a global variable or a parameter.
You probably need something like this, but i haven't tested it...

#define I1 1
#define I2 2
#define Q3 3


boolean Input1, Input2, Output1, M1;


void setup()
{
  pinMode(I1, INPUT);
  pinMode(I2, INPUT);
  pinMode(Q3, OUTPUT);
  
  M1 = 0;
}


void loop()
{
  Input1 = digitalRead(I1);
  Input2 = digitalRead(I2);
  
  Output1 = keep(Input1, Input2, &M1);
  
  digitalWrite(Output1, Q3);
}

boolean keep(boolean Set, boolean Reset, boolean *Memory)
{
  if (Reset == HIGH) *Memory = LOW;
  else if (Set == HIGH) *Memory = HIGH;
  
  return *Memory;
}

the only reason for me to use PLC way of programming is that it is something i fully understand

Limiting what you do to what you already know is a bad idea, learn new things.

If you insist on programming the Arduino in Ladder logic then what you should look for is something that pre-processses ladder logic into C code.

Somebody seems to have done this here;

However even if you were going to use something like this I would suggest you need to learn how to program the Arduino fully in C first, otherwise what is happening will just be "magic" and you will not really know what is going on.

Zatalian thanks for the code. it works but theres a slight Typo in the code
int the part

digitalWrite(Output1, Q3);

it should have been

digitalWrite (Q3, Output1);

there's only one problem with this function of the one i post before,
if let say that i would like to call keep function a couple of time,
any term that use the same term will exhibit the same result.

To those who have never used ladder logic and been involved in troubleshooting a machine where it has been used it would seem to be a rather archaic and feeble system. But for those who have used it it provides a great deal of ease for troubleshooting and an easy to decode code for learning about how the controlled machine works.

Ladder logic is a graphical language and can produce very complex control over very complex machines. The basic elements are the examine true ( ---|/|---) and examine false (---| |---) and the OR which is a branch. Various PLCs allow various complexities of the branching and some allow more complex coding than others.

Ladder is used for programming PLCs in the US while the STL languge is used in Europe and Japan. Some PLC programming packages will convert between the 2, there are others where code can be written in STL that can't be converted to Ladder. STL has a look and feel that is very close to Assembly language. Well written code in Ladder or STL if fairly easy to decypher and work with, while poorly written STL code is just as much a nightmare as poorly written code in any other system. Ladder could be considerred a structured language as there are only certain things you can do in certain places - outputs can only be on the right rail, inputs go from the left rail to the right rail. Unfinished rungs are an error.

Imagine writing a statementin C with over 50 AND, OR and NOT. Piece of cake with ladder.

Being graphical it is very easy to animate what is happening in a rung, with those elements that are true being highlighted and the path from left to right is easily seenand requies a lot less analysis than getting multiple dumps of several variable. I have written ladder programs running to over 500 rungs, 48 inputs, 32 outputs (along with a couple axis drives) 4 analog inputs and 4 analog outputs. To have coded it in C and then debugged it would have taken much longer and would have been much harder to modify when the specs changed for a specific machine.

Ladder still rocks and is a powerful tool for process control and machine control.

ash901226:
there's only one problem with this function of the one i post before,
if let say that i would like to call keep function a couple of time,
any term that use the same term will exhibit the same result.

If you want to use more than 1 keep function, you will need more than 1 "memory bit" variable...

Output1 = keep(Input1, Input2, &M1);
Output2 = keep(Input3, Input4, &M2);

I have to agree with the others here that trying to rewrite ladder to c is not the best way to go... You are making things more difficult than it should be. Everything you want can be solved with some simple bool & integer logic and some if statements. Even the counters you want...

Either use a ladder to c translator as suggested or forget about the ladder structure.

But i understand that you try to stick to ladder though... people tend to forget that programming is only a means to reach a goal and that we're not all programmers in the first place.

Ladder still rocks and is a powerful tool for process control and machine control.

Absolutely, ladder logic is a very easy to use yet powerful tool for solving many problems.
However it is not a good idea to devise a solution to your problem in ladder logic and then implement it in C/C++, which is what ash901226 seems to be trying to do.

If your solution is in ladder then implement it in ladder, not C or C++.
Likewise if your solution is devised in C/C++ implement it in C/C++, don't tie yourself in knots trying to convert to ladder.