Shop OBEX P1 Docs P2 Docs Learn Events
Plc ladder logic compiler idea — Parallax Forums

Plc ladder logic compiler idea

Peter JakackiPeter Jakacki Posts: 10,193
edited 2008-03-11 12:33 in Propeller 1
Ron Nollet mentioned it would be good to be able program in Ladder Logic, the language of PLCs. Here's an idea for a dirt simple Ladder Logic compiler. Imagine the diagram is coded in ASCII characters to represent the various functions and that this closely matches a normal ladder diagram. By using very simple rules it should be possible to extract the symbols and generate interpreted byte codes to represent the operation. When the parser sees certain character sequences such as -|/|- it interprets this as a normally closed signal. The label for this was parsed on the preceding line and it remembers the value of the label from the position on the line. Where the symbol starts on a line is the index into the line array where labels and data are stored.

It's after midnight and I had a very late night last night so I may have missed a few things but bear with me.

For a stand-alone system the compiler could be written in Spin itself and the ladder logic diagram could be stored as a text file either in EEPROM or SD card on the target. Otherwise a compiler could be written in VB or whatever to generate the byte codes. Of course the Prop could use it's font characters in place of the standard characters to improve the display if compiling on the Prop and yet the parser remains the same.

SIMPLE LADDER LOGIC PARSER AND COMPILER

The ladder diagram is an ASCII text file representing the ladder logic
The parser can read the labels and assign them to a memory corresponding to it's X position on the line.
Symbols are extracted from the input stream and simple rules are applied working off the X position memory and a data stack.

The labels and symbols are compiled as byte tokens which are then interpreted by the runtime engine in Forth fashion either
with a Forth itself or a simple engine written in assembler or Spin.

A brief step-through is given below. I'll leave it to forum members to make some sense of it while I get some sleep for now.

0123456789012345678901234567890123456789012345678901234567890123456789

