java 读取地磅读数,COM口.

private String weightNum(){
         int flag=1;
        String data=null;
        CommPortIdentifier portId = null;
        InputStream inputStream=null;//串口输入流
        SerialPort serialPort=null;//串口对象
        String str1=null;//缓冲区字节码转换后的字符串
        byte[] readBuffer = new byte[4096];//用于存放串口输入流中读取的字节缓冲区
        StringBuffer buffer = new StringBuffer();//将字节缓冲区的值拼接成字符串
        try{
            Enumeration en = CommPortIdentifier.getPortIdentifiers();
            if(en.hasMoreElements()){
                portId=(CommPortIdentifier)en.nextElement();
                
                if(portId.getPortType()!=CommPortIdentifier.PORT_SERIAL){
                }
            }
            if(portId!=null){//如果有端口对象,打开端口,得到数据流
                
                    serialPort = (SerialPort) portId.open("wData", 1000);//portId.open("串口所有者名称", 超时等待时间);
                    inputStream = serialPort.getInputStream();//获取端口数据流
                    serialPort.setSerialPortParams(9600,//波特率-9600
                    SerialPort.DATABITS_8,//数据位数-8
                    SerialPort.STOPBITS_1,//停止位-1
                    SerialPort.PARITY_NONE);//校验-无
                
            }
            if(flag==1){
                    Thread.sleep(1000);
                    while(inputStream.available() > 0) {
                        inputStream.read(readBuffer);/
                        buffer.append(new String(readBuffer).trim());//去除数据中间空格
                        str1=buffer.toString();//将拼接的字符串转换成用于分离的字符串
                        data=str1;
                        buffer.delete(0, buffer.length());//清空字符串拼接缓存区
                    }
            }
            inputStream.close();
            serialPort.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return data;
    }

调用:

String wNum = weightNum();
        String wData = "";
        if(null != wNum){
            String str = wNum.substring(wNum.indexOf("=")+2,wNum.indexOf("=")+8);
            wData = Integer.valueOf(new StringBuffer(str).reverse().toString()).toString();
        }

直接得到的地磅读数是反的。如1000,会显示0001

需要反转后使用。

 

转载于:https://my.oschina.net/wardrobe/blog/751062

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值