A Practical Java serial communication program that sends/receives data from the serial port COM1

Source: Internet
Author: User
This article mainly provides a practical Java serial communication program for discussion and learning.

/*************************************** ***
* Program file name: sendcomm. Java
* Function: send data from the serial port COM1
**************************************** **/
Import java. AWT .*;
Import java. AWT. event .*;
Import java. Io .*;
Import java. util .*;
Import javax. Comm .*;

Class s_frame extends frame implements runnable, actionlistener
{
/* Detect available communication port categories in the system */
Static commp ortidentifier portid;
/* Enumeration is an enumeration class, in util */
Static enumeration portlist;
Outputstream;
/* Serial port of RS-232 */
SerialPort;
Thread readthread;
Panel P = new Panel ();
Textfield in_message = new textfield ("enable COM1, baud rate 9600, data bit 8, stop bit 1 .");
Textarea out_message = new textarea ();
Button btnopen = new button ("Open the serial port and send data ");
Button btnclose = new button ("Close the serial port and stop sending data ");
Byte data [] = new byte [10240];
/* Set the flag to determine whether to disable the serial port */
Boolean mark;

/* Arrange the form */
S_frame ()
{Super ("sending data via serial port ");
Setsize (200,200 );
Setvisible (true );
Add (out_message, "center ");
Add (P, "North ");
P. Add (btnopen );
P. Add (btnclose );
Add (in_message, "South ");
Btnopen. addactionlistener (this );
Btnclose. addactionlistener (this );
} // R_frame () End

/* Click the button to open the serial port .*/
Public void actionreceivmed (actionevent event ){
If (event. getsource () = btnclose ){
SerialPort. Close (); // close the serial port
Mark = true; // run () method used to abort a thread
In_message.settext ("Serial Port COM1 has been disabled, stop sending data .");
}
Else {mark = false;
/* Read data by byte from the shard area */
Data = out_message.gettext (). getbytes ();
/* Open the serial port */
Start ();
In_message.settext ("Serial Port COM1 is enabled, and data is being sent every 2 seconds .....");
}
} // Action=med () End

/* Open the serial port and call the thread to send data */
Public void start (){
/* Obtain all communication ports in the system */
Portlist = commp ortidentifier. getportidentifiers ();
/* Use the loop structure to find the serial port */
While (portlist. hasmoreelements ()){
/* Forcibly convert to communication port type */
Portid = (comatrix ortidentifier) portlist. nextelement ();
If (portid. getporttype () = comatrix ortidentifier. port_serial ){
If (portid. getname (). Equals ("COM1 ")){
/* Open the serial port */
Try {
SerialPort = (SerialPort) portid. Open ("readcomm", 2000 );
}
Catch (portinuseexception e ){}
/* Set the serial output stream */
Try {
Outputstream = SerialPort. getoutputstream ();
}
Catch (ioexception e ){}
} // If end
} // If end
} // While end
/* Call the thread to send data */
Try {
Readthread = new thread (this );
// The thread is responsible for sending data every time, sleeping for 2 seconds
Readthread. Start ();
}
Catch (exception e ){}
} // Start () End

/* Send data, and re-send after 2 seconds of hibernation */
Public void run (){
/* Set serial communication parameters */
Try {
SerialPort. setserialportparams (9600,
SerialPort. databits_8,
SerialPort. stopbits_1,
SerialPort. parity_none );
}
Catch (unsupportedcommoperationexception e ){}
/* Send data streams (send the data in the array data )*/
Try {
Outputstream. Write (data );
}
Catch (ioexception e ){}
/* Sleep for 2 seconds after the data is sent and resend */
Try {thread. Sleep (2000 );
If (mark)
{Return; // end the run method, resulting in thread death
}
Start ();
}
Catch (interruptedexception e ){}
} // Run () End
} // Class s_frame end

