Tue. Dec 7th, 2021
Arduino ethernet modbus tcp

Arduino ethernet modbus tcp

The undertaking I wish to share with you right this moment is easy methods to talk between Arduino and Android through Modbus TCP.

This article belongs to a set of walkthrough articles which might be dependent on understanding:

  1. How Arduino communicates to Android units not solely by way of USB
  2. How simply is to make use of the light-weight modbus protocol in each Arduino and Android
  3. How the 2 barely totally different implementations of modbus TCP and RTU, can be utilized in industrial and residential functions

Take a take a look at easy methods to talk between Arduino and Android through RS485 and modbus RTU article if you’re focused on realizing the “serial” model of the present article.

So, again to the principle subject, the objects that I’ve used on this undertaking are the next:

each linked by a change and RJ45 cables. I supposed that the Arduino is the slave system and the Android panel is the grasp within the communication paradigm.

I begin first by presenting the Arduino sketch. It makes use of the SPI and Ethernet Arduino libraries (first two traces) and the Mudbus libraries (for the modbus TCP).
In the setup() perform, aside from setting Ethernet parameters like mac, ip, gateway and subnet masks, I set to zero the primary 4 registers of the modbus. Mb.R is an array that corresponds to the (signed) modbus TCP integer registers whereas Mb.C refers to boolean-based registers.

In the loop() perform, I learn the analog values of pins 0, 1, 2 and saved them into the primary three modbus registers. This allowed me to show within the Android panel three temperature values (as an illustration three temperature probes corresponding to TMP36 linked to the analog pins).

#embody "Mudbus.h"

//uncomment if you wish to see debug data
//#outline DEBUG

Mudbus Mb;
//Function codes 1(learn coils), 3(learn registers), 5(write coil), 6(write register)
//signed int Mb.R[0 to 125] and bool Mb.C[0 to 128] MB_N_R MB_N_C

void setup()
  uint8_t mac[]     = { 0x90, 0xA2, 0xDA, 0x00, 0x51, 0x06 };
  uint8_t ip[]      = { 192, 168, 1, 8 };
  uint8_t gateway[] = { 192, 168, 1, 1 };
  uint8_t subnet[]  = { 255, 255, 255, 0 };
  Ethernet.start(mac, ip, gateway, subnet);
  //Avoid pins 4,10,11,12,13 when utilizing ethernet defend

  delay(5000);  //Time to open the terminal

  Mb.R[0] = 0;
  Mb.R[1] = 0;
  Mb.R[2] = 0;
  Mb.R[3] = 0;

void loop()
  //modbus TCP replace

  //learn analog values and retailer the integer illustration within the first three modbus registers
  Mb.R[0] = analogRead(0);
  Mb.R[1] = analogRead(1);
  Mb.R[2] = analogRead(2);

  Do some work with the management register Mb.R[3]. For occasion:

  	if (Mb.R[3]>10)



The Ethernet port used for the modbus TCP requests is 502. To modifying the default port, simply change the MB_PORT variable outlined contained in the Mudbus.h header file.

We at the moment are prepared to research the Java code that’s essential to create an Android app that requests slave’s first three registers values and write (a management) integer worth to the fourth.

The following is the Android Activity for this demonstrative undertaking. The structure merely consists of two buttons that set off modbus TCP reads and writes. I skipped the code for the structure however you possibly can simply create a structure with two buttons named btnRead and btnWrite.

public class MainActivity extends Activity implements OnClickListener{

	// The vital situations of the lessons talked about earlier than
	TCPMasterConnection con = null; 	//the TCP connection
	ModbusTCPTransaction trans = null; 	//the Modbus transaction

	// Variables for storing the parameters
	InetAddress addr = null; 		//the slave's deal with
	int port = Modbus.DEFAULT_PORT;

	Button btnRead, btnWrite;

	protected void onCreate(Bundle savedInstanceState) {

		// affiliate the structure to the exercise

		// I suppose of getting a structure with two easy buttons
		btnRead = (Button) discoverViewById(R.id.btnRead);
		btnWrite = (Button) discoverViewById(R.id.btnWrite);

	protected void onStop() {
		//Close the TCP connection

	protected void onResume() {

		attempt {
			// specify the slave IP deal with
			addr = InetAddress.getByName("");

			// Open the connection
			con = new TCPMasterConnection(addr);

		} catch (Exception e) {
			Log.d("MODBUS","connection error");


	public boolean onCreateChoicesMenu(Menu menu) {
		// Inflate the menu; this provides objects to the motion bar whether it is current.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;

	public void onClick(View v) {

		int startReg = 0;

		attempt {
			if (v.getId()==R.id.btnRead){

				  // modbus reads

			}else if (v.getId()==R.id.btnWrite) {

				// modbus writes

		} catch (Exception e) {
			Log.d("MODBUS", "Error in reading/writing");


The code that I wish to spotlight is the one which opens and closes the TCP connection and is positioned inside onResume() and onStop() strategies.
Basically, onResume units the slave IP deal with, the port and creates the tcp connection to slave units whereas onStop() closes it.

The core a part of the undertaking is positioned contained in the onClick() methodology the place modbus reads/writes requests are created and executed. I used the Jamod library; references are on the backside of the article.
Creating a modbus learn(or write) request takes some easy steps:

  1. Declare acceptable request and response variables
  2. Create the learn/write request
  3. Create a modbus TCP transaction and affiliate a learn/write request to it
  4. Execute the transaction
  5. Get the transaction response

Point 1 wants to make use of variable sorts that refer particularly to the kind of learn/write you plan to make use of. For occasion, if you wish to use the modbus perform 3, use the categories:

  • ReadMultipleRegistersRequest
  • ReadMultipleRegistersResponse

Conversely, if you wish to write a number of registers (perform code 16), simply use the next sorts:

  • WriteMultipleRegistersRequest
  • WriteMultipleRegistersResponse
public void onClick(View v) {

	// begin register
	int startReg;

	attempt {
		if (v.getId()==R.id.btnRead){
			startReg = 0;

			ReadMultipleRegistersRequest req = null; //the request
			ReadMultipleRegistersResponse res = null; //the response

			// Prepare the request
			req = new ReadMultipleRegistersRequest(startReg, depend);

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

			// execute the transaction
			// get the response
			res = (ReadMultipleRegistersResponse) trans.getResponse();


			 do one thing with
			 the place okay is the index of the response array registers


		}else if (v.getId()==R.id.btnWrite) {
			startReg = 3;				//writes the fourth register

			WriteMultipleRegistersRequest req = null; //the request
			WriteMultipleRegistersResponse res = null; //the response

			// Prepare the request and create a easy integer register
			SimpleRegister[] hr = new SimpleRegister[1];
			hr[0]=new SimpleRegister(65);

			req = new WriteMultipleRegistersRequest(startReg, hr);

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

			//execute the transaction
			res = (WriteMultipleRegistersResponse) trans.getResponse();

	} catch (Exception e) {
		Log.d("MODBUS", "Error in reading/writing");

That’s it! What do you suppose? If you appreciated this text, please share it!


[1] Arduino Ethernet Board
[2] Ltouch Android multi contact panel

[3] Arduino Modbus TCP library (slave)
[4] Jamod Modbus for Java

By admin