26 เมษายน 2561
การเขียนโปรแกรมรับส่งข้อมูลทางพอร์ตอนุกรมด้วย Java
ในบทความนี้จะแสดงตัวอย่างการรับส่งข้อมูลทางพอร์ตอนุกรมด้วยภาษา Java โดยใช้ Netbeans เป็นคอมไพเลอร์ สามารถดาวน์โหลดโปรแกรม Netbeans มาใช้งานได้ฟรีจาก https://netbeans.org
ก่อนอื่นให้ download Library สำหรับใช้ติดต่อพอร์ตอนุกรมด้วยภาษา Java ก่อน โดยสามารถเข้าไป download ได้ที่ http://rxtx.qbang.org/wiki/index.php/Download เมื่อ download เสร็จแล้วให้แตกไฟล์ zip แล้ว Add ไฟล์ RXTXcomm.jar เข้าไปยังโปรแกรม Netbeans เนื่องจากตัวอย่างนี้ใช้ระบบปฏิบัติการ Windows ดังนั้น ให้คัดลอกไฟล์ rxtxParallel.dll และ rxtxSerial.dll ไปวางไว้ที่ \jre\bin หากใช้ระบบปฏิบัติการอื่นให้ดูวิธีติดตั้งได้ที่ไฟล์ INSTALL ในไฟล์ zip ที่ download มา
เมื่อติดตั้งเรียบร้อยแล้ว ให้สร้าง Project ใหม่ขึ้นมาแล้วสร้างหน้าต่างโปรแกรมดังนี้

ในส่วนของโค้ดให้ import Library เข้าไปดังนี้
import java.io.*;
import java.util.*;
import gnu.io.*;
import javax.swing.SwingUtilities;
จากนั้นให้ implements Runnable, SerialPortEventListener และประกาศตัวแปรดังนี้
int i=1;
static CommPortIdentifier portId;
InputStream inputStream;
SerialPort serialPort;
static String messageString = "Hello Serial"; // ข้อมูลที่จะทดลองส่งออกจากพอร์ตอนุกรม
static OutputStream outputStream;
String port="COM3";
int baudrate= 9600;
public String temp = "";
คลิกขวาที่ปุ่ม Connect แล้วเลือก Events -> Action -> actionPerformed แล้วใส่ฟังก์ชั่นนี้เข้าไป
ConnectSerial();
คลิกขวาที่ปุ่ม Disconnect แล้วเลือก Events -> Action -> actionPerformed แล้วเขียนโค้ดดังนี้
serialPort.close();
คลิกขวาที่ปุ่ม Send แล้วเลือก Events -> Action -> actionPerformed แล้วเขียนโค้ดดังนี้
try {
// write string to serial port
outputStream.write(messageString.getBytes());
} catch (IOException e) {
}
จากนั้นให้เพิ่มฟังก์ชั่นต่อไปนี้เข้าไปในโค้ด
@Override
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
@Override
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:
ReadData();
break;
}
}
private void ConnectSerial() {
// initalize serial port
try {
portId = CommPortIdentifier.getPortIdentifier(port);
} catch (Exception exception) {
}
try {
serialPort = (SerialPort) portId.open("Test232", 2000);
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
} catch (Exception exception) {
}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
}
// activate the DATA_AVAILABLE notifier
serialPort.notifyOnDataAvailable(true);
try {
// set port parameters
serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
}
public void ReadData(){
// runs this if data has been received
/* try {
int nb = inputStream.available();
while (nb > 0) {
byte[] readBuffer = new byte[nb];
inputStream.read(readBuffer);
String str = new String(readBuffer);
jTextArea1.append(str);
m_shTxt.setText(str);
// jTextArea1.append("aaaaa");
nb = inputStream.available();
}
} catch (IOException e) {}
*/
try {
/**if command available hardware respone data here**/
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "tis-620"));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
final String testline = line;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
m_shTxt.setText(Integer.toString(i));
jTextArea1.append(testline + "\n");
i++;
}
});
}
}
} catch (IOException e) {
}
// break;
}
ถ้าหากต้องการให้ Netbeans ทำการ import Library ให้โดยอัตโนมัติ ให้กดปุ่ม Ctrl+Shift+I เพื่อ fix impors
References :
http://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/javax/comm/package-summary.html
http://www.thainetbeans.com/articles/serial/serial.php
http://java.sun.com/developer/releases/javacomm/SimpleRead.java
http://java.sun.com/developer/releases/javacomm/SimpleWrite.java
Please login for comment