|   X000     X001
|----| |------| |---| 
|                   | 
|   X004     X005   | X002
|----| |------| |---|--|/|---|
|                            |
|   X006     X007            |
|----| |------| |------------|
|                            |
|   Y000                     |  X003                      Y000
|----| |---------------------|---|/|-----------------------(
|

SYMBOLS
        space - clear value from X memory
|       Left rail - dummy
|-      Left junction - push TRUE onto data stack
-| |-   Input N/O - AND with data stack
-|/|-   Input N/C - INVERT and AND with data stack
-|-     Junction  - OR with data stack
 |      Wire      - maintain value in X memory
-(      Output    - STORE data from stack to output

LABELS
X Y     Signal    - Read value and mark this position along the line as that value (offset Y label values)



COMPILING THE DEMO PROGRAM LINE BY LINE:
SYMBOL  CODE                    COMMENT

|                               Ignore
X000    0 4 XP!                 Mark X postion 4 with value of 000
X001    1 13 XP!                Mark X postion 13 with value of 001
X002    2 22 XP!                Mark X postion 22 with value of 002
X003    3 32 XP!                Mark X postion 32 with value of 003
Y000    0 58 XP!                Mark X postion 58 with value of 000

|-       TRUE                   Push TRUE onto stack
-| |-    4 XP@ TEST AND         Read value of input 000 (taken from X position memory) and AND with stack
-| |-    13 XP@ TEST AND        Read value of input 001 (taken from X position memory) and AND with stack
-|       20 XPOR!               POP stack and OR with X position 20 memory

X004    4 4 XP!                 Mark postion 4 with value of 004
X005    5 13 XP!                Mark X postion 13 with value of 005

|-      TRUE                    Push TRUE onto stack
-| |-   4 XP@ TEST AND          Read value of input 004 (taken from X position memory) and AND with stack
-| |-   13 XP@ TEST AND         Read value of input 005 (taken from X position memory) and AND with stack
-|-     20 XP@ OR               OR with X position memory - save on stack
-|/|-   22 XP@ TEST INVERT AND  Read input 002, INVERT then AND with stack
-|      30 XPOR!                POP stack and OR with X position 30 memory

X006    6 4 XP!                  Mark
X007    7 13 XP!                 Mark

|-      TRUE                    Push TRUE onto stack
-| |-   4 XP@ TEST AND           Read value of input 006 and AND with stack
-| |-   13 XP@ TEST AND          Read value of input 007 and AND with stack
-|      30 XPOR!                POP stack and OR with X position 30 memory

Y000    100 58 XP!              Mark this position as Y000 (100)

|-      TRUE                    Push TRUE onto stack
-| |-   4 XP@ TEST AND          Read value of input Y000 and AND with stack
-|-     30 XP@ OR               Read X position 30 memory and OR with stack
-|/|-   32 XP@ TEST INVERT AND  Read input 003, INVERT then AND with stack
-(      58 XP@ WRITE            Write stack to output Y000

     *** TOTAL OF 87 BYTES ***  Assuming byte codes also encode literal values directly
The compilation of the X position can be optimized to say 4-bits as part of the opcode. This would reduce the
program size to 62 bytes.



LADDER LOGIC RUNTIME BYTECODE DEFINITIONS

XP@ ( adr -- data )           \ read data from XP array
XP! ( data adr -- )             \ Store data into XP array
XPOR! ( data adr -- )           \ OR data with XP array
TEST ( signal -- true/false )   \ Test the state of the signal and return true or false
AND ( n1 n2 -- n3 )             \ AND the top two items from the stack and push the result
OR ( n1 n2 -- n3 )              \ OR the top two items from the stack and push the result       





Of course ladder logic is not the most efficient way to program but it is the way many PLCs are programmed. There is probably some fatal flaw in my idea but for some reason I though I'd throw it out there to at least get more ideas flowing. I haven't even thought about latches and timers etc yet.

*Peter*

Post Edited (Peter Jakacki) : 3/10/2008 3:22:20 PM GMT

Comments

  • hippyhippy Posts: 1,981
    edited 2008-03-10 15:54
    I did some work on parsing ladder logic this way but I'm not a PLC programmer and I
    found it all got quite confusing once one gets beyond simple switches, AND's and OR's.
    All those X's and Y's had me done in. I couldn't see any gain in what I was doing so
    moved onto something else.

    It should be possible and there are also Ladder Logic programming tools, some of
    which can generate output code which can be turned into bytecode which can be
    interpreted. One pulled at random from Google : www.cq.cx/ladder.pl

    Comfile Technology sell CUBLOC which is a Basic Interpreter ( ala Basic Stamp ) which
    also supports Ladder Logic programming, which is why I was looking at how this could
    be done for another potential product : cubloc.com/product/01_01.php

    Ladder Logic like Fuzzy Logic, despite its use, may be a niche market so whether there
    is enough momentum to garner support and help for such a project I don't know, but
    I cannot see anything which makes it a non-starter.
  • QuattroRS4QuattroRS4 Posts: 916
    edited 2008-03-10 16:04
    Peter,
    Once Ron mentioned it - I was wondering how long it would take .. good work ..

    also refers to - http://forums.parallax.com/showthread.php?p=714616

    John

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    'Necessity is the mother of invention'
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2008-03-10 17:10
    Upon my first exposure to ladder logic nearly thirty years ago, I though, "OMG, what an odd, awkward way to program!" But I was soon to discover that, for industrial control, this was — and still is — the way automation is done. In fact, many plant engineers have never programmed with anything else.

    The Propeller, I believe, makes an excellent core processor for a PLC. One cog could handle all the ladder logic, with other cogs dedicated to status display, input filtering (e.g. quadrature decoding), high-speed timers, specialized outputs (e.g. PWM for motor control), etc. To be effective, though, at least as much effort would have to be expended on the PC-side development tools (e.g. graphical ladder editor) as on the Propeller code. In any event, it seems like an interesting and worthwhile project!

    -Phil
  • bambinobambino Posts: 789
    edited 2008-03-10 17:15
    I live in the Carpet Capitol of the world "Dalton Georgia" and PLC's have a foot hold here so deep it is futile to think a guy like me can make a product they would buy. Unless their work force (Trained in Ladder Logic) can service or program it folks like Allen Bradly are the only names they will listen to. Just because the prop could do it faster or cheaper means nothing considering the amount of retraining they would have to do for their on service people. And haveing one guy "Like me" service them all really makes them sick, because my next service could be in a competiters building. Considering their own employees get fired if they so much as bring a camera phone to work with them, they have to be able to work, fix and service their own equipment or they don't buy it.
    Kudos to you and anyone else that can open this market for me.

    I've never attempted ladder Logic but maybe by the time this idea gets rollin pretty good I'll be proficient enough with the prop to make use of it
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2008-03-10 18:00
    Bambino,

    You're right about the loyalty to Allen Bradley and other major PLC suppliers. I've seen that myself, and it's a hard barrier to overcome. But an aversion to novelty is understandable when you consider that every minute of downtime in a large plant can cost thousands of dollars. A plant manager's biggest concern isn't, "How much does your system cost?" but, "How fast can you get here when things go bad?" A large supplier with local offices will have the edge every time.

    -Phil
  • hippyhippy Posts: 1,981
    edited 2008-03-10 18:05
    bambino said...
    Unless their work force (Trained in Ladder Logic) can service or program it
    folks like Allen Bradly are the only names they will listen to.

    I think the solution there is to take the approach used for PropJavelin; use existing development
    tools to create the executable code and then set about executing that code on a Propeller. Split
    that from any home-brew front-end which should generate the same code as the commonly used
    development tools do.

    A clone of an existing product seems far more likely to gain acceptance than something new or
    radical. Just doing the emulation and not the tools cuts development significantly, although any
    reverse engineering necessary adds to it. If a PLC programmer can code and download to a
    PropPLC they will care less that it's not their usual physical device.

    Does anyone know any PLC Programming Tool which can be leveraged this way ? Ideally free or
    the scope for developing the project becomes quite limited.
  • whickerwhicker Posts: 749
    edited 2008-03-10 18:09
    There's a standard for Industrial Programming called IEC-61131-3. Basically, the language called "statement list" (STL) is the "assembly language" of ladder logic; Peter you'd might want to look at that if you haven't already. STL has a standardized syntax.

    I work for a small OEM, and I'm happy to say that Ladder Logic is at least mostly going away because of a newer product called a Motion Controller. It's usually a three-in-one-box deal, basically it runs an industrial program, controls 3-phase servos, VFD's, and/or stepper motors, and handles I/O communication transactions. There are also some (imho rather failed) attempts to try and integrate the visualization (HMI) aspect into the same box as well, but anyway.



    With the motion controllers and newer more powerful PLC's there's a great language called "structured text" (ST) which is typically described as being a Pascal variant, and it's absolutely wonderful to use in conjunction with LL. In addition to function calls, there's actually a form of "stateful objects" called function blocks (FB's), which help immensely with data encapsulation and organization. Most programming software lets you use named-variables instead of just raw memory locations. That way if you need to change what the variable is assigned to, as in making it an internal bit instead of an output, it's a simple change to a single table cell or program code line.

    I literally cry whenever I see a Ladder Logic program with only one super-long main section that is chock full of global variables, one-scan output glitches (race condtions), and dangerous assumptions. Seriously, it does not have to be this way any more, and I'm doing everything I can as a programmer to make my programs more readable, organized, and maintainable. There's job security, and then there's incompetence.
  • crgwbrcrgwbr Posts: 614
    edited 2008-03-10 18:21
    I must admit, I hate working in Ladder. Normal written languages seem much easier and much more useful. That said, a Ladder Compiler would be greatly useful to those who are used to working in a Ladder environment. This would help push the Prop into more industrial applications for potential PLC replacement.

    To me at least, it seems to easiest way to do this would be to write the actual interpreter in SPIN or ASM. The Computer app could compile the Ladder symbols into a text file (ex. N.O. Switch = %00000000; N.C. Switch = %00000001, etc.) and store it eeprom or an SD card. Then the Prop interprets this into commands. It doesn't seem like this would be overly hard to do. The difficult part would lie in distributing the work evenly in all available COGs, to get the most power out of the Prop.

    Regards,
    Craig

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    My system: 1.6 GHz AMD Turion64 X2, 4GB DDR2, 256MB ATI Radeon Graphics card, 15.4" Widescreen HD Screen

    I have a duel boot of Ubuntu Linux and Windows Vista. Vista, because it came with the PC, Ubuntu because I like software that works.

    "Failure is not an option -- it comes bundled with Windows."

    Use The Best...
    Linux for Servers
    Mac for Graphics
    Palm for Mobility
    Windows for Solitaire
  • Peter JakackiPeter Jakacki Posts: 10,193
    edited 2008-03-11 00:40
    Thanks for the feedback. I had a look at that PIC/AVR Ladder Logic compiler and was aghast at the code size. When I say dirt simple I mean something that would fit onto a page.

    Here is a version that just uses the Forth parser so there is nothing complicated. It is even half readable too. The symbols are simply Forth words that are defined and become part of the dictionary as usual. If you type in the ladder program without defining the function by skipping the "LADDER ..." line then it will interpret the logic as you type each line. By using the word "LADDER" you are simply creating another word in the Forth dictionary by that name that can be invoked from the keyboard or by another Forth Word (function).

    Again this is only a quick demonstration as to how it could be done.

    *Peter*

    { DEMO LADDER LOGIC
    
    ORIGINAL LADDER LOGIC DIAGRAM 
    
    |   X000     X001
    |----| |------| |---| 
    |                   | 
    |   X004     X005   | X002
    |----| |------| |---|--|/|---|
    |                            |
    |   X006     X007            |
    |----| |------| |------------|
    |                            |
    |   Y000                     |  X003                      Y000
    |----| |---------------------|---|/|-----------------------(
    |
    }
    \ FORTH CODE BELOW
    
    variable inputs
    variable outputs
    : - ; IMMEDIATE                  \ dummy spacing, compiles nothing
    : |<     ( bitnum -- bitmask )   1 SWAP SHL ;
    : -||-   ( flag adr -- flag )    |< inputs AND 0<> AND ;
    : -|/|-  ( flag adr -- flag )    |< inputs AND 0= AND ;
    : -(     ( flag adr -- )         SWAP IF outputs SET ELSE outputs RES THEN ;
    : -()-   ( flag adr -- flag )    32 + -||- ;
    : READ                           INA@ inputs ! ;
    : WRITE                          outputs @ OUTA! ;
    ALIAS FALSE |
    ALIAS TRUE |-
    ALIAS : LADDER
    ALIAS ; END
    ALIAS OR -|
    
    
    
    \ DEMO LADDER PROGRAM
    LADDER DEMO
    READ
    |
    |- 00 -||- 01 -||- -|
    |- 04 -||- 05 -||- -| 02 -[noparse][[/noparse]/]- -|
    |- 06 -||- 07 -||- - - - - - - -|
    |- 00 -()- - - - - - - - - - - -| 03 -|/|- 00 -(
    WRITE
    END
    
    
  • bambinobambino Posts: 789
    edited 2008-03-11 01:22
    @ Hippy, I think you nailed it when you said:
    (If a PLC programmer can code and download to a
    PropPLC they will care less that it's not their usual physical device.
    )

    Considering what Whicker said and everyones opinion of LL, maybe a turn of the tides could be accomplished by making a compiler that gave the programmer access to the spin/assembly as well. Then die hard LL individuals could use the product, and up and comeing more efficent intellects could decide which works best for them.
    ·No doubt spin will win. Who wouldn't want to be paid to work in a language that they can take home and make a hobby of as well. It's very doubtful that any PLC programmers have a 3 to 400 dollar PLC boe-bot at home to chase their cats with!
  • crgwbrcrgwbr Posts: 614
    edited 2008-03-11 12:33
    bambino said...
    It's very doubtful that any PLC programmers have a 3 to 400 dollar PLC boe-bot at home to chase their cats with!

    I did that once, with an S7-300. [noparse]:)[/noparse] I had a couple days before I had to return it, so I figured, why not. lol

    Anyway, I think that would be a good path to take. That way, a more capable programmer (even if they like LL) could write the simple part of the code in LL, then change tabs, and there would be the SPIN or ASM of everything he just did in LL. Then, he could edit the code however he wanted. I don't imagine it would be to hard to compile LL to SPIN, but SPIN to LL would be a nightmare. So pehaps, once they start editing the code, they would not be able to switch back to LL.

    Just some thoughts,
    Craig

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    My system: 1.6 GHz AMD Turion64 X2, 4GB DDR2, 256MB ATI Radeon Graphics card, 15.4" Widescreen HD Screen

    I have a duel boot of Ubuntu Linux and Windows Vista. Vista, because it came with the PC, Ubuntu because I like software that works.

    "Failure is not an option -- it comes bundled with Windows."

    Use The Best...
    Linux for Servers
    Mac for Graphics
    Palm for Mobility
    Windows for Solitaire
Sign In or Register to comment.