factory automationIoTPLC programming

Modbus in a Nutshell (Plus a Short Introduction to IoT and PLC Programming)

Have you ever had the opportunity to work on a factory automation project? Currently, I’ve got the opportunity to program software controlling real hardware in an assembly line. My program influences real machines in the real world. Most of the software I’m writing remains in cyberspace, so I consider “getting real” pretty exciting.

One of the key requirements of our project is that we have to use the Modbus protocol. That’s an old protocol dating back to the 80s. Even so, I wasn’t happy with the documentation. One might expect such an old, battle-tested protocol to be thoroughly documented. Well, it is, in a sense. The only problem being that most of it has been written for experts. So I decided to write a cursory introduction for the hurried Java developer. After reading it, you should be able to understand the expert documentation. Along the way, you’ll learn something about the IoT world the media keep raving about. If you’re only interested in Modbus, just scroll to the PLC section.

Welcome to the IoT world

Come to think of it, I’ve already participated in four IoT projects. My first project took place long before the term “IoT” was coined. But even in 1992, machines doing chemical analyses already were run by software. In my case, it was an infrared spectroscope. That, in itself, is fascination enough. You can determine what a substance consists of by just pointing a beam of light on it and examining the wave spectrum of the reflected light (or – in my case – the light passing the fluid or gas).

Spektroscopy. Taken from an article of BeyondJava.net on Modbus and IoT. According to Wikimedia, As a work of the U.S. federal government, the image is in the public domain.
Image source: Wikimedia

Another project of mine controls a robot moving raw material to the assembly line and moving the finished parts to the next station of the assembly line. That’s not as trivial as it may sound. The holy grail of modern manufacturing is to reach “batch size 1”. In other words: the assembly line, which originally has been designed to enable the mass production of identical items, is becoming more and more flexible. As a customer, you can order very small quantities of products manufactured specifically for you. The ultimate goal is to be able to produce a single item and still earning money. The minimal economical size of a batch of items to be produced has been reduced to a single item.

Of course, producing on an assembly line doesn’t allow for infinite flexibility. It’s always about mass production. Even so, “lot size 1” is an exhilarating goal. In former times, we all bought cars that were identical to the neighbor’s car. Nowadays, even if both of us buy a popular car, there are zillions of options distinguishing it from your neighbor’s car.

Computers play an important role in this story.

Computers in the factory

This image give you an idea why computers play a crucial role in modern factories:
Explaining the role of PLCs and computers in general in a factory. BeyondJava.net. Image source: Wikimedia.org.Image source: Wikimedia

In this particular example, big and small bottles are sorted according to their size and quality. A computer reads the height of the bottle from a sensor and checks whether the bottle is broken. If the height is below a certain threshold, the bottle is moved to the left-hand side conveyor belt. Large bottles are moved to the right-hand side conveyor belt. The broken bottles just stay on the central conveyor belt.

The height can be detected using a simple photodiode. That’s not a big deal. It can be solved by simple analogous electronic. Engineers already did this in the 60s and 70s. Detecting whether it’s broken probably requires a camera and image processing (or something like that). In other words, if it’s not done by a human, we need a computer.

Programmable logic controllers (PLCs)

In a factory, those computers are usually called programmable logic controllers or PLCs. Sometimes they look very much like a desktop computer, with keyboard and screen, just a bit more ruggedized. Sometimes they are just a module in a rack. More important is that they usually have inputs and outputs, physical lines sending electric current to a machine or receiving data from a sensor.

Both the inputs and the outputs are mapped to memory cells. I’m not a PLC expert, but from my limited experience the memory typically consists of several different memory types:

  • Discrete output coils (or just coils for short) control single electrical lines. A coil is a single bit sent to a machine. For instance, you could use it to switch a light on or off. Coils can be both written and read, so I suppose you can also use them to read data.
  • Discrete input contacts are also bits, this time used as an input. For example, in the example above the photodiode could be connected to an input contact.
  • Analog input registers read a voltage and convert it into a 16-bit number.
  • Analog holding registers can both read and write a voltage.