Public class sendcomm
{Public static void main (string ARGs [])
{S_frame s_win = new s_frame ();
S_win.addwindowlistener (New windowadapter ()
{Public void windowclosing (invalid wevent E)
{System. Exit (0 );}
});
S_win.pack ();
}
}

/*************************************** ***
* Program file name: readcomm. Java
* Function: receives data from the serial port COM1.
**************************************** **/
Import java. AWT .*;
Import java. AWT. event .*;
Import java. Io .*;
Import java. util .*;
Import javax. Comm .*;

Class r_frame extends frame implements runnable, actionlistener, serialporteventlistener
{
/* Detect available communication port categories in the system */
Static commp ortidentifier portid;
/* Enumeration is an enumeration class, in Java. util */
Static enumeration portlist;
Inputstream;
/* Declare the member variable of the RS-232 serial port */
SerialPort;
Thread readthread;
String STR = "";
Textfield out_message = new textfield ("the text box above shows the received data ");
Textarea in_message = new textarea ();
Button btnopen = new button ("open serial port ");

/* Create a form */
R_frame ()
{
Super ("Serial Port receiving data ");
Setsize (200,200 );
Setvisible (true );
Btnopen. addactionlistener (this );
Add (out_message, "South ");
Add (in_message, "center ");
Add (btnopen, "North ");
} // R_frame () End

/* Click the button to trigger the event: Open the serial port and listen to the serial port .*/
Public void actionreceivmed (actionevent event)
{
/* Obtain all communication ports in the system */
Portlist = commp ortidentifier. getportidentifiers ();
/* Use the loop structure to find the serial port */
While (portlist. hasmoreelements ()){
/* Forcibly convert to communication port type */
Portid = (comatrix ortidentifier) portlist. nextelement ();
If (portid. getporttype () = comatrix ortidentifier. port_serial ){
If (portid. getname (). Equals ("COM1 ")){
Try {
SerialPort = (SerialPort) portid. Open ("readcomm", 2000 );
Out_message.settext ("the port COM1 is enabled and receiving data .....");
}
Catch (portinuseexception e ){}

/* Set the serial port listener */
Try {
SerialPort. addeventlistener (this );
}
Catch (toomanylistenersexception e ){}
/* Listen to the serial port for data and trigger the serial port event */
SerialPort. yonyondataavailable (true );
} // If end
} // If end
} // While end
Readthread = new thread (this );
Readthread. Start (); // The thread is responsible for every 20 seconds of Data sleep received
} // Action=med () End

/* Sleep for 20 seconds after receiving data */
Public void run (){
Try {
Thread. Sleep (20000 );
}
Catch (interruptedexception e ){}
} // Run () End

/* Set the serial communication parameters for the events triggered by the serial port listener, read the data, and write the data to the serial port listener */
Public void serialevent (serialportevent event ){
/* Set serial communication parameters: baud rate, data bit, stop bit, and parity */
Try {
SerialPort. setserialportparams (9600,
SerialPort. databits_8,
SerialPort. stopbits_1,
SerialPort. parity_none );
}
Catch (unsupportedcommoperationexception e ){}
Byte [] readbuffer = new byte [20];
Try {
Inputstream = SerialPort. getinputstream ();
}
Catch (ioexception e ){}
Try {
/* Read data streams from the line */
While (inputstream. Available ()> 0 ){
Int numbytes = inputstream. Read (readbuffer );
} // While end
STR = new string (readbuffer );
/* The received data is stored in the Region */
In_message.append (STR + "/N ");
}
Catch (ioexception e ){}
} // Serialevent () End
} // Class r_frame end

Public class readcomm
{
Public static void main (string ARGs [])
{
/* Instantiate the Form class for receiving serial data */
R_frame r_win = new r_frame ();
/* Define the button function for the form adapter */
R_win.addwindowlistener (New windowadapter ()
{Public void windowclosing (invalid wevent E)
{System. Exit (0 );}
});
R_win.pack ();
}
}

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.