Learning PLCs from the very beginning - Page 1
Forum section: electronics / beginners

author: unitedatoms
author_rank: Frequent Contributor
timestamp: January 31, 2020, 12:36:37 am
content: I hope that this can help someone else, who is just starting with PLCs. The fascinating devices which are designed to never fail no matter what.So thanks to work duties, I was volonteered by my team to go and learn PLC thing. To learn officially in 4 days.Here is my thoughts about PLCs at day 3 of learning, from the point of view of software/firmware developer, a list of things I made for myself, to share with other newbies. It is mostly conclusions, not the direct content of what they teach you.1. No fancies there in a languages (ladder language, plain text, diagrams etc. they are all about the same)2. No pointers3. No stack (nearly everything as parameter is passed by value, may be using stack after all, but hard to tell)4. No loops (they are there, but not recommended, I mean loops like FOR, WHILE, REPEAT UNTIL)5. No strings (not recommended, unless you really need it)6. No heap7. No dynamic allocation, deallocation8. No exceptions (except may be divide by zero or similar)9. No jumps or goto (can be used but explicitely not recommended)10. No need for code address labels, since no goto11. No ends, returns, exits or halts. The scanning keeps looping forever.12. No stepping, so no debugger, only monitor13. No breakpoints14. No OS or kernel or framework, it is true bare metal15. No error handling since it is not an OS16. No tracing outputs, only monitoring (or I did not lean it yet)17. No threads18. No locks since there is no threadsSo what you have ? So far it looks like a sort of pre FORTRAN with only static manual allocation of DATA and CODE.I hope this is helpful for software minded people who wonders what PLC actually is.It is not a criticism, but just an observation how much of usefulness one can get from programming, when everything unnecessary is removed.ha ha.Edit: And the good news is that you need nothing, just a bunch of relays to build civilization upward from the complete disaster, just by using PLCs alone.

author: Nusa
author_rank: Super Contributor
timestamp: January 31, 2020, 01:50:03 am
content: PLC's can fail. Ask me how I know.

author: unitedatoms
author_rank: Frequent Contributor
timestamp: January 31, 2020, 01:56:19 am
content: Quote from: Nusa on January 31, 2020, 01:50:03 amAs much as I learned on day 3, it is only people who fail, not PLCs, so I am asking how ?I thought that PLCs are next to last of super reliable things, like QNX in automotive or avionics.

author: Nerull
author_rank: Frequent Contributor
timestamp: January 31, 2020, 02:00:25 am
content: QuotePLCs typically run a RTOS which hosts the interpreter that is actually running your ladder logic. Allen Bradley PLCs run either Microware OS-9 or VxWorks, most others run VxWorks.

author: Ground_Loop
author_rank: Frequent Contributor
timestamp: January 31, 2020, 03:01:08 am
content: I think the most difficult part of developing a PLC based system is setting up all the IO and networking correctly. After that, ensuring all the module firmware is compatible.

author: Berni
author_rank: Super Contributor
timestamp: January 31, 2020, 06:49:37 am
content: You are looking at PLCs from the wrong side of the fence.If you are a programmer and have used C or anything similar they indeed look like horrendous atrocities that must have been designed by satan himself to torture anyone who is unfortunate enough to have to program it.But there are also the oldschool industrial automation engineers that have been designing control systems for massive machines by filling whole cabinets full of relays and wiring them together in a way that produces the required logic. Before computers came around this was the only easy way to do it. So because training people is expensive they made PLCs that are basically a glorified relay cabinet stuffed into a tiny computerized brain box. The engineers already used ladder diagrams to plan out the relay cabinets, except now they don't have to painstakingly wire it all up, instead they just draw it and upload it in this magical PLC brain box and it emulates the relay cabinet in software.So in the regard of making a Relay Cabinet 2.0 they certainly did the job nicely. Its smaller, cheaper, uses less power, is faster to 'wire up' and easy to debug from a PC, or even control remotely over a network.Automation engineers are not software developers. They just want to stick together some 'industrial Lego' and have the giant machine do it's things so the bosses are happy. It doesn't matter if its expensive or inelegant, as long as the manufacturing line is ready to start up next Monday morning. And these PLCs are nice modular things that they can throw in there and quickly get the thing up a running (The required logic if often pretty simple anyway).So there is some sense behind the madness. I admit i also hate PLCs, but i can also see why some people like them.

author: SmallCog
author_rank: Frequent Contributor
timestamp: January 31, 2020, 08:16:15 am
content: PLC’s do go wrong, but to be fair it’s normally things like power surges that do the damage... I don’t remember the last time I had one just spazz out and need a reset for no obvious reason.PLC’s are used in all sorts of places to do all sorts of things. Ours run autonomously and although they’re monitored remotely it’s not uncommon to loose comms from a site for a month or more. ISP’s can take quite a while to sort issues in remote areas...Anyway the PLC’s just chugg away doing this thing. We visit these sites once a year to check on things - that’s mostly about the sensors attached to the PLC’s rather than the modules. Most of our modules only get turned off for their lithium backup battery to be replaced - this could be done hot but we figure a power cycle every few years is probably a good thing.I have other types of autonomous non PLC gear that is far worse behaved, some of it has analogue timers power cycling it to bring it back if it hangs due to long standing intermittent undiagnosed gremlins.

author: I wanted a rude username
author_rank: Frequent Contributor
timestamp: January 31, 2020, 09:04:54 am
content: Quote from: Berni on January 31, 2020, 06:49:37 amHalf way through unitedatoms' list of what PLCscan'tdo I found myself asking,are they even Turing-complete?So thanks for putting them in context.

