Data Reading through serial ports

Source: Internet
Author: User
How to read data through serial ports-Linux general technology-Linux programming and kernel information. Import java. io .*;
Import java. util .*;
Import gnu. io .*;
Import java. awt .*;
Import java. util. Properties;
Import javax. swing .*;
Import java. awt. event .*;


/**
* Class declaration
*
*
* @ Author
* @ Version 09/03/20
*/
Public class test extends JFrame implements ActionListener, SerialPortEventListener
{
Static Enumeration portList;
Static commp ortidentifier portId;
Static String messageString;
Static SerialPort serialPort;
Static InputStream inputStream;
Static boolean outputBufferEmptyFlag = false;
JScrollPane p1;
// JTextField Text = new JTextField (10 );
JTextField port = new JTextField (10 );
JButton OK = new JButton ("open ");
JTextArea area = new JTextArea (15, 10 );
// JLabel l1 = new JLabel ("Message :");
JLabel l2 = new JLabel ("port :");
JButton read = new JButton ("read ");
/**
* Method declaration
*
*
* @ Param args
*
* @ See
*/
Test ()
{
SetTitle ("SerialCom ");
SetVisible (true );
SetLayout (null );
P1 = new JScrollPane (area );

Add (port); port. setBounds (, 30 );
Add (l2); l2.setBounds (35,30, 100,25 );
Add (OK); OK. setBounds (, 30, 80, 23 );
Add (read); read. setBounds (150, 80, 80, 25 );
Add (p1); p1.setBounds (35,120,340,250 );
OK. addActionListener (this );
Read. addActionListener (this );

SetSize (400,400 );
Setdefaclocloseoperation (JFrame. DISPOSE_ON_CLOSE );
SetResizable (true );
Dimension screen = Toolkit. getdefatooltoolkit (). getScreenSize ();
SetLocation (screen. width)/4, (screen. height)/4 );

AddWindowListener (new WindowAdapter (){
Public void windowClosing (incluwevent we ){
SerialPort. close ();
System. exit (0 );
}
});
}

Public void actionreceivmed (ActionEvent e)
{
If (e. getSource () = OK)
{
Boolean portFound = false;
String useport = port. getText ();

Area. append ("choose port :");
Area. append (useport );
Area. append ("\ n ");
System. out. println ("choose port:" + useport );

String defaultPort = "/dev/" + useport;

PortList = commp ortidentifier. getPortIdentifiers ();

While (portList. hasMoreElements ()){
PortId = (comatrix ortidentifier) portList. nextElement ();

If (portId. getPortType () = comatrix ortidentifier. PORT_SERIAL ){

If (portId. getName (). inclusignorecase (defaultPort )){
Area. append ("Found port :");
Area. append (defaultPort );
Area. append ("\ n ");
System. out. println ("Found port" + defaultPort );

PortFound = true;

Try {
SerialPort = (SerialPort) portId. open ("test", 200000 );
}
Catch (PortInUseException ex ){
Area. append ("Port in use! ");
// Area. append (defaultPort );
Area. append ("\ n ");
System. out. println ("Port in use .");

Continue;
}

Try {
SerialPort. setSerialPortParams (115200,
SerialPort. DATABITS_8,
SerialPort. STOPBITS_1,
SerialPort. PARITY_NONE );
}
Catch (UnsupportedCommOperationException ex ){}



// Area. append (serialPort. getName ());
Area. append ("\ n ");

// SerialPort. close ();
// System. exit (1 );
}
}
}

If (! PortFound ){

Area. append ("port ");
Area. append (defaultPort );
Area. append ("not found! ");
Area. append ("\ n ");
System. out. println ("port" + defaultPort + "not found .");
}
}
Else if (e. getSource () = read)
{
Area. append ("wait for msg :");
Area. append ("\ n ");
Try
{
SerialPort. addEventListener (this );
}
Catch (TooManyListenersException ){}
SerialPort. yonyondataavailable (true );
Try
{
InputStream = serialPort. getInputStream ();
}
Catch (IOException ){}

}
}
Public void serialEvent (SerialPortEvent event)
{
Switch (event. getEventType ())
{
Case SerialPortEvent. BI:
Case SerialPortEvent. OE:
Case SerialPortEvent. FE:
Case SerialPortEvent. PE:
Case SerialPortEvent. CD:
Case SerialPortEvent. CTS:
Case SerialPortEvent. DSR:
Case SerialPortEvent. RI:
Case SerialPortEvent. OUTPUT_BUFFER_EMPTY:
Break;
Case SerialPortEvent. DATA_AVAILABLE:
Byte [] readBuffer = new byte [200];
Try
{
String fileName = null;
While (inputStream. available ()> 0)
{
Area. append ("there are data available in the port ");
Area. append ("\ n ");
Int numBytes = inputStream. read (readBuffer );
FileName = "/root/data.txt ";
BufferedWriter bw = new BufferedWriter (new FileWriter (fileName ));
Try {

String str = new String (readBuffer );
Bw. write (str); // write
Bw. newLine ();

}
Catch (IOException e ){}
Area. append (new String (readBuffer ));

Bw. close ();

}


}
Catch (IOException e ){}
Break;
}
}



