banner



How To Read And Write Data From Serial Port In Java

cross platform java serial port communication programming with PC and Arduino,ATmega328P,Microchip PIC,STM32 microcontroller tutorial

In this tutorial we will learn how to program serial port of a PC using Java programming linguistic communication. The PC will communicate with an Arduino continued to the USB virtual Serial port of the PC and substitution text data using a Coffee plan.

Java Standard library no longer carries classes to communicate with the PC serial port. Some of the user developed java serial port programming API's like RxTx are no longer maintained.

In our Java Series port programming tutorial nosotros volition exist using a third party library chosen jSerialComm library from Fazecast, Inc to open and control the series ports.

According to its website,

" jSerialComm is a Java library designed to provide a platform-independent way to admission standard series ports without requiring external libraries, native code, or whatever other tools. Information technology is meant as an alternative to RxTx and the (deprecated) Coffee Communications API ".

This tutorial will teach you lot how to plan your serial port using java to communicate with a USB Virtual series Port based device like Arduino, USB Multifunction DAQ,GPS devices etc

Contents

  • Sourcecodes
  • How to use jSerialComm JAR with your Serial Port lawmaking
  • Checking for available serial ports in Java
  • Opening a Series Port connection using Coffee
  • Java Serial Port data Reception from Arduino
  • RTS / DTR SerialPort pivot Control using Java

Source Codes

  • Browse our online Github Repo
  • Download the Serial Comm Repo as Goose egg File

Compiling jSerialComm JAR on Windows Control line

First pace in learning Coffee serial port programming is to correctly compile jserialcomm jar file forth with your Coffee source code.

Make sure that the version number of the jSerialComm JAR file is correct, It may alter with time .

In one case you have downloaded the jSerialComm JAR file in a directory of choosing, you lot can compile the source code as shown beneath.

                                    javac                              -cp                                            .;                jSerialComm-two.nine.0.jar                            YourSerialSourceCode.coffee                  

One time the lawmaking has compiled without any errors you can run the resulting class file as shown below.

The above lawmaking was compiled on a Windows System.

                      java                              -cp                                            .;                            jSerialComm-ii.9.0.jar              YourSerialSourceCode                  

Practise not forget to add . ; earlier the JAR file while compiling and running

Checking for available serial ports using Java

Once yous have managed to compile your code without whatsoever result, for Eg jSerialComm JAR file not found error,j SerialComm JAR file missing error.

You tin  build a simple serial port program in Java that volition check for the bachelor serial ports (COM ports ) on a Windows Organization.