author: senso
author_rank: Frequent Contributor
timestamp: January 31, 2020, 10:05:47 am
content: Quote from: unitedatoms on January 31, 2020, 12:36:37 am1. What do you mean by no fancies?2. There are pointers (https://support.industry.siemens.com/cs/document/24521805/why-are-the-bit-and-byte-addresses-changed-when-indirectly-addressing-a-program-converted-from-s5-to-s7-?dti=0&lc=en-USFinding new docs up to the reader)3. There is a stack, heck, STL from Siemens is all stack based programming(kinda like a RPN ugly child)..4. You can do loops in lots of ways beyond using those instructions, all machines have a work loop, or they woulnd't cycle after making one part..5. Lots of strings, made a work station with an R&S Multimeter that does eletrical testing and the PLC talks to the DMM via SCPI(strings over TCP/IP).6. No need7. So does code that runs on a plane, no memory allocation after take off, its just so you dont blow you memory or fragment it, for safety..8. LOTS of exceptions, on Siemens its called OB and can be used to catch lots of system failures, divide by zero being one of them9. There is jumps and goto, use to your earth contempt, just makes reading core a bit harder if you are not used to that mind-set10. See 911. Thats the whole point of a PLC, a micro also doesn't stop its clock, nor you usually run a couple lines of code and then return 0 from main..12. You can kinda make it step using extra logic in your code, and I also felt the lack of it, until I got used to the monitor, that allows you to watch everything that is going on, and you can pause execution, and the simulators usually allow single stepping.13. Put a NO contact with an AlwaysTrue where you want to stop.14. There is an OS in there, and there is a massive framework, I can connect to a TCP server or client in one function call, send/receive data with another..15. Lots of error handling, see point 816. Siemens, OMRON and AB all allow to trace signals into graphs, all called something akin to tracing, its there, read the docs17. Its supposed to work that way, top to bottom, left to right execution.18. Easy to make a lock, just use a bit and NC/NO it, every machine works with lots of locks..Its a PLC, its not a micro-controller, its made for a job, and as a different mind-set that what you expect coming from the embedded world, thats for sure, but they are pretty capable little devices, just dont expect them to be fail proof, nor are they supposed to be "safe" just because they are a PLC.For safety use safety relays, and safety sensors, or a safety PLC, a regular PLC won't cover you in case of accident, nor will a safety one if you dont know how to program them..

author: Berni
author_rank: Super Contributor
timestamp: January 31, 2020, 10:32:03 am
content: Quote from: I wanted a rude username on January 31, 2020, 09:04:54 amThey are touring complete, but then again very simple and crude machines can be touring complete (yet be incredibly difficult to make it do anything useful, like for example the language called 'brainfuck'https://en.wikipedia.org/wiki/Brainfuck)You could for example make a reasonably capable chess playing robot on a normal PLC, but you are going to have one hell of a time writing the program for that. Heck in theory you can write a 8051 CPU emulator on a PLC. Doing such a thing would be incredibly slow tho since the language the PLC executing is in itself executed by an interpreter in software (Or at least i have not yet seen a real hardware CPU that executes this weird PLC assembler instruction set)Thing is that most industrial automation needs fairly simple logic so this clumsy language works well enough for the job while making it hard for the programmer to make stupid mistakes like trampling over RAM, make memory leaks, mutex deadlocks.. etcAll of the more complex functionality is handled by other underlying systems. Things like TCP/IP for remote monitoring and control is all done in the PLCs 'OS' If you hook up a graphical UI display then the display does all the graphics thinking, the PLC simply makes its internal variables available to it via 'OS magic'. The software running on the graphical display is again a hidden OS that is actually programed in some interpreted language using a software where you drag and drop buttons and dials onto the screen rather than make OpenGL draw calls or something.

author: janoc
author_rank: Super Contributor
timestamp: January 31, 2020, 10:59:23 am
content: Well, re PLC limitations and Turing completeness - both are pretty much irrelevant, IMO.What the OP describes is very likely the "structured text" (ST) programming language. For those that haven't seen it, it is very similar to BASIC, with some vendor-specific things thrown in, such as addressing registers representing I/O banks or a block that talks TCP/IP or Modbus for you. Good enough for doing things like periodically reading switches and temperature and updating an 7 segment display. Or changing speed of a motor using PWM. Or sequencing movements of some motors in a machine. It is not meant for doing something very sophisticated.You aren't supposed to use loops, PLCs typically have cyclic tasks and timer-triggered tasks for that. Loop in the structured text code would often mean a busy loop, preventing other things from running or preventing the CPU from going to sleep.However, the PLC is typically capable of running programs in multiple languages, so ST is not your only option. There is ladder logic, there are various schematic entry languages ...Also, these things dodiffer a lotbetween vendors and model lines! I have experience with the ABB's AC500 Eco line (the lowest cost one) and when I have compared that to what e.g. Siemens ships, it is very different, both in the way these things are configured, how the language primitives work, which languages are supported, etc.And re PLC not being a microcontroller or "running on bare metal". Neither is true. A typical modern industrial PLC contains one of the beefier micros, either with a lot of built-in flash or an SD-card support for storing the code, running an RTOS of some kind, which then typically interprets some sort of bytecode that the ST or ladder logic has been compiled into using the vendor tooling.The other important thing why PLCs are used is their robustness - while the "smarts" of that "brainbox" are really primitive, the majority of the complexity is in the various protection circuitry. E.g. the I/O handles a dead short to mains without damage (industrial techs are known to mis-wire things), large voltage spikes (relays or motors switching), overcurrent, large temperature swings, you name it ...

author: unitedatoms
author_rank: Frequent Contributor
timestamp: January 31, 2020, 11:10:46 am
content: @senso. Agree. The professionals sure have all the rope they need if go into details. I just made list of things what a beginner does not need to know when starts with PLC. Also I got the feel that missing things are never used in 99.9% of real world PLC programs.Basically I like how simple PLCs are in general, all software people should try programming in PLC. They seem to be an independent branch of computer evolution originating from times before vacuum tubes. May be it is a better entry device for programming in general than other platforms.Other: By locks and threads I meant the mutexes and multithreading, not the latches and ordered execution.

author: senso
author_rank: Frequent Contributor
timestamp: January 31, 2020, 11:20:27 am
content: Regarding what makes them tick, the uber common(in EU) S7-1200 family runs on a Cortex R4:https://sec-consult.com/en/blog/2019/02/reverse-engineering-architecture-pinout-plc/There are a lot of gotchas and catches for the young player with PLC's that might not be so obvious, they are fun to use, and they are way more powerful today than they where even 5 years ago, but for a tool for intro to programming they might not be the best, or maybe they are, but I was already pre-formated to program micros and was going crazy not having a printf over a serial port like I used to do basic debugging, that and writing into I memory space and calling it names why dont this crap one shot doesn't work

author: SmallCog
author_rank: Frequent Contributor
timestamp: January 31, 2020, 11:32:36 am
content: Quote from: janoc on January 31, 2020, 10:59:23 amI admit to nothing...

author: forrestc
author_rank: Unknown
timestamp: January 31, 2020, 11:58:22 am
content: Quote from: unitedatoms on January 31, 2020, 11:10:46 amHere's my $0.02 about PLC's:Ladder logic, in particular, is much easier to express a lot of 'machine operation' or 'process control' in than C code or any other programming language, once you understand the basics of how it works.Take for instance a simple thermostat - read temperature from a sensor, and turn a relay on if the temperature is above a certain value. It's one rung of ladder logic.In a 'real' programming language you'd end up having to declare variables, and then write a loop that reads a value from an ADC, possibly converts it to a usable value, then does a compare, and then sets an output based on it.Need to add some hysteresis? Two more logic elements on the same rung in ladder logic. Having coded hysteresis in a Microcontroller, I can guarantee that while it isn't that difficult, it isn't as easy as in a PLC.But, you have to realize that this is a niche area. If you're controlling a machine (or more typically multiple machines), then a PLC is often the first choice, because it's purpose built for that. But you aren't going to find PLC's replacing data processing equipment any time soon.Just a recent example: I have a PCB assembly line here. There are various pieces of gear that need to be turned on depending on various conditions. For example, if the Pick and Place is in use, it needs compressed air. If the reflow oven is on it needs the exhaust fan to be running. The wave solder needs both. For the wave solder machine, the exhaust fan needs to run for about an hour after its turned off because it takes a while to cool down and it needs the exhaust fan on during that time. On the air compressor, we need a manual way to turn it on if we need compressed air for a period of time, but we also would like to be able to have it turn itself off if the staff forgets, so it isn't running during off hours. Oh and also on the air compressor, the unit we have here has had the pressure switch stick on in the past, causing the unit to run continuously which isn't a good thing for a compressor to do (it eventually blows one of the overpressure valves and starts jetting air), so we needed to add some sort of overpressure detector which will recognize this as a fault and shut the thing off until someone who knows what they're doing will look at it. Add a few status lights and emergency stop switches and you get the idea.All of the above could have been done in an Arduino or the like, but it was much easier to implement in a modern, inexpensive PLC. For like $200 or so I got the controller and all of the I/O modules I needed (a bit more for a contactor for the compressor and the buttons and indicators). Put it in an electrical cabinet, wire everything up, and with 7 rungs of ladder logic I was done. Yes all of the above was done in 7 rungs.I've done far more complex work on PLC's in the past, needing far more than 7 rungs, but in each case, working through it was just a logic exercise. It's a completely different thing than programming. It's probably more like a 'slow, sequential FPGA' than a microcontroller.

author: GerryR
author_rank: Frequent Contributor
timestamp: January 31, 2020, 12:40:47 pm
content: To be fair to the OP, a 3-4 day course is barely going to scratch the surface of PLC programming and applications. It isn't until you have to design and complete a system for a machine process or task that you really get to learn and see what PLC's are capable of doing. I've been a self-employed automation engineer for over 30 years (mostly retired now), doing the machine design, control system design and the software, as well as the build of each system. Some software can get quite complicated, and occasionally, I've had to get help from those who just specialize in PLC software to get the job done. But as stated above, once you know the requirements, then defining the I/O needed to do the job becomes the task. If you look at Rockwell Automation (Allen-Bradley products) and similar companies (like Siemens), I think you will find that just about anything you can do with C, or many other languages, can be done in ladder logic. Automation is a fun and challenging area to work in!

author: janoc
author_rank: Super Contributor
timestamp: January 31, 2020, 05:02:45 pm
content: Quote from: unitedatoms on January 31, 2020, 11:10:46 amUh, hell no. That's like advocating BASIC as a first/teaching language, along with a load of inevitable kludges required to do anything useful because the system is so primitive. The highest level concept is a procedure/function there (in the BASIC or SQL sense, i.e. fairly different and much more primitive than anything a "normal" programmer may expect). You don't get any more advanced control flow, no meaningful data structures beyond primitive data types, etc.That something is primitive doesn't mean it makes a good learning platform. A big part of learning to program is development of algorithms and learning to convert your data into abstract data structures. And having to learn that using a language where you can't even make a proper record type or a buffer is not really a good pedagogy. If you want to learn programming using hardware (not the best idea, IMO, because you are adding needless complexity), then Arduino or Wiring are likely much better platforms than a relatively expensive PLC programmed using obscure languages and proprietary, vendor-specific tools, all the while fighting with a language that is based around almost 100 years old automation concepts and the closest mainstream sibling to it is BASIC - the canonical example of aterribleprogramming language for learning programming ...BTW, for those that haven't seen it, here is a handy tutorial of the Structured Text:https://www.plcacademy.com/structured-text-tutorial/Of course, any vendor-specific things you would have to find in the vendor's documentation but the language itself is actually an ISO standard and the CODESYS IDE is a free download (e.g. ABB uses that directly for their PLCs, along with another tool used to configure the controller - set up the I/O banks, configure networking, etc.)

author: Nerull
author_rank: Frequent Contributor
timestamp: January 31, 2020, 07:30:54 pm
content: Quote from: unitedatoms on January 31, 2020, 11:10:46 amInside a PLC is a normal computer, running a software stack that presents a programming interface designed to be familiar to people used to using relay logic. Your code isn't running in hardware, and it isn't some special branch separately evolved from normal microprocessors.

author: vu2nan
author_rank: Contributor
timestamp: January 31, 2020, 07:34:02 pm
content: Fifty years ago, the mainstay of automatic special purpose machine control was hard-wired relay logic which was supported by electro-pneumatic/motorised timers, electromagnetic digit-wheel counters, step selectors, and latched relays.Special purpose machines had come into being for carrying out reliable, repetitive and sequential machining operations in the mass manufacturing of automobile components.Then came electronic logic gates, hard-wired gate modules, timers, counters and shift registers followed by basic microprocessor control which did not gain ready acceptance (resistance to change).The first microprocessor-based PLCs catered only to logic functions using input, output, timer, counter and latch modules. Proficiency in relay logic made 'Ladder Diagram' programming/troubleshooting easy and that enabled the take over of automatic special purpose machine control by PLCs.Later, introduction of arithmetic and process control functions made the PLC quite versatile. Then came servo control & computer numerical control and the rest is history!In the test and measurement field the industrial PC rules, with the support of dedicated modules for data acquisition & control including software, supplied by companies like National Instruments (Virtual Instrumentation using LabView).Regards,Nandu.

author: unitedatoms
author_rank: Frequent Contributor
timestamp: January 31, 2020, 09:18:14 pm
content: @janoc. I find the PLC is pure in some academic sense. It is real life implementation of some abstract automata like Mili or Moor, it also has no self code modification, so it is not a Turing machine. There is perhaps bazillion papers about provability of correctness. It may be possible to prove that there is no dead code, infinite loops, or other ill effects in the code, using some theorems by click of a button.What I am saying is that PLC are not primitive, they are fundamental. They are not artificially limited, they are perfectly complete to provide some strong guarantees coming from the theories.I do not mean that PLC is good for learning programming as a whole. It is good for learning very first programming attempt to understand what automata is before diving in processors. It is very useful demonstration of things like determinism, atomicity, statefulness and statelessness, combinatorics, Boolean logic, volatiles, finite range arithmetics. gates, latches etc. And it is very clear demo without early introduction of consequent complex things I listed in original post. I think if more devs learned PLC hand on, my blue ray player whould be more responsive than it is now, and some apps on the phone whould never break to talk to car console screen on carplay. Ha ha

author: I wanted a rude username
author_rank: Frequent Contributor
timestamp: January 31, 2020, 10:14:14 pm
content: The inherent parallelism seems ideal for control in an interrupt-driven environment. I love finite state machines, but they lose their elegance as soon as the possibility arises of multiple interrupts occurring simultaneously.In fact, it would have been useful on a recent project. Tempted to giveOpenPLCa shot.

author: janoc
author_rank: Super Contributor
timestamp: January 31, 2020, 11:07:36 pm
content: Quote from: unitedatoms on January 31, 2020, 09:18:14 pmUm, only in the sense as assembly language on a CPU is an implementation of such. There is nothing particularly special about the PLCs in this regard, notabene when you are never interacting with the raw hardware but always talking to some sort of interpreter/VM running on top of an RTOS.Quote from: unitedatoms on January 31, 2020, 09:18:14 pmSelf code modification is not required for something being Turing complete (btw, nothing can be a "Turing machine" unless you physically build a contraption with an infinite tape a read/write head). The Structured Text language certainly is Turing complete as are most ladder logic implementations. Turing completeness of a system only means that you can implement a Turing machine with it (which, in turn, means it can execute all Turing machine programs and since it can do that, it is universal). You certainly can do that with both ST and ladder logic, within reason (no infinite tape because you don't have unlimited memory).Quote from: unitedatoms on January 31, 2020, 09:18:14 pmOn a PLC code? With side effects, with hardware modifying the state of your code in unpredictable ways (e.g. interrupts or the RTOS feeding data from outside directly into registers that are mapped onto variables of your code)? Good luck with that. I guess you haven't done anything like this, have you?I have actually done correctness proving (btw, dead code has nothing to do with correctness), both on BASIC-like imperative programs and on structured (C or Pascal-like) code (where it is a bit easier). A system that could prove correctness of an arbitrary code in the usual sense - i.e. that if the program stops, it will give the correct result - on a push of a button doesn't exit. Oh and proving that some program will actually stop is NP hard too ... (i.e. you can't do it in polynomial time, so an untractable problem for a large codebase).Quote from: unitedatoms on January 31, 2020, 09:18:14 pmFundamental? Jeeze, in what sense? What strong guarantees gives you an ARM MCU running an RTOS which runs an interpreter?I mean, sure, you can claim that. But why would you? That's like measuring distances in palms and horse steps and temperature by the pitch of the screaming when you burn yourself. Those "units" also undisputably follow from some theories. I am sure you could calculate even the trajectory to the Moon and back in them, if you really wanted to.But the point is that we choose measurement units or declare something as fundamental because it is in some way advantageous for progressing in the given field - by simplifying computation, simplifying the mathematics needed, making the reasoning easier (e.g. the recent debate about pure functional languages for reasoning about parallelism and computability - stuff like ST being a complete opposite of a functional language).Quote from: unitedatoms on January 31, 2020, 09:18:14 pmNo, absolutely not. And I am saying that as someone who has both a degree in CS, has a teaching qualification and has actually taught programming to both engineers and people with zero software background. There are some very goodpedagogicalreasons why programming at this level is done first with some "toy" languages, such as Logo, Scratch, even Lego Mindstorms and then the students move on to something like Scheme, Python, or in the CS/engineering curricula to something like C or Java.When you are teaching basics of programming youdo notstart with automata, you don't teach atomicity or volatiles, neither anything about gates, latches, etc. (which, btw, a PLC totally abstracts for you - which is the entire point of using a PLC ...). That stuff comes later.Why? Because the student must first learn to walk before they can run. E.g. if they don't understand the concept of a variable, then having to deal with the fact that in a PLC a variable can be mapped to a register that represent I/O if it is at some address and something totally different when it is at another would completely confuse them. The same for the various error states of the PLC, the fact that you can't make proper loops or the thing will hang on you, that there is no meaningful I/O (people learning to program want to use files, not just read switches and blink LEDs ...), etc. The worst thing you can do as a teacher is to have to handwave some stuff as black magic because it is not relevant or too complex - at some point your students will get lost and will consider everything to be black magic.When you are teaching programming to novices, you wantto remove complexity, not to add needless unneeded complications like dealing with an obscure hardware. Until the basic concepts of how the machine worksat the abstract level(i.e.notgates and latches!), what an algorithm is and what needs to be done to create one - by creating an abstract model of the problem being solved, how do you represent your data (types, basic data structures, etc.), you must keep the environment as simple as possible. Only once the students have this settled and digested you may start adding complexity - be it another language, dealing with hardware (e.g. Arduino) or start teaching formal fundamentals of computation, such as formal languages, grammars, automata, basics of parallel computing, etc.Quote from: unitedatoms on January 31, 2020, 09:18:14 pmThat is software engineering, good development practices and techniques for writing correct code. That you really won't learn by hacking up some ladder logic on a PLC which has been expressly designed to be programmed by engineers and techs in the field that have little idea about these concepts (since they are not software engineers but e.g. automation engineers or even electricians).

author: unitedatoms
author_rank: Frequent Contributor
timestamp: February 01, 2020, 12:41:37 am
content: This is interesting discussion. I feel like I hit the point separating Theoretical Computer Science vs Software Engineering. Or simply Science vs Engineering. You possibly are looking at this as arguing about preferred programming languages for teaching. I'd agree that functional languages are well fit for acdemia. I, myself was lucky to learn programming only in Pascal, the language designed for teaching students to program. Any prior attempt to learn, were BASIC (bad), Fort like calculator language (OK but very niche), Fortran (OK, but very obsolete), PDP11 machine code and assembly were dead ends.My point is that all above could be much less painless for me personally, and for any newbie, if there was a stepping stone with perfect minimalism. And I just found it in PLC. I speak from my experience of decades of programming in dozen of languages, as everyone in software world. Java, C, C#, SQL, JavaScript etc.I could not imagine that things likehttps://en.wikipedia.org/wiki/Moore_machinehttps://en.wikipedia.org/wiki/Mealy_machineare not just academic abstractions. But have a practical implementation. It was in my curriculum before I learned higher level Software Engineering. The Noore and Mealy. They are correct things to learn. Like State Machines. The Turing Machine (not the Turing Completeness) is just an oddity, which should be skipped. There is a certain sentiment in Software World of disapproval of Theoretical Computer Science folks. May be on grounds of notion of Infinite Automata Machines etc. But I may be I am not updated what happened in this world in last few decades. May be current debate is around of validity of Deep Learning or some other bullshit.The pedagogical value, we seek, is possibly is out there somewhere. For the sake of making systems absolutely correct with provable correctness, unhackable. And saying this, I find the trend (from few years ago) of some universities teaching Java for programming is total absolute crap of "teaching" computer language. It is very wrong language to learn as first language. Same for any language which is not Pascal, Rust, PLC, C (not C++) or assembly. Java was in big competition with rest of languages to have highest possible feature count. It is a useful practical language for some scalable solutions, but it is overloaded with features because it is design to compete with other languages.Re: about ARM hardware running hidden OS layers in PLC. I assume that the original PLC designs were truly bare metal with specialized CPUs running assembly code without any interpreters. The instructions in machine code were directly placed into memory of devices and that was all the user had. No compilation or interpretation.Edit: And I am not in position to criticize teachers. People who chose to teach other people to program. Teaching looks like a very hard occupation. It is very mad way to channel your passion. If I ever was a teacher of any kind, I'd rather just beat and starve students instead of carefully going though reams of written material, prior art, available science etc. I learned something this last few days. And it was because of teachers.

author: janoc
author_rank: Super Contributor
timestamp: February 01, 2020, 02:48:11 pm
content: Quote from: unitedatoms on February 01, 2020, 12:41:37 amAnd that's where you hit the distinction between training a plumber and training a guy that actually designs those things. The first one doesn't need to know anything about the formalism of computation, they just need to know how to apply some pre-made "recipes"/procedures to solve their problems.The latter? Not so much. You can't really stop with teaching finite state automata (whether that's Mealy or any other variant is completely irrelevant, they are equivalent). Why? Because then you wouldn't be able to build e.g. a compiler or any sort of parser.Most programming languages are not representable using a finite state automaton, you need a more powerful formalism for that. That's why formal languages are taught - grammars and automata and their equivalence. Regular grammars are equivalent to finite state automata - that's e.g. how your regular expressions are matched. But if you have used those, you have likely discovered, that some things can't be matched by them, no matter how complex you make it. There you move on to context-free grammars which are equivalent to stack automata (or automata with counters) - those can match most currently used programming languages. And the class above that are Turing machines, that can handle context grammars and thus pretty much anything you can throw at them.That's why this is being taught. It is important information for anyone who is going to be designing any sort of tools to be used by those "plumbers".Quote from: unitedatoms on February 01, 2020, 12:41:37 amThat's pretty much an impractical red herring. You could make your software provably correct and still get hacked because you are not running it on a perfect hardware. E.g. using one of the recent class of CPU side-channel vulnerabilities due to speculative execution. Or someone will "glitch" the CPU's power line, corrupting the internal state causing it leak data (common way of extracting firmware from locked microcontrollers). "Unhackability" (aka security) and correctness of the code are two completely orthogonal concepts.Worse, proving formal correctness of a program of any sort of realistic size and functionality requires an enormous effort. Even mission critical software for aerospace is not being formally verified like this - it is just not doable at such scale. Good engineering practices (such as handling errors, redundancy, correct design) are much more important than having some firmware 100% bugfree. Bugfree code won't save you if a bit in memory gets flipped due to a cosmic ray hit and your engine blows up as a result.Also, you are forgetting that proving something as correct only proves that the code will do what has been demanded in the specification. BUT it does nothing about the fact that the design itself could be faulty. Your program will give perfectly correct, 100% formally proved results - and your system still blows up, because it has been designed based on incorrect assumptions or not using good engineering practices, such as adding a checksum/ECC to that memory code above to guard against such cosmic ray hits. Proving code correctness will not help you any there - that's pure system design.E.g. the recent Boeing 737 MAX mess is a good example of what happens, both when good engineering practices are followed (the planes have multiple redundant systems for pretty much everything and a mechanical backup!) and when they aren't (allowing a single, non-redundant faulty sensor introduce bad data causing a big problem because of a poorly thought out software system). Those planes didn't crash because of a bug in the code - the system worked exactly as designed. The problem was in the design itself.Quote from: unitedatoms on February 01, 2020, 12:41:37 amThen it is very good you are not actually a teacher. With the exception of Pascal (which has been explicitly designed as a teaching language and it isn't used these days because there isn't any good compiler/IDE for it anymore - the last one was Turbo/Borland Pascal), the others are extremely poor choices for introducing programming concepts. I am not going to repeat the arguments I have made already. I will only say that carpenters don't learn to build roofs by first teaching them how nails are made or how their power drill works neither. It is neither effective nor useful.Re Java - I am not a Java in education fan but Java has displaced things like Scheme and Pascal for the CS 101 classes because it is both widely available, standardized (no matter what platform you are running it it is the same - important for students to be able to use their Macbooks and what not) and it is a practical language used in the industry. That has been one of the major issues with both Pascal and Scheme - it is very demotivating for many students to have to learn something they feel is "artificial" and they don't see its practical use. With Java that complaint was not valid anymore.These days a lot of universities have replaced Java with Python or even Racket (a newer version of PLT Scheme), though. Java is way too complicated with a ton of boilerplate required to get anything meaningful done in these early programming courses.Quote from: unitedatoms on February 01, 2020, 12:41:37 amThat has been true maybe 20-30 years ago. These days you won't find a PLC from a major vendor like Siemens or ABB that works like that anymore. Companies want remote control and monitoring of their production lines, reconfigurability, HMIs, SCADA, etc. - that you can't do without networking, multitasking and with just a small microcontroller. And even the older style PLCs that were like that used interpreters and compilers - I am not aware of an CPU/MCU capable of running e.g. ladder logic directly!If you want that style of learning, that's what Arduino is good for. With all the caveats that now you are adding dealing with hardware issues on top of the mental difficulty of "groking" the algorithmisation and problem modelling to the students. Not the best idea, IMO, but people do this, especially as a way to get kids interested into "coding" - building robots is more fun than just writing abstract code outputting some text.

author: Vtile
author_rank: Super Contributor
timestamp: February 01, 2020, 03:55:53 pm
content: This pointless argument is fun to watch.Quote from: janoc on February 01, 2020, 02:48:11 pmI'm not familiar any CPU/MCU that is capable of running any programming language directly.Ie. In Siemens older (now many times dupped as S7-classic) S7-300/400 series of PLCs all of these ladder/structured text/Graph/FBD etc. higher abstraction languages were first compiled to this assembly like stack based STL/(IEC Instuction list), which then were interpret in somehow to in PLC itself. The new system s7-1200/1500 seems to have dropped out the middle language and these high abstracted languages are directly compiled (without guarantee of similarity) to something that PLC is capable of run.I'm not entirely sure the PLC (..and PLC language standards) are developing in a good direction, by adapting more and more from the general purpose philosophies.

author: janoc
author_rank: Super Contributor
timestamp: February 01, 2020, 04:16:48 pm
content: Quote from: Vtile on February 01, 2020, 03:55:53 pmThere were ARM CPUs capable of running Java bytecode directly (Jazelle), for ex. But yes, strictly speaking it all gets compiled into some kind of machine code.

author: Vtile
author_rank: Super Contributor
timestamp: February 01, 2020, 04:39:38 pm
content: Quote from: janoc on February 01, 2020, 04:16:48 pmExactly.

author: Nerull
author_rank: Frequent Contributor
timestamp: February 01, 2020, 06:08:40 pm
content: Quote from: unitedatoms on February 01, 2020, 12:41:37 amAre you familiar with Stuxnet, the virus designed to attack PLCs, subtly modifying their behavior to destroy equipment connected to them?PLCs are far from unhackable.

author: janoc
author_rank: Super Contributor
timestamp: February 01, 2020, 06:21:07 pm
content: Quote from: Nerull on February 01, 2020, 06:08:40 pmI would even go as far as saying that they arenotoriousfor being insecure. Get on the plant's network and it is game over. Even the PLC security holes notwithstanding, the PLCs have rarely any meaningful access control or authentication. If there is a password and it isn't the vendor default one, it is likely a trivial one and identical for the entire plant to simplify maintenance. Oh and having the plant LAN directly connected to the administrative networks (which are connected to the Internet) is also very commonplace - the management wants to see pretty dashboards and blinking lights. And then a stupid virus strikes and there is suddenly a blackout or production stoppage ...And the bugs are pretty much never fixed because it would mean taking the plant offline and updating firmware in every single affected one. All the while risking that who knows what stops working afterwards. Not going to happen.

author: Berni
author_rank: Super Contributor
timestamp: February 01, 2020, 06:29:23 pm
content: Quote from: Nerull on February 01, 2020, 06:08:40 pmWell technically the PLC was working as intended since being able to load in new programs or to read/write variables is what that network interface is supposed to do. The idea being that networks that PLCs sit on are dedicated isolated networks. Much like telephone line is dedicated for that one task and is not supposed to have any security features. Just that some PLCs happen to be able to use normal consumer Ethernet as its transport medium. Much like in the old days there was individual wires carrying analog and digital signals to individual meters and dials in the control room, this wiring is now replaced by digital data running trough twisted pair.The actual vulnerability was that people plugged random USB drives into PCs on this isolated network so by peppering the Stuxnet virus all over the facility eventually someone would infect a USB drive by plugging it into a infected machine and then at some point plug the same USB drive into the isolated control room PC.Security is hard tho, especially when a nation pours mountains of money into the effort of breaking your security.

author: RoGeorge
author_rank: Super Contributor
timestamp: February 01, 2020, 06:45:28 pm
content: Quote from: unitedatoms on January 31, 2020, 12:36:37 amOverall, my advice is to let it sink for a while before jumping to conclusions. Do a few real world implementations (recommended at least 3-5 of them) before commenting about it.Pretty much every conclusion is not OK. Nothing about blaming you here, just that a 4 days training classes is obviously not enough to get a taste of the subject. Again, not your fault, but you are looking at it from a very wrong angle. First of al you need to drop the "programming/algorithms" priority, and think about it in terms of "real world process control" priorityies, which are very different, each with their own set of problems.By the way, overall you are obviously on a good path already, and the way you treated so far this dialogue is highly appreciated!

author: Nerull
author_rank: Frequent Contributor
timestamp: February 01, 2020, 07:16:19 pm
content: Quote from: Berni on February 01, 2020, 06:29:23 pmThere's more to it than that. Stuxnet installed a rootkit on the PLC allowing it to hide itself from monitoring systems. It was an incredibly sophisticated attack that relied on simultaneously attacking multiple systems at multiple network layers.

author: rstofer
author_rank: Super Contributor
timestamp: February 01, 2020, 08:03:41 pm
content: I have always asked myself: Why was the control system exposed to the Internet? Who would be that stupid? Sure, it allows consultants, thousands of miles away, to update the program but that's a bug, not a feature.

author: rstofer
author_rank: Super Contributor
timestamp: February 01, 2020, 08:12:35 pm
content: No stack, you say? I was looking at a PLC yesterday and it was clearly stack oriented and, in fact, had just 8 levels for expression evaluation. The programming language was specifically designed for stack operations.https://www.automationdirect.com/adc/shopping/catalog/programmable_controllers/directlogic_series_plcs_(micro_to_small,_brick_-a-_modular)/directlogic_06_(expandable_micro_brick_plc)/plc_units/d0-06dd1Chapter 5 has the instruction set:https://cdn.automationdirect.com/static/manuals/d006userm/dl06userm.pdf

author: Workalot
author_rank: Newbie
timestamp: August 19, 2020, 11:16:36 am
content: To the OP...Ladder logic starts with a document. It is the graphical representation of the control algorithms. This is important as there is then a document that others can consult to fix issues or advance performance.Further, ladder is familiar to field technicians.How the ladder logic diagram is translated for execution is PLC specific. Some may have an interpretive regime (Java like) but the best result is to have the ladder diagram rendered to machine code.The mechanism to update is preferably done independently of the PLC's operating system. As with mobile phone system updates it is done while the system remains active.C/C++ based solutions require a system recompile and system stoppage when downloading the replacement runtime. Beyond field technicians pay grade I'll bet.And yes, no pointers, no threads, no heap etc - just a look, think, act in a repeating sequence.

author: wizard69
author_rank: Super Contributor
timestamp: August 21, 2020, 05:12:29 am
content: I really hope this training course wasn't from one of the major PLC vendors because it looks like they have made the wrong impression on you.Quote from: unitedatoms on January 31, 2020, 12:36:37 am4 days is basically an introduction.QuoteThere is actually a language standard for PLC's. In some cases though you can make use of C type languages or at least you could, there is little demand for that. Also it isn't uncommon for a plug in module to run a different language. At one time BASIC co-processors where a thing.Quote

author: mfro
author_rank: Regular Contributor
timestamp: August 21, 2020, 05:42:10 am
content: PLCs do have everything you mentioned missing (including fatal bugs, sometimes).It's just they don't let you access it.

author: Berni
author_rank: Super Contributor
timestamp: August 21, 2020, 07:33:58 am
content: Yeah deep down the PLCs still do a lot of programmery stuff, but its hidden away as much as possible from the user.Its the PLCs OS that is doing all the magic while running on just a regular MCU in there. The user software that is loaded on there is almost always ran as an interpreter. It is the PC software job to turn whatever you created into the PLCs proprietary byte code that then gets loaded in. But yes this intermediate language that the PLC is executing is typically designed to work with a stack made to easily represent ladder diagrams.And yes while you don't have directly debugger access to the CPU, but any decent PLC has high level debug functionality (Provided by its OS and the PC software). Its possible to see ladder diagrams light up like a christmas tree with signals flowing trough them live. Its possible to stop it at any point. Its possible to see memory fields changing in real time. You can force signals to high or low, write into variables...etc. This is incredibly useful in tracking down problems, be it in the software logic, or just looking at the PLCs inputs to troubleshoot a wonky sensor.If you ever try to run any more advanced modules on a PLC such as fancy analog cards or VFDs you will see that it looks a lot like programing a peripheral on a MCU where you configure and give it commands by writing to memory registers.But yes in general the way PLCs are programed is to make it more difficult to mess things up accidentally while at the same time the jobs that PLCs do are generally very simple. They typically just repetitively run a machine trough a work cycle or regulate some process values. Things too complex for just a few relays, but not complex enough to require a full on computer. You don't use a PLC to run a CNC machine or 3D printer or heck a chess playing robot.

author: rstofer
author_rank: Super Contributor
timestamp: August 21, 2020, 10:22:33 pm
content: In the beginning...Machines were run with relay based control systems and it is darn difficult to create a Finite State Machine with relays. In some cases we used stepper switches. This worked well if the sequence was relatively linear, step by step. I was working on relay control systems in the aerospace industry back in '69, fully 10 years before C was invented. At the time we would probably have used an IBM 1800 minicomputer and a rack full of addons if we wanted to use computer control. Too expensive and too hard for electricians to deal with FORTRAN. In those days, the alternatives were COBOL or assembly language and assembly might have been the easiest. But for ordinary electricians? No chance!The IBM System 7 was just being introduced.Take a simple machine, a riveter, for example. There is a sequence start signal that tells the positioner to move the fuselage panel to the next rivet position. This was set up with a template and photo sensors running on rails attached to the floor. The template had multiple lines of holes, one for each stringer on the panel. Remember, these panels are probably 20 feet long and 10 feet wide, more or less. Once the horizontal position is achieved, the panel is leveled using pneumatic gauging devices. The panel is a 3D shape, not a simple flat sheet of aluminum.Eventually the panel is in position and level. Raise the bottom ram and lower the clamp then drill the hole and dwell to clean it out. Retract the drill and, in some cases, position a squirt tube over the new hole and apply some paint. Retract the squirt tube. Now move the rivet inserter mechanism into place and place the rivet. Hold the rivet head down tight with the upper ram and upset the rivet with the lower punch. Retract the rivet tooling and unclamp the part. Move to the next hole.Rinse and repeat for weeks on end times 4 machines. BTW, everything was hydraulic except the sensors.I never counted the number of relays but there were probably 50 DPDT ice cube relays in the main machine and another 20 or so industrial relays in the positioner. On a good day they all worked. Oh, let's not forget manual step-by-step operation from a control panel along with some switches and lights. Lots and lots of IO points but we didn't call them that. Obviously, there was some interlocking to consider. We couldn't unclamp if the upper ram was down, things would break - violently!The ladder diagram was about 36" wide and over 30 feet long. We rolled it out on the shop floor when we had to troubleshoot something.I was on that program for nearly a year!All of this could be done with a relatively small PLC and a bunch of IO modules. There would probably have to be intermediate relays to handle the current of the various valves and actuators but they wouldn't be involved with the logic. PLCs were brand new and Allen Bradley probably had the best. We were an AB shop anyway - all of our controls, including the GE Mark Century NC controls, were required to use AB relays! I'll bet GE loved that...Some time around '71, another engineer decided to use Dow Corning Fluidics modules to create a machine control. I give him points for originality but an 'F' for maintainability. Electricians don't work with air controls and plumbers are, well, plumbers. Still, it was interesting. Corning had logic gates and flip-flops so, in theory, you could build an entire pneumatic computer. There were operating environments where this would be handy. The machine shop floor probably wasn't the place. Diagnostics of air flow is another issue - it's sort of hidden. You can't stick your Simpson 260 probes in there and tell what is happening.https://en.wikipedia.org/wiki/FluidicsElectricians (and most electrical engineers) prefer ladder diagrams and the ability to program PLCs in ladder logic. I have come across some PLCs that actually force the programmer to write the expression for each output in terms of RPN logic. That's great if you know how to do it (and I do) but it's a lot like programming an HP calculator. The logic printout doesn't look at all like the ladder diagram!Diagnostics and debugging favor the PLC over relays, no doubt about it. Adding another relay is usually as easy as adding another IO module (if needed) and writing the ladder rung. If you run out of IO space, add another chassis!I'm really fond of GE Fanuc controls and have used them in a number of non-machine applications including power monitoring over 26 unit substations all tied to the GEnius bus. Very cool stuff!My last project, about 20 years ago, used one of the Fanuc man-machine interface panels with a touch screen. That was a very nice control system! At the time, I thought this was the future of control systems.I expect PLCs in one form or another to be around forever. They are simply the best way to build machine controls.

author: tszaboo
author_rank: Super Contributor
timestamp: August 21, 2020, 11:03:10 pm
content: They are meant to do tasks, that a trained monkey can do." Tank almost empty, must fill tank"" Tank almost full, must stop filling tank"So yeah, thats not the point. The point is this:And if you need to read a ethernet connected profibus level sensor, and control a valve with a mirocontroller, good luck.