การส่งข้อมูลผ่าน com port ด้วย java ก่อนอื่นต้องไป download library "RXTXcomm" จากเว็บ //rxtx.qbang.org/wiki/index.php/Download แล้วแตกไฟล์ไปที่ Drive C: (หรือ drive อื่นก็ตามสะดวก) จากนั้นให้ทำขั้นตอนต่อไปนี้
- copy file "C:/rxtx-2.1-7-bins-r2/Windows/i368-mingw32/*.dll" ไปเก็บที่ home directory ของ java ยกตัวอย่าง "C:/Program Files/Java/jdk1.7.0_02/bin/"
- copy file "C:/rxtx-2.1-7-bins-r2/RXTXComm.jar" เก็บไว้ที่ ext lib ของ java ยกตัวอย่าง "C:/Program Files/Java/jre7/lib/ext/"
- boot เครื่องใหม่
- เปิดโปรแกรม Netbeans
- สร้าง Project ชื่อ TestComPort
- คลิ้กขวาที่ชื่อ Project -> Properties เลือกหัวข้อ Libraries แล้วกดปุ่ม "Add JAR/Folder" เลือกไฟล์ .jar ชื่อ "RXTXComm.jar" ตามรูป
จากนั้นเริ่มเขียน code ตามนี้
package testcomport;
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class TestComPort {
private InputStream in;
private OutputStream out;
public TestComPort() {
}
public void run() {
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1"); // ใส่ชื่อ com port ที่ต้องการใช้งาน
if (portIdentifier.isCurrentlyOwned()) {
JOptionPane.showMessageDialog(null, "Error: Port COM1 is currently in use", "Notice", JOptionPane.INFORMATION_MESSAGE);
} else {
CommPort commPort = portIdentifier(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // ตรงนี้ต้อง set ให้ตรงกับ com port ที่ติดต่อด้วยที่ความเร็ว และ databits (บางอุปกรณ์เป็น 7)
out = serialPort.getOutputStream();
in = serialPort.getInputStream();byte[] hello = {'H', 'E', 'L', 'L', 'O', 0x0D, 0x0A};
out.write(hello);
out.flush(); // ส่ง string "HELLO" ออกไปยัง com port 0x0D, 0x0aA คือตัว Enter หรือ "n" (บางอุปกรณ์ต้องสลับกัน)
in = serialPort.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) > -1) {
System.out.println(new String(buffer, 0, len)); // พิมพ์ค่าที่อ่านจาก com port
}
in.close();
} else {
JOptionPane.showMessageDialog(null, "Error: Only serial ports COM1 are handled by this example.", "Notice", JOptionPane.INFORMATION_MESSAGE);
}
commPort.close();
}
/**
* @param args the command line arguments
*/
} catch (IOException | UnsupportedCommOperationException | PortInUseException | NoSuchPortException ex) {
Logger.getLogger(TestComPort.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TestComPort prog = new TestComPort();
prog.run();
}
}
เมื่อใส่ code เสร็จให้ต่ออุปกรณ์ที่ com port แล้วกด F6 เพื่อ Run โปรแกรมผลจะอยู่ที่ out put pane ด้านล่าง
CommPort commPort = portIdentifier(this.getClass().getName(), 2000);
ตรง portIdentifier มัน ERROR ครับ
พอดีกำลังเริ่มศึกษา JAVA อ่ะครับ
รบกวนดูให้ที ขอบคุณครับ