Using Java to realize serial port full duplex communication

Source: Internet
Author: User
Tags constructor functions interface connect query thread
An embedded system usually needs to carry out Full-duplex communication with its main control system, for example, a pipelined control system needs to continuously accept the query and control information sent from the master control system, and send the execution result or query result back to the master control system. This paper introduces a simple Java class library which realizes Full-duplex communication through serial port, which simplifies the operation process of serial port greatly.

This class library mainly includes: Serialbean.java (interface with other applications), Serialbuffer.java (used to save the data received from the serial port buffer area), Readserial.java (from the serial port to read the data program). In addition, this class library also provides a routine Serialexample.java as a demonstration. Each of these sections is described in detail in the following section.

1. Serialbean

Serialbean is the interface of this class library with other applications. This class library defines the construction method of Serialbean and the function of initializing serial port, reading data from serial port, writing data to serial port and shutting down serial port. The details are as follows:
Public Serialbean (int portid)

This function constructs a serialbean that points to a specific serial port, which is specified by the parameter portid. Portid = 1 means that Com1,portid = 2 represents COM2, and so on.

public int Initialize ()

This function initializes the specified serial port and returns the initialization result. Returns 1 if the initialization succeeds in returning 1. The result of initialization is that the serial port is Serialbean exclusive and its parameters are set to 9600, N, 8, 1. If the serial port is initialized successfully, a process is opened to read the incoming data from the serial port and save it in a buffer.

Public String readport (int Length)

This function reads a string of a specified length from a serial port (buffer). Parameter length specifies the length of the returned string.

public void Writeport (String Msg)

This function sends a string to the serial port. Parameter msg is a string that needs to be sent.

public void Closeport ()

This function stops the serial port detection process and closes the serial port.

Serialbean's source code is as follows:

Package serial;

Import java.io.*;
Import java.util.*;
Import javax.comm.*;

/**
*
* This bean provides some basic functions to implement full Dulplex
* Information exchange through the srial port.
*
*/

