Java串口编程学习2

编程入门 行业动态 更新时间:2024-10-10 05:23:15

Java<a href=https://www.elefans.com/category/jswz/34/1769224.html style=串口编程学习2"/>

Java串口编程学习2

如果读串口出现乱码,则:

1.可能是波特率设置不对

2.可能是数据编码格式不对

import gnu.io.*;import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;/*** Created by gbr on 13-12-12.*/class R_Frame extends Frame implements Runnable, ActionListener, SerialPortEventListener{static CommPortIdentifier portId;static Enumeration portList;InputStream inputStream;SerialPort serialPort;Thread readThread;String str = "";TextField out_message = new TextField("上面文本框显示接收到的数据");TextArea in_message = new TextArea();Button btnOpen = new Button("Open Comm");R_Frame(){super("串口接收数据");setSize(200, 200);setVisible(true);btnOpen.addActionListener(this);add(out_message, "South");add(in_message, "Center");add(btnOpen, "North");}public void actionPerformed(ActionEvent event){portList = CommPortIdentifier.getPortIdentifiers();while (portList.hasMoreElements()){portId = (CommPortIdentifier)portList.nextElement();if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){if (portId.getName().equals("COM8")){try{serialPort = (SerialPort)portId.open("ReadComm", 2000);out_message.setText("已经打开串口COM8,正在接收数据...");} catch (PortInUseException e) {out_message.setText("端口已被占用!");e.printStackTrace();}try{serialPort.addEventListener(this);}catch (TooManyListenersException e){out_message.setText("监听异常!");e.printStackTrace();}serialPort.notifyOnDataAvailable(true);}}}readThread = new Thread(this);readThread.start();}public void run(){try{Thread.sleep(20);}catch (InterruptedException e){e.printStackTrace();}}public void serialEvent(SerialPortEvent event){try{serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);}catch (UnsupportedCommOperationException e){e.printStackTrace();}byte[] readBuffer = new byte[200];try{inputStream = serialPort.getInputStream();}catch (IOException e){e.printStackTrace();}try{while (inputStream.available() > 0){int numBytes = inputStream.read(readBuffer);}str = new String(readBuffer);in_message.append( str + "\n" );}catch (IOException e){e.printStackTrace();}}
}public class ReadComm {public static void main( String[] args ){R_Frame R_win = new R_Frame();R_win.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);//super.windowClosing(e);
            }});R_win.pack();}
}

 

转载于:.html

更多推荐

Java串口编程学习2

本文发布于:2024-02-27 09:10:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1705982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:串口   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!