Java+jSSC 串口从读取数据
首先搜索jSSC 并下载jssc包
http://www.mvnjar.com/org.scream3r/jssc/2.8.0/detail.html
或者
https://download.****.net/download/xiatiancc/10519259
然后把该包加入到Eclipse 项目中(通过file->build path->configure build path->java build path->Libraries->add external jars)
引用jssc.jar文件。
import jssc.SerialPort;
import jssc.SerialPortException;
public class SerialRecieveData{
public static void main(String[] args) throws InterruptedException{
new Thread(new Runnable(){ //开启线程
@Override
public void run() {
// TODO Auto-generated method stub
SerialPort serialPort = new SerialPort("/dev/ttyACM2"); //设置串口
try {
//Open port
serialPort.openPort();
//We expose the settings. You can also use this line - serialPort.setParams(9600, 8, 1, 0);
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
String buffer = serialPort.readString(5); //从串口读取5字符字符串
System.out.println(buffer);
if(buffer.trim().equals("Hello")){
System.out.println("start write");
serialPort.writeBytes("1".getBytes()); // 往串口写入数据
}else{
System.out.println("failed");
}
//Closing the port
serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}}
).start();
}
}