Public static void main (String [] args)
{

New test ();
}

} This interface runs on pc a. After selecting port and open, click the read button. When another pc B sends data, it can correctly receive and write the file.
However, after adding a write button, click this button and send the command "ask for reply" to B. After B receives the button, it sends "13900100400" to a, which means that a receives all garbled characters. The Code is as follows: package comm;
Import java. io .*;
Import java. util .*;

Import gnu. io .*;

Import java. awt .*;
Import java. util. Properties;
Import javax. swing .*;

Import java. awt. event .*;
Import java. io .*;
Import java. util .*;

Import javax. swing. JFrame;

Import gnu. io .*;

/**
* Class declaration
*
*
* @ Author
* @ Version 09/03/20
*/
Public class test extends JFrame implements ActionListener, Runnable, SerialPortEventListener
{
Static Enumeration portList;
Static commp ortidentifier portId;
Static String messageString;
Static SerialPort serialPort;
Static InputStream inputStream;
Static OutputStream outputStream;
Static boolean outputBufferEmptyFlag = false;
Thread readThread = new Thread ();
JScrollPane p1;
JTextField port = new JTextField (10 );
JButton OK = new JButton ("open ");
JTextArea area = new JTextArea (15, 10 );
// JLabel l1 = new JLabel ("Message :");
JLabel l2 = new JLabel ("port :");
JButton write = new JButton ("write ");
JButton read = new JButton ("read ");
/**
* Method declaration
*
*
* @ Param args
*
* @ See
*/
Test ()
{
SetTitle ("SerialCom ");
SetVisible (true );
SetLayout (null );
P1 = new JScrollPane (area );

Add (port); port. setBounds (, 30 );
Add (l2); l2.setBounds (35,30, 100,25 );

// Add (Text); Text. setBounds );
Add (OK); OK. setBounds (, 30, 80, 23 );
Add (read); read. setBounds (150, 80, 80, 25 );
Add (writes); write. setBounds (150,120, 80, 25 );
Add (p1); p1.setBounds (35,150,340,250 );
OK. addActionListener (this );
Read. addActionListener (this );
Write. addActionListener (this );
SetSize (400,400 );
Setdefaclocloseoperation (JFrame. DISPOSE_ON_CLOSE );
SetResizable (true );
Dimension screen = Toolkit. getdefatooltoolkit (). getScreenSize ();
SetLocation (screen. width)/4, (screen. height)/4 );

AddWindowListener (new WindowAdapter (){
Public void windowClosing (incluwevent we ){
SerialPort. close ();
System. exit (0 );
}
});
}