You tin notice the list of  Source lawmaking SerialPortsAvail.java beneath.

                                    import              com.fazecast.jSerialComm.*;                                            public class                              SerialPortsAvail                                                          {                    public static void main (Cord[] Args)                                {                                                              SerialPort []              AvailablePorts                =                                            SerialPort.getCommPorts()                            ;                                                          // utilise the for loop to print the available serial ports                                for(SerialPort S : AvailablePorts)          System.out.println("\n  " +            Southward.toString());                                }                                }                  

Copy and save the file into a java source file ( SerialPortsAvail.java ).

Here we import the all the classes required for series port access from the JAR file using

import com.fazecast.jSerialComm.*;

SerialPort.getCommPorts() ; is a static form method that render an array of serialport objects which is stored in the AvailablePorts array.

We and then use a for loop to iterate over the available ports.

You can then compile and run the code.

                                    javac              -cp              .;jSerialComm-2.9.0.jar                              SerialPortsAvail.java                            java              -cp              .;jSerialComm-ii.9.0.jar                              SerialPortsAvail                                            

In my system, I have ii connected devices that identify as USB Virtual COM port

  1. An Arduino UNO
  2. FT232RL based USB Device

On Running the lawmaking, we get the following output

java serial port communication program showing available serial ports on a Windows machine

In most applications we simply wants to render the COM port number. For that you can use  Southward.getSystemPortName(); Method which but returns the COM port number.

The below tabular array shows some of the Methods you can use to get more information about the port you take to access

  1. Returns port number in COMxx format  S.getSystemPortName();
  2. Port Clarification as reported by the device S.getDescriptivePortName();
  3. Port Os path                            S.getSystemPortPath()
  4. Location of the Virtual COM port on the USB HubSouth.getSystemPortLocation()

java serial communication how to find available port number,port description api tutorial

Click Image to Enlarge

Opening a Series Port connection using Java

Now nosotros will open a connection to the serial port using the below Java program.

Please use the full program from the Github repo instead of the snippet below.

SerialPortOpen.java

                                    import              com.fazecast.jSerialComm.*;              // Series Port classes                                            public class                SerialPortOpen              {    public static void main (String[] Args)    {      SerialPort [] AvailablePorts = SerialPort.getCommPorts();              //Open up the first Available port                                                SerialPort MySerialPort = AvailablePorts[0];                                            MySerialPort.openPort();                            //open the port                                  //Arduino May get reset                                                                        if (MySerialPort.isOpen())//Check whether port open/not              System.out.println("is Open ");         else            Arrangement.out.println(" Port not open up ");                                                                                MySerialPort.closePort();                            //Shut the port                                                          if (MySerialPort.isOpen())             System.out.println(" is Open ");         else             Arrangement.out.println("\northward Port not open up ");        }//end of main()              }                  

SerialPort [] AvailablePorts = SerialPort.getCommPorts(); At beginning we get all the bachelor serial ports using

At present AvailablePorts array contains all the serial ports bachelor in the arrangement provided you have multiple USB virtual COM ports continued to your System.

You tin can access the bachelor ports using array alphabetize notation.

  • AvailablePorts[0]
  • AvailablePorts[1]
  • AvailablePorts[due north times]

In our example we volition exist using the first i or index 0 as i have a single Arduino UNO connected to my Laptop.

Now create a SerialPort object  ( MySerialPort ) and assign the first Port on the organisation to it equally shown below.

SerialPort MySerialPort = AvailablePorts[0];

At present you can open the port using .openPort() method

then check whether the port is open up or not using the .isOpen() Method .The Method return TRUE if port is open, FALSE if not .

                                                    MySerialPort.openPort()              ;              //open the port                                                                        if (                MySerialPort.isOpen()              )              //Check whether port is open or not                                System.out.println("is Open up ");                                else                                              Organisation.out.println(" Port not open up ");                  

and finally y'all can close the port using .closePort();

MySerialPort.closePort() ; //Close the port

java serial port programming using jserialcommopening and closing ports

Arduino Reset Event

  • Please note that your Arduino UNO may get RESETed when you open the Serial Port .This may cause problem when Arduino is trying to receive info from PC

Receiving data from Arduino using Java Serial Port Program

arduino java serial communication circuit diagram

In this section,

we will learn how to receive a string of text send by an Arduino UNO using Coffee Serial Port program running on command line.

The Arduino will be sending the data using standard baud rate of 9600bps and 8N1 format (8-data bits, No Parity, Single End chip).

  • All  the code can be downloaded from our Github Repo.
  • Please note that I volition just be showing relevant parts of the code hither, Please download the total lawmaking from our github repo.

The Arduino code is a basic serial transmission program which uses Serial.println() to send a text message Hello to Java from Arduino UNO to PC  via COM port.

Arduino Manual Lawmaking

                      void setup() {              Series.begin(9600);              // opens serial port, sets data rate to 9600 bps 8N1                                            }                                void loop() {              char              TextToSend[]              = "Hullo to Java from Arduino UNO";              Serial.println(TextToSend);              // sends a \n with text              filibuster(thousand); }                  

So if you effort to update your Arduino (on COM4) lawmaking while the Serial Port Program (on COM4)  is running ,you will become a port in use mistake.

Our Java Series Programme volition be running in the Blocking Mode where the Series Port will be locked by the program when in utilise. This means that simply 1 programme can admission the port at a fourth dimension.

jSerialComm library supports all the standard baudrates 1200,9600,19200 etc.

                      int              BaudRate              =              9600;                                int              DataBits              =              8;                                int              StopBits              =              SerialPort.ONE_STOP_BIT;                                            int              Parity              =              SerialPort.NO_PARITY;                                            //Sets all serial port parameters at one time                                MySerialPort                .setComPortParameters              (BaudRate,              DataBits,              StopBits,              Parity);                                //Gear up Read Time outs                                MySerialPort                .setComPortTimeouts              (SerialPort.TIMEOUT_READ_BLOCKING,              1000,                                      0);                                            MySerialPort.                openPort()              ;              //open the port                              

int StopBits  = SerialPort.ONE_STOP_BIT; Here we are using but one stop flake,

int Parity    = SerialPort.NO_PARITY; Parity is none here ,

Jserialcomm also allow y'all to take odd and fifty-fifty parity like

int Parity = SerialPort.ODD_PARITY;

int Parity = SerialPort.EVEN_PARITY;

After which we configure the port to employ the above settings using

          MySerialPort                                                    .setComPortParameters                                              (          BaudRate          ,          DataBits          ,          StopBits          ,          Parity          );        

Later which we fix out the Time outs

                      .                setComPortTimeouts                                              (                      TIMEOUT_Mode                    ,                                READ_TIMEOUT_milliSec                    ,                                WRITE_TIMEOUT_milliSec                    );        

Here Read Timeout is set for 1000 milliseconds while Write Time out is set for 0.

          MySerialPort                      .                setComPortTimeouts                                              (          SerialPort.TIMEOUT_READ_BLOCKING          ,                    one thousand          ,                                 0);                  

We so read the bytes arriving at the port using

MySerialPort.readBytes ( readBuffer , readBuffer.length );

here readBuffer is the buffer into which data will exist read and readBuffer.length is the number of bytes to read from serial port.

once the bytes are read, they are converted to String and displayed on the command line

                                    //Reading from COM port using Java                                                          try                                                                        {                                                                        while (truthful)                                              {                                              byte[]              readBuffer              = new byte[100];                                              int              numRead              =                              MySerialPort.readBytes              (readBuffer,              readBuffer.length);                                              System.out.impress("Read " + numRead + " bytes -");                                                                                          
                                                    //Convert bytes to String                                                                String S = new String(readBuffer, "UTF-eight");                                                          System.out.println("Received -> "+ South);                                              }                                              }                                                                        catch (Exception e)                                                                        {                                                          eastward.printStackTrace();                                                          }                                            MySerialPort                .closePort()              ;              //Shut the port                              

Here is the output of the program on a Windows Command line

java serial port programming tutorial with Arduino,Raspberry Pi

Transmitting data from PC to Arduino using Java Serial Port API

Here we will transmit a byte from PC to Arduino using Coffee and Arduino will light up a LED connected to its Port 7 .

Arduino Reset Effect

Please note that when you lot Open the SerialPort using MySerialPort.openPort() ; //open the port method ,

the Arduino UNO board may get RESET. Then you need to insert a pocket-sized delay afterwards opening the Serial Port, otherwise the Arduino will  not receive any data

                      MySerialPort.openPort();              //open up the port                                                                          //Arduino Volition Reset                            Thread.sleep(2000);              //Delay added to so Arduino-                     //-can recover subsequently RESET                              

.

Once you have configured all the settings as nosotros had done in the earlier case. We can now write data as shown below.

You lot can go the Total code from our github repo.

This will ship 65 decimal to the Arduino and Arduino volition calorie-free up the LED connected to Pin7.

SerialPortTransmit.java

try

{

byte[]WriteByte = new byte[one];

WriteByte[0] = 65;//send A

      int bytesTxed  = 0;

      bytesTxed  = MySerialPort.writeBytes(WriteByte,ane) ;

      System.out.print(" Bytes Transmitted -> " + bytesTxed );

}

java serial port transmission reception  to Arduino using jserialcomm library tutorial

RTS and DTR pin control of Serial Port using Java

In this department of our Coffee serial port programming tutorial nosotros volition learn how to control the RTS and DTR pins.

Serial port have two pins RTS and DTR which tin be turned ON/OFF by your Series port program for signaling purposes.

In some Arduino variants DTR pin is used to reset the microcontroller for uploading the code. This method is also used by other serial port based programmers.

jserialcomm provides two example methods which nosotros tin employ to command the land of RTS and DTR pins.

  • .setRTS(); Make RTS pin Loftier
  • .clearRTS(); Make RTS pin Depression

DTR

  • .setDTR(); Make DTR pin Loftier
  • .clearDTR();   Make DTR pin Depression

When you lot are using USB to Serial Converter (USB2SERIAL) like FT232,you should check the agile logic levels of their RTS and DTR pins.

In FT232, RTS and DTR pins are active LOW ,so setRTS() will make the pivot Depression and clearRTS volition make the pin High.

USB to serial/RS232/Rs485 converter

Now programming the RTS /DTR pins in Java is quite simple. You open the serial port and use the series port object to telephone call the necessary methods.

You tin can find the partial code beneath. Total code available in Github Repo.

                                                    MySerialPort.openPort();                            //open the port                                            MySerialPort.setRTS();              // Make RTS pivot High              Thread.sleep(2000);              // Filibuster added to so you tin see                            MySerialPort.clearRTS();              // Make RTS pin Low                                                          MySerialPort.setDTR();              // Make DTR pin High              Thread.sleep(2000);              // Delay added to so you tin meet                            MySerialPort.clearDTR();              // Make DTR pin Depression                                                                                        MySerialPort.closePort();              //Close the port                              

Here is the full program running on a Windows 10 PC ,

USB to serial/RS232/Rs485 converter

We are using USB2SERIAL USB to Series/RS232/RS485 converter (higher up image)with built in LED's connected to DTR and RTS pins  here.

java serial port program using jserialcomm controlling rts dtr pins of usb to serial converter

How To Read And Write Data From Serial Port In Java,

Source: https://www.xanthium.in/cross-platform-serial-port-programming-tutorial-java-jdk-arduino-embedded-system-tutorial

Posted by: westwelition.blogspot.com

0 Response to "How To Read And Write Data From Serial Port In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel