Java+jSSC 串口从读取数据

来源:互联网 发布:企业数据标准化 编辑:程序博客网 时间:2024/06/06 04:01

首先google搜索jSSC 并下载jssc包

然后把该包加入到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();
    }

}

0 0
原创粉丝点击