public class Serialbean
{
Static String PortName;
Commportidentifier Portid;
SerialPort SerialPort;
static OutputStream out;
Static InputStream in;

Serialbuffer SB;
Readserial RT;

/**
*
* Constructor
*
* @param portid The ID of the serial to be used. 1 for COM1,
* 2 for COM2, etc.
*
*/

Public Serialbean (int portid)
{
PortName = "COM" + portid;
}

/**
*
* This function initialize the serial port for communication. It starts a
* Thread which consistently monitors the serial port. Any signal captured
* From the serial port are stored into a-buffer area.
*
*/

public int Initialize ()
{

int initsuccess = 1;
int initfail =-1;

Try
{

Portid = Commportidentifier.getportidentifier (portname);

Try
{
SerialPort = (serialPort)
Portid.open ("Serial_communication", 2000);
catch (Portinuseexception e)
{
return initfail;
}

Use InputStream in to read from the serial port, and OutputStream
Out to write to the serial port.

Try
{
in = Serialport.getinputstream ();
out = Serialport.getoutputstream ();
catch (IOException E)
{
return initfail;
}

Initialize the communication parameters to 9600, 8, 1, none.

Try
{
Serialport.setserialportparams (9600,
Serialport.databits_8,
Serialport.stopbits_1,
Serialport.parity_none);
catch (Unsupportedcommoperationexception e)
{
return initfail;
}
catch (Nosuchportexception e)
{
return initfail;
}

When successfully open the serial port, create a new serial buffer,
Then create a thread that consistently accepts incoming signals from
The serial port. Incoming signals are stored in the serial buffer.

SB = new Serialbuffer ();
RT = new Readserial (SB, in);
Rt.start ();

Return success Information
 
return initsuccess;
}

/**
*
* This function returns a string with a certain length from the incoming
* Messages.
*
* @param length The length of the string to be returned.
*
*/

Public String readport (int Length)
{
String MSG;
MSG = SB. Getmsg (Length);
return MSG;
}

/**
*
* This function sends a through the serial port.
*
* @param Msg The string to be sent.
*
*/

public void Writeport (String Msg)
{
int C;
Try
{
for (int i = 0; i < msg.length (); i++)
Out.write (Msg.charat (i));
catch (IOException e) {}
}

/**
*
* This function closes the serial port with use.
*
*/

public void Closeport ()
{
Rt.stop ();
Serialport.close ();
}
}

2. Serialbuffer

Serialbuffer is a serial buffer defined in this class library that defines the functions required to write data to the buffer and read data from that buffer.

Public synchronized String getmsg (int Length)

This function reads a string of a specified length from a serial port (buffer). Parameter length specifies the length of the returned string.

Public synchronized void Putchar (int c)

This function looks at the serial port buffer to write a character, parameter C is required to write characters.

When writing data to a buffer or reading data from a buffer, the data must be synchronized, so the getmsg and Putchar functions are declared as synchronized and synchronized with the data implemented in the implementation of the measures.

Serialbuffer's source code is as follows:

Package serial;

/**
*
* This class implements the ' buffer area ' to ' store incoming data from the serial
* Port.
*
*/

public class Serialbuffer
{
Private String Content = "";
Private String currentmsg, tempcontent;
Private Boolean available = false;
private int lengthneeded = 1;

/**
*
* This function returns a string with a certain length from the incoming
* Messages.
*
* @param length The length of the string to be returned.
*
*/

Public synchronized String getmsg (int Length)
{
lengthneeded = Length;
Notifyall ();

if (lengthneeded > Content.length ())
{
Available = false;
while (available = = false)
{
Try
{
Wait ();
catch (Interruptedexception e) {}
}
}

currentmsg = content.substring (0, lengthneeded);
Tempcontent = content.substring (lengthneeded);
Content = tempcontent;
lengthneeded = 1;
Notifyall ();
return currentmsg;
}

/**
*
* This function stores a character captured from the serial port to the
* Buffer area.
*
* @param t The char value of the character to is stored.
*
*/

Public synchronized void Putchar (int c)
{
Character d = new Character ((char) c);
Content = Content.concat (d.tostring ());
if (Lengthneeded < Content.length ())
{
Available = true;
}
Notifyall ();
}
}


3. readserial

Readserial is a process that continuously reads data from a specified serial port and stores it in a buffer.

Public readserial (Serialbuffer SB, InputStream Port)

This function constructs a readserial process, and parameter SB specifies the buffer in which the incoming data is stored, and the parameter port specifies the stream of data received from the serial port.

public void Run ()

The main function of the readserial process, which continuously reads data from a specified serial port and stores it in a buffer.

Readserial's source code is as follows:

Package serial;

Import java.io.*;

/**
*
* This class reads the specific serial port and save
* The message to the serial buffer.
*
*/

public class Readserial extends Thread
{
Private Serialbuffer Combuffer;
Private InputStream comport;

/**
*
* Constructor
*
* @param SB the buffer to save the incoming messages.
* @param port The InputStream from the specific serial port.
*
*/

Public readserial (Serialbuffer SB, InputStream Port)
{
Combuffer = SB;
Comport = Port;
}

public void Run ()
{
int C;
Try
{
while (true)
{
c = Comport.read ();
Combuffer.putchar (c);
}
catch (IOException e) {}
}
}

4. Serialexample

Serialexample is a routine provided by this class library. It realizes the function is opens the serial port COM1, carries on the initialization, from the serial port reads the information to it processing after the processing result sends to the serial port.

Import serial.*;
Import java.io.*;

/**
*
* This is an example of the Serialbean. It opens COM1 and reads
* Six messages with different length form the serial port.
*
*/

Class Serialexample
{
public static void Main (string[] args)
{
To do:add your JAVA codes

Serialbean SB = new Serialbean (1);
String MSG;
 
SB. Initialize ();
for (int i = 5; I <= i++)
{
MSG = SB. Readport (i);
SB. Writeport ("Reply:" + MSG);
}
SB. Closeport ();
}
}


5. Compiling and debugging

The Java Communication API (JAVAX.COMM) is used in this class library. This is a Java Extension class library that is not included in the standard Java SDK. If you haven't installed the Extended class library, you should download the library from Sun's Java site and install it on your system. In the download package contains an installation instructions, if you do not properly install the class library and its operating environment, you can run this program when you will not find the serial port.

After properly installing the Java Communication API and compiling the above program, you can test the program as follows. If you have only one machine, you can use a RS-232 cable to connect COM1 and COM2, run Serialexample on COM1, and run the HyperTerminal program provided by Windows on the COM2. If you have two machines, you can use a RS-232 cable to connect the COM1 (or COM2) of two machines, run routines at one end, and run the HyperTerminal program provided by Windows at the other end. If there is a need for
, you can make corresponding changes to the serial port declared in Serialexample.

This program compiles and runs successfully in Windows Java SDK 1.3 environment.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.