Public void actionreceivmed (ActionEvent e)
{
If (e. getSource () = OK)
{
Boolean portFound = false;
String useport = port. getText ();

Area. append ("choose port :");
Area. append (useport );
Area. append ("\ n ");
System. out. println ("choose port:" + useport );

String defaultPort = "/dev/" + useport;

PortList = commp ortidentifier. getPortIdentifiers ();

While (portList. hasMoreElements ()){
PortId = (comatrix ortidentifier) portList. nextElement ();

If (portId. getPortType () = comatrix ortidentifier. PORT_SERIAL ){

If (portId. getName (). inclusignorecase (defaultPort )){
Area. append ("Found port :");
Area. append (defaultPort );
Area. append ("\ n ");
System. out. println ("Found port" + defaultPort );

PortFound = true;

Try {
SerialPort = (SerialPort) portId. open ("test", 200000 );
}
Catch (PortInUseException ex ){
Area. append ("Port in use! ");
// Area. append (defaultPort );
Area. append ("\ n ");
System. out. println ("Port in use .");

Continue;
}

Try {
OutputStream = serialPort. getOutputStream ();
}
Catch (IOException ex ){}

Try {
SerialPort. setSerialPortParams (115200,
SerialPort. DATABITS_8,
SerialPort. STOPBITS_1,
SerialPort. PARITY_NONE );
}
Catch (UnsupportedCommOperationException ex ){}



// Area. append (serialPort. getName ());
Area. append ("\ n ");

// SerialPort. close ();
// System. exit (1 );
}
}
}

If (! PortFound ){

Area. append ("port ");
Area. append (defaultPort );
Area. append ("not found! ");
Area. append ("\ n ");
System. out. println ("port" + defaultPort + "not found .");
}
}
Else if (e. getSource () = read)
{
Area. append ("wait for msg :");
Area. append ("\ n ");
Try
{
SerialPort. addEventListener (this );
}
Catch (TooManyListenersException ){}
SerialPort. yonyondataavailable (true );
Try
{
InputStream = serialPort. getInputStream ();
}
Catch (IOException ){}

}
Else if (e. getSource () = write)
{
String message = "ask for reply ";
Try {
OutputStream. write (message. getBytes ());
}
Catch (IOException ex ){}

Area. append ("write message :");
Area. append (message );
Area. append ("\" to the port \ n ");

Try
{
SerialPort. addEventListener (this );
}
Catch (TooManyListenersException ){}
SerialPort. yonyondataavailable (true );
Try
{
InputStream = serialPort. getInputStream ();
}
Catch (IOException ){}

ReadThread = new Thread (this );
ReadThread. start ();


}
}

Public void run ()
{
Try
{
Thread. sleep (6000 );
}
Catch (InterruptedException e ){}
}
Public void serialEvent (SerialPortEvent event)
{
Switch (event. getEventType ())
{
Case SerialPortEvent. BI:
Case SerialPortEvent. OE:
Case SerialPortEvent. FE:
Case SerialPortEvent. PE:
Case SerialPortEvent. CD:
Case SerialPortEvent. CTS:
Case SerialPortEvent. DSR:
Case SerialPortEvent. RI:
Case SerialPortEvent. OUTPUT_BUFFER_EMPTY:
Break;
Case SerialPortEvent. DATA_AVAILABLE:
Byte [] readBuffer = new byte [200];
Try
{
String fileName = null;
While (inputStream. available ()> 0)
{
Area. append ("there are data available in the port ");
Area. append ("\ n ");
Int numBytes = inputStream. read (readBuffer );
FileName = "/root/data.txt ";
BufferedWriter bw = new BufferedWriter (new FileWriter (fileName ));
Try {

String str = new String (readBuffer );
Bw. write (str); // write
Bw. newLine ();

}
Catch (IOException e ){}
Area. append (new String (readBuffer ));

Bw. close ();

}


}
Catch (IOException e ){}
Break;
}
}



Public static void main (String [] args)
{

New test ();
}


} Only write and read in the added write button actioncommitted med, and read garbled characters when the thread is used. Can't I write and read it at the same time? Is it because thread sleep is not enough time, or is it because the test thread open port is not enough time?

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.