These memory types are usually mapped to different address ranges.

In reality, I suppose there are many different variations of this idea. For instance, this document describes several other types of coils and contacts, such as timers, counters and relay coils.

BTW, the word “coils” refers to the construction of a switch. A relay is simply a wire wrapped around an iron core. If electrical current is flowing, the coils get magnetical, thus attracting an iron bar. This, in turn, closes a contact:

beyondjava.net on Modbus and PLC programming. Image source: Wikimedia, published under a creative commons license.
Image source: Wikimedia

The scan cycle

A PLC executes a “scan cycle” periodically. According to Wikipedia, this cycle consists of five steps:

  1. Reading inputs
  2. Executing the program
  3. Processing communication requests
  4. Executing CPU diagnostics
  5. Writing outputs

This simple programming model has a couple of consequences. When a sensor reading changes or an input contact fires, the PLC doesn’t notice automatically. There are no interrupts starting a function automatically when an input changes. The only way to detect such a change is to store the old data and compare the current input registers or coils with the old state.

If you’re interested in learning more about PLCs: there’s plenty of information in the internet, but this presentation may be a good starting point: Mahesh Vadhavaniya on PLCs.


The Modbus protocol is an application-level protocol working on the level of coils and registers. All you can do is read and write memory cells. Every Modbus command is a short telegram sent via TCP/IP (or simpler network protocols, like Modbus RTU) to the PLC. Usually, the PLC acts as a server. As a Java programmer, you open a client socket to the IP address of the PLC, using port 502 by default. After that, you can send commands to the PLC by simply writing a byte stream to the socket. The PLC will never send a telegram to the Java program. If you want to react to changes, you have to poll the PLC cyclically (also known as “busy waiting”).

BTW, I’m pretty sure there are also more advanced methods of communication between the PLC and a controlling program. I’m just describing the general idea of the Modbus protocol.

Modbus commands

Basically, the Modbus protocol is about reading and writing memory, so every Modbus command does just that:

01 read coils
02 read input contacts
03 read analog holding output registers
04 read analog input registers
05 write a single coil
16 write analog holding output registers

I’ve omitted a couple of commands, but you get the idea.

The rest of the story is quickly told. A read command sends two parameters: the starting address and the number of registers to be read. The PLC sends the response of the same sockets. Basically, it’s simply a byte stream.

Analogously, a write command takes three parameters: the starting address, the number of registers to be sent and the byte stream itself. The PLC sends back a simple acknowledgment.

Java libraries

There are several Java libraries simplifying sending Modbus commands. The library we finally used is Modjn. What we didn’t like about this library is that there is no license information, and the library seems to be abandoned since 2014. On the other hand, the Modbus protocol has been around for thirty years, so maybe there’s simply no need to change the library. It doesn’t support every Modbus command, but it does the trick for us.

DIGITALPETRY seems to be a bit more complex. It supports Java 8. It’s published under an Apache V2 license, and it’s still actively maintained.

Modbus simulator

We’ve found several generic Modbus simulators. The first simulator we found and tried worked good enough for us, so suffice it to point you to the simulator of IBH systems. Note that this isn’t exactly a recommendation: we simply didn’t look at the other simulators. The other simulators may or may not be better.

Wrapping it up

I’ve been working on several automation projects in the past. These projects used a high-level protocol, sending commands like “move the bottle to the left conveyor belt”. In this case, the PLC translates these commands to the level of memory cells.

Modbus is an older protocol, working directly on the level of registers with the PLC memory. Plus, it only allows for unidirectional communication. If you want to learn about changes in the sensor readings, you are not notified automatically. You have to poll the PLC memory cyclically.

Once you’ve wrapped your head around that, Modbus programming is fairly easy. It reminds me a lot of programming in assembly language.

By the way, I’ve omitted a lot of details for the sake of brevity. And I’m not an expert. If you spot any mistake in my description, please leave a comment so I can improve the article.

Dig deeper

Introduction to Modbus
Modbus specification