Programmable Logic Controllers: Switching Coils With Java

Or, How To Connect To Real Physical Stuff Using Java



First, a disclaimer. I know next to nothing about programming programmable logic controllers. I don't even own one.

However, a client of mine is interested in making stuff happen in the real world using his computer. He has a programmable logic controller, which is basically a relay (i.e. an electrical switch that can be switched on and off electronically) that connects to his computer via a serial port.

According to my understanding, once you've bought one of these devices and connected it to your computer somehow, you can read and write the controller's "coils" to switch the relays on and off, hence switching devices on and off in the real world.

Since I don't have such a device, I've been using the free Modbus PLC simulator here (Modbus is a protocol for communicating with these devices).

I've been using the Jamod API to send commands to the simulator. All you have to do is download the .jar file and link to it in your Java project.

Since I couldn't find any example code for setting coils, I had to figure it out myself. I'm pasting it here, just in case it's useful to someone other than my client.

Do let me know if you find it useful.

Note: the code below is a TCP Master. If you want to use your serial port with Jamod, you'll need to download and install the quasi-obsolete Java Communications API (see this excellent link, or this one). Also be aware that the tutorial Master example on the Jamod site has a typo in it at the time of writing; they've missed an 's' out of ModbusSerialTransaction.

Setting PLC Coils Using Jamod



Note: it will help a lot if you look at example on the Jamod site for setting up a Jamod TCP master before you attempt this!

 
// Open the connection
// You'll need to change the IP address and port.
con = new TCPMasterConnection(InetAddress.getByName("192.168.50.100"));
con.setPort(502);
con.connect();

// Prepare the transaction
trans = new ModbusTCPTransaction(con);

// Prepare the request
WriteCoilRequest wcr = new WriteCoilRequest();

// Don't know what unit ID is; 1 seems to work
wcr.setUnitID(1);

// This is the number of the coil to set.
wcr.setReference(2);

// Turn coil on or off?
// This doesn't physically do anything; it just specifies
// what state should be set later on.
wcr.setCoil(true);

// Must execute a transaction now to actually do stuff.
trans.setRequest(wcr);
trans.execute();

WriteCoilResponse res = (WriteCoilResponse) trans.getResponse();

if (res != null) {
    System.out.println("Set coil " + res.getReference() + " to "
            + res.getCoil());
}

// Close the connection
con.close();