开发者社区> 问答> 正文

Java串口完整实例

上级要求用java写个串口,但是小弟第一次,不会写呀!求哪个好心大神帮帮忙,给个实例!

展开
收起
蛮大人123 2016-06-08 14:27:15 2273 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    
    public class SimpleCommIO implements Runnable {
    
        static CommPortIdentifier portId;
        static String cmdHand = "I\r\n";
        static String cmdWeight = "WX\r\n";
        static SerialPort serialPort;
        static OutputStream outputStream;
        static String comm="COM11";
    
        InputStream inputStream;
        Thread readThread;
    
        public void run() {
            while (true) {
                try {
                    byte[] readBuffer = new byte[200];
    
                    try {
                        while (inputStream.available() > 0) {
                            int numBytes = inputStream.read(readBuffer);
                            System.out.print("收到数据:"+new String(readBuffer));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
        public void initComm() {
            try{
                portId = CommPortIdentifier.getPortIdentifier(comm);
                serialPort = (SerialPort) portId.open("SimpleCommIO",2000);
    
                outputStream = serialPort.getOutputStream();
                inputStream = serialPort.getInputStream();
    
                serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8, 
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
            }catch(Exception e){
                e.printStackTrace();
            }
    
        }
    
        public void writeComm(String cmd) {
            try {
                outputStream.write(cmd.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
    
            SimpleCommIO reader = new SimpleCommIO();
            reader.initComm();
            Thread readThread = new Thread(reader);
            readThread.start();
            System.out.println("发出指令:"+cmdHand);
            reader.writeComm(cmdHand);
            
            //暂停一会儿
            try { 
                Thread.sleep ( 2000 ) ; 
            } catch (InterruptedException ie)
            {
                
            }
            System.out.println("发出指令:"+cmdWeight);
            reader.writeComm(cmdWeight);
        }
    
    }
    2019-07-17 19:31:54
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载