A Cheap DIY PLC Based On The Atmega328P

If you’re running a big factory, you’ve probably got a massively expensive contract with a major programmable logic controller (PLC) manufacturer. One shudders to think about the cost of the service subscription on that one. If you’re working on a smaller scale, though, you might consider a DIY PLC like this one from [Mr Innovative.]

PLCs are rarely cutting-edge; instead, they’re about reliability and compliance with common industry standards. To that end, this design features the ATmega328P. Few other microcontrollers are as well understood or trusted as that one. The device is compatible with RS232 and RS485 and will run off 24 VDC, both of which you would find in a typical industrial environment. It offers 24 V digital inputs and outputs, as well as analog inputs and outputs from 0 to 10 V. [Mr Innovative] demonstrates it by hooking up a DWIN human-machine interface (HMI) for, well… human interaction, and a variable frequency drive to run a motor.

If you want to run a basic industrial-lite system but can’t afford the real industrial price tag, you might enjoy tinkering around at this level first. It could be a great way to get a simple project up and running without breaking the bank. Video after the break.

 

41 thoughts on “A Cheap DIY PLC Based On The Atmega328P

  1. Cheap industrial PLC can be had for 200 bucks already and, depending on vendor, the software for them can be free (e.g. ABB PLCs). There are even Arduino-based PLCs.

    No expensive subscription necessary.

    PLCs make sense if you are automating some (relatively simple) process but you need the robustness of the device. E.g. they are designed to survive the electrician shorting mains voltage into the I/O terminals. Signalling is usually done at 24V or 48V, for noise immunity and reliability (24V breaks oxidation on switch or relay contacts easily).

    1. I think we need something in between a PLC and just an Arduino. I’m in fact working on a design for that right now.

      Not everything needs to survive a short to mains, but 15-30KV ESD and shorts to 12v are pretty likely, as is wanting to drive something with an Arduino without having to making a bulky mess with modules and wires.

      1. Speaking of Automation Direct, I have their Arduino programmed PLC, which uses a SAMD M0 chip. It works well with their various I/O cards.
        And if you want more powerful, they have a SAMD M4 PLC, programmed with CircuitPython. I think that’s fun, PLC circuits programmed with CircuitPython.

  2. One shudders to think about the cost of the service subscription on that one.

    10k a year for one of the big names.

    Also Rockwell dings you a bit harder for the PLC itself than some other vendors but… yeah A NEW CAR!!!!

    Also I’ve never heard of a PLC suriving mains short to IO…. they can survive ESD but probably not a mains short. In any case “Mains” in most PLC cabinets is 480V… if you are UL listed or certified by some other group, you are never going to short 480V to PLC IO BY DESIGN…

    1. IO should be able to handle quite a bit without killing the PLC. I’ve seen someone swap a 110v input card with a 24v card that lit up quite spectacularly. After swapping the right card back it, everything ran as normal.

      1. TwinCAT is actually really fun to develop in, forced me to start learning structured text IEC style coding. Wish their servo/amplifier hardware wasn’t so freaking expensive. Also it sucks that etherCAT hardware isn’t visible downstream of the processor, so I can’t check any of my IO-link stuff without talking to the controller first. Don’t know if that’s by design or not.

        1. “TwinCAT Runtime for Linux® is based on Beckhoff’s own Linux® distribution, which expands the choice of operating systems in addition to Windows and TwinCAT/BSD.”

          Ha! TIL!

      2. Beckhoff imo is the best way to get into the industrial control world. TwinCAT 3 is fully IEC61131-3 compliant, runs in Visual Studio, and you can use any of their libraries for free with an unlimited number of 7 day trials, you only need to pay for a full license once you commission your setup. Those libraries work with the actual modules too. And Ethercat is an insanely fast protocol that carries every other protocol within it to every other node you have in your system. I absolutely love it; I once described it as fancy arduino and shields lol

  3. If you search Aliexrpess for FX2N, you’ll find similar looking PLC’s in lots of variants, from small ones such as this (about 5 inputs & 5 outputs) and bigger ones (16 inputs / 16 outputs). There are also other options you can choose between:
    * Bare PCB.
    * DIN rail mount, open frame.
    * Complete Enclosure.
    * Relay or transistor output.
    * Screw connectors or pluggable screw connectors.

    And as far as I know all these have an STM32F103. Prices for these start around EUR25 for a completely built PCB.

    This Mr Innovative sells his (bare) PCB’s with schematic for USD 10, but judging from his youtube video, the power supply does not look very good. It looks like it there is just an MP1584 PCB piggy backing on this PLC. It’s adequate for DIY, but not really for a PLC, for which you expect more industrial robustness. The PLC from Aliexpress has the SMPS build o the main board, much more / bigger capacitors and a fairly big common mode filter before the SMPS circuit.

    For programming. A few days ago I saw that arduino has plc programming software on their website these days. (I normally don’t go to arduino website, I got lost). But it’s not open source. You have to buy some key to unlock the software, and you have to fiddle with that key to get it to work. Not my piece of cake.

    I once had a few PLC lessons at school. You had to draw weird ladder diagrams, and then fiddle with “coils” and switches to remember a bit. No thank you mam, just give me a decent programming language in which I can simply declare a variable and then use it’s bits, use it as a counter etc. I find it hard to comprehend that anyone who has learned a bit of programming in C / C++ or eve micropython, would want to go back to the archaic “PLC” stuf. But to each his own.
    Oh, Th FX2N PLC’s from Aliexpress tend to have pads to add a programming connector for the STM32 :) (But I can’t guarantee the would all have this).

    Prices

    1. ” I find it hard to comprehend that anyone who has learned a bit of programming in C / C++ or eve micropython, would want to go back to the archaic “PLC” stuf. But to each his own.”

      It does depend on the job market, getting laid off from one area gets one to consider “transferable skills”.

      1. Different applications. There are different languages used for high level PLC programming but good old ladder logic is kind of easier to decipher for industrial processes and a common language of industrial guys. PLCs are not very expensive considering the cost of the industrial systems they support. The programming environments are similar to the cost models of CAD software used commercially. The unique thing about PLCs that can make them costly is the various levels of fault tolerance and intrinsic safety of the devices. I have used some cheap ones as well as some really pricy stuff certified for explosive environments and the main difference is the testing regime they are put through and the liability the manufacturer takes on when they sell these.

        As far as the market, there are a zillion python developers and not so many PLC programmers and like anything else there is a difference between guys that have built systems consisting of ten PLCs and the guys automating major automotive plants and refineries. Most of the PLC programmers I have worked with have additional skills in mechanical and chemical processes being controlled, it helps a lot in developing industrial programs to have a deep understanding of the physical process so its kind of unique knowledge, it also happens to be a lot harder to go offshore with the programming. One thing about the industrial programmers is they usually have very good job security because they intimately know their company processes.

      2. The “transferable skills” with PLC programming being that ladder logic is, roughly, equivalent to ladder diagrams for electrical, so ANY electrician, with proper documentation of course, can decipher the ladder logic diagram. Programming languages are nice for it, and certainly useful in some applications (especially when hiring dedicated programmers), but when you have a lot of technicians who can wire by memory but have never touched a programming language, ladder diagrams are a Godsend.

    2. IEC61131-3 Languages for ICS aren’t for programmers or developers, they’re for the people maintaining the facilities they’re installed in. The vast majority of control systems are maintained by over worked instrument techs or electricians, not programmers.

      1. Kind of, it depends how mature the process is. Over time it shifts to a more electrical/network maintenance process. In the beginning there is a lot of debugging and reprogramming going on. The best PLC programmers are also pretty good at wiring and networking.
        The thing that the programming environments offer is canned monitoring and human machine interface widgets. They offer logging and monitoring tools, alarm notification widgets like SMS, email,syslog, SNMP integrations, etc. They also offer libraries of devices so you have a template of I/Os and often a grahpical view of the physical device so you can remotely see LEDs and displays as if you were standing at the rail. You could of course roll your own just like you don’t need an IDE to program, just a text editor but you would be re-investing the wheel. For example, the Rockwell software I have used allows you to simulate the hardware during programming and prevent bonehead moves like polling a device too often or writing code for states that cannot physically exist for a given environment. Another example, having a 10,000 C temperature limit on a device sensor that cannot read that high. One frustration is often that they are vendor specific so you kind of need to decide if you are a siemens shop, rockwell shop etc. Yeah they can work together but is gonna cost you and not be too easy.
        In terms of programming I feel like it is very much like the ADA mission of eliminating unhandled errors and illegal function calls at all costs. It is a very conservative risk adverse world and it needs to be because lots of these processes can be lethal if they so awry.

    3. PLCs were a replacement for logic made with a pile of relays and other dothats wired together and have looked like it since. I guess it had to look familiar and not be too easy to screw up for the electricians that had to use them

      1. Sort of but mainly its because PLCs interface with the physical world where thing are on and off, motors have speed and directions, sensors measure things with resistance and contacts. At the end of the day its a lot of switches and dials. The HMI interface are often click start and stop. PLCs replaced relay logic and have moved along into things like IP networks and wireless tramsports but primarily it is switch flipping by machine vs humans.

    4. No thank you mam, just give me a decent programming language

      It’s called “structured text” and while some people don’t like it (maybe because it’s based on pascal syntax?) it’s still decent enough.
      Never touched ladder diagrams or any of the other standardized methods.

      1. Well, really you could program your PLCs with any high level language you like but it all gets compiled into something like machine code. When documenting industrial processes and understanding them there has to be common language. Imagine being the only C+ guy writing modules in an all Python shop. Think of trying to sell you new wizbang PLC into a GM plant but you only speak Java. Not gonna happen.

    5. I’ve been working on a new way of programming PLC type problems, but using “Excel”-like expressions. The FX2/3/etc are my test-bed devices since they’re cheap and readily available for prototyping everything.

      So far, I’ve enjoyed them a lot. SOME of the boards I have, definitely do NOT have programming headers, you have to trace the paths to find good places to solder leads to :( POGO pins to the rescue!

    6. For you all responding here…
      If you’re working in the industry and you can earn your sandwitches and hamburges and get a roof above your head by writing ladder diagrams, sure go ahead.

      But if you are a hobbyist with a bit of tinkering with arduino behind you… Then you’d be mad to go back to the archaic stuff of ladder diagrams. I’ve heard of the “structured text” thing, but find it hard to imagine it would be a “better” language then C or C++, even when those have been mangled and deformed by the “arduino” muck.

      1. Like others have said, its a modernization and shrinkage from old Relay logic where the electrical prints/schematics were laid out in as a ladder. You started at the top with power source on the left and return power on the right. Is this relay contact closed? Yep, then this other relay should be on.

        In terms of PLC usage it is useful for visually seeing stuff turning on and off or what conditions are or are not met to energize an output. Especially since ladder logic is just a visual wrapper for structured text logic that is mostly If statements.

        For example, here’s the structured text from Allen Bradley plc to start a process:
        XIC(RobotPressLoad.O.Enb)XIC(Sta.Cycle.AutoCycle)[XIC(gDebug.BIT[0].8)XIC(gOP075_Robot.O.Posn.InAnyPounce)XIC(RobotPressLoadupper.O.Done)XIC(RobotPressLoadlower.O.Done)XIC(RobotUnloadpart1Pallet1.O.Done)XIC(RobotUnloadpart2Pallet1.O.Done)XIC(gRBT_Press.I.ClearForLoad)XIC(part1Gripper.Clamp.DN)XIO(part2Gripper.Clamp.DN)XIC(part3Gripper.UnClamp.DN)XIC(INP_Gripper_partPresent_I085104.DN),XIC(RobotPressLoad.O.Start)]XIO(RobotPressLoad.O.Done)[OTE(RobotPressLoadO.Start),OTE(gRobotPressLoadStart)];

        This translates into:
        If ((robotPressLoad.O.Enb) && (Sta.Cycle.AutoCycle) && ((gDebug.BIT[0].8 ) && (gOP075_Robot.O.Posn.InAnyPounce) && (RobotPressLoadupper.O.Done) && (RobotPressLoadlower.O.Done) && (RobotUnloadpart1Pallet1.O.Done) && (RobotUnloadpart2Pallet1.O.Done) && (gRBT_Press.I.ClearForLoad) && (part1Gripper.Clamp.DN) && (!part2Gripper.Clamp.DN) && (part3Gripper.UnClamp.DN) && (INP_Gripper_partPresent_I085104.DN)) || (RobotPressLoadO.Start)) && (!RobotPressLoad.O.Done)){
        RobotPressLoad.O.Start = True;
        gRobotPressLoadStart = True:
        }

        Now lets say that part present switch has a loose wire and therefore an intermittent signal that drops out in and out within 500ms, granted in the code above it wouldn’t matter since the process would have already started, but in other parts of the code the intermittent connection might cause part data to drop out. How would you or say a non-programmer detect that issue?

        With PLC ladder logic that part present bit is highlighted indicating that its condition is met allowing the proceeding logic to execute.

        Is the structured text language such as C/C++/C#/Java/Python/Basic/Kabal/whatever have you more flexible and easier to use, in a lot of cases YES! There are times where I want to implement a simple function in a PLC, that if I could program it in C or C++ would be quick, easy, and simple. But, I’m constrained to ladder logic where its structured text is ugly and doing it in ladder is ugly, huge, and complicated.

        1. I took out those two text blocks and reformatted them. I am not familiar with the XIC XIO thing, but the complexity / formatting is very much comparable to the C program.

          The biggest annoyance I had when I had some PLC lessons at school was that we had to make some PLC software for a sequential machine, the PLC thing very hard tried to do “everthing at once”, and then you had to figure out how to turn that into a sequential thing again.

          If I was to write C code for a “more than average” reliability standpoint, I would probably add in timers for switch activations, that catch it when there are intermittent contacts or when contacts switch at moments they are not supposed to switch.

          I once wrote C++ code for a microcontroller that controls some roller blinds with a simple brushed DC motor. It monitored the current, (including allowance for higher startup current for about 2seconds. ramping speed when the motor starts, maximum runtime of the motor, and maybe some more parameters. That software ran flawless for about 10 years, and then it just stopped. The commutator was completely worn. There was no more copper on it. So the software detected the motor did not ramp up and send an error message back over the network.

          1. I’ve had good success with writing state machines in ladder logic. You know the conditions to get into a state, when to move to the next etc. Which state you’re in can be a relay output, and thus block off entire parts of your program from running.
            This made controlling cycles such as compactors very simple, and very predictable.
            Ladder logic’s good points are easy documentation (you just print it out and file it with the wiring diagrams) and supportability (can be read and understood by techs, can be ported to another manufacture’s device, etc.)

      2. Sounds more like a “you”-problem. That’s your own personal hell, if you have a problem with PLC languages. They work very well for what they are made for.

        But if you are that fixated doing C(++), it sure is possible on a PLC also. Beckhoff supports it, Siemens supports it (only i think you need to buy their most or second most expenssive CPU, which is not cheap).

    1. Most industrial programming environments do not require you to write in ladder logic anymore. I know one popular package interacts with you in a visual basic sort of langauge and allows for functional blocks written in C. The same package also allows for a flow chart import from Visio. Doesn’t matter and it can document everything in ladder logic output. What the PLCs actually ingest is a low level machine language. Ladder logic is the industry current common documentation langauge but very few people actually write code in it for complex environments. Ladder logic while looking very ugly is great at showing states across many devices at any point like no ther language I am aware of.

  4. There is definitely the legacy drag in the PLC world but there kind of has to be. You can load a new OS and IDE into your new PC in a couple hours and your web server should work just fine. You cannot do this to an automotive plant or refinery. There is too much sunk investment there. Big upgrades in those industries happen in new plants or when they retool which is a years long multimillion (conservatively) dollar program. Just imagine the validation that has to happen if you change ANYTHING that affects the manufacture of explosive chemicals and pharmaceuticals (an industry I am familiar with). It takes forever and you are not producing while thats going on. You better have a great reason to replace the original process (it’s not cool or easy are not great reasons, saving time or money is a great reason) It like the old story of the ancient computers running space and nuclear systems, it works, its validated, its proven, and its reliable and its probably going to stay the life of the program like the space shuttle. Even your slick new CPU and Apple PC are built using age old PLC controlled processes that are well understood and do what they need to do.

    1. Same principles of complex and time consuming verification applies when when you are writing critical software. From payment terminals to voyager and mars rovers.

      And when that is skipped. Millions of people show up late for work because the timezone on their phone is set wrong, or that recent cloudflare thing which was apparently something with a regular expression, and it floored half a country for a day.

  5. The readers’ responses to this article highlight a basic confusion programmers have about PLCs.
    “Real” PLC applications don’t have 8 -16 I/O or are best programmed in a text language. The PLC systems I work with have multiple distributed PLCs, hundreds of motors/drives and thousands of sensors. They could never have been implemented with relays and contacts.
    These large systems are organic, undergoing modification and enhancement throughout the plant’s lifetime. Also, they are required to operate 24/7 and are maintained in operation by electricians/technicians, not the engineers who originally program them.
    At 2 AM in the morning diagnosing a section of a program, perhaps never seen before, that has caused the plant problem being experienced is where ladder logic shines. A problem will more often than not involve field hardware eg. a faulty limit switch, rather a program bug. The ability to visually identify the source of an interlock problem, coupled with the possibility of temporarily resolving the problem with a software force can save tens of thousands of dollars in lost production.
    IEC61131-3 describes multiple programming languages and the language used should be selected that is appropriate to the task being done eg. Functional Block Diagram is suited to high level logic and algorithms, Sequential Function Charts for sequencing, Ladder Diagram for low level logic. Structure text is rarely used. Anyway, if a task would be most appropriately implemented in a structured language, then if required modern PLCs can create functional blocks in C.

    1. Sure, big PLC’s exist too, but that does not mean that the small things are not PLC’s. But even so, the big names sometimes use their small PLC’s “programmable relays” even if they have 4 or so outputs.

      And for the more complex systems, industrial PC’s have also been quite common for 40 years or so.

      And for the Hobby / Hacker / DIY market, plenty of people have tinkered with for example modbus to create a distributed microcontroller network.

  6. Ladder logic is the worst but is can also be kind of the best. It can be well written and be easy to follow, or the opposite. Just like any other programming language.

    It all comes down to how well things are commented!

    Anyway, I had the opportunity to build up a control system for a fairly complex process entirely from scratch. No legacy code. No validated state. No nothing. I was feeling rebellious and and decided that there would be no ladder logic. Gotta love IEC61131-3!

    In the end, the only aspect of the controls that ended up in ladder logic was the section for forcing outputs. One simple rung per output was all it took. Couldn’t figure out anything simpler in any of the other four programming styles.

  7. I have been using outseal PLC since 2017, this software has quite a lot of features and is also easy to use with arduino nano.
    modbus communication uses serial ttl and can be transformed to rs232 / rs485 or modbus tcp.

  8. obviously i don’t know anything but running a factory but from a DIY perspective, isn’t “cheap PLC” synonymous with RAMPS (a relay / stepper controller hat for arduino) or smoothieboard (basically the same hat, but with an LPC ARM built in)?

Leave a Reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.