上次已经为大家介绍过java中SerialBuffer的定义,今天再来为大家介绍一下java中的ReadSerial及SerialExample的具体内容,同样地,会用实际的代码为大家展示。
首先来看一下ReadSerial。它是一个进程,它不断的从指定的串口读取数据并将其存放到缓冲区中。内容如下:
1.public ReadSerial(SerialBuffer SB, InputStreamPort)
本函数构造一个ReadSerial进程,参数SB指定存放传入数据的缓冲区,参数Port指定从串口所接收的数据流。
2.public void run()
ReadSerial进程的主函数,它不断的从指定的串口读取数据并将其存放到缓冲区中。
然后再来看一下SerialExample。
SerialExample是本类库所提供的一个例程。它所实现的功能是打开串口COM1,对其进行初始化,从串口读取信息对其进行处理后将处理结果发送到串口。
接下来分别展示它们的源代码。
ReadSerial代码展示如下:
package serial; import java.io.*; /** * * This class reads message from the specific serial port and save * the message to the serial buffer. * */ public class ReadSerial extends Thread { private SerialBuffer ComBuffer; private InputStream ComPort; /** * * Constructor * * @param SB The buffer to save the incoming messages. * @param Port The InputStream from the specific serial port. * */ public ReadSerial(SerialBuffer SB, InputStream Port) { ComBuffer = SB; ComPort = Port; } public void run() { int c; try { while (true) { c = ComPort.read(); ComBuffer.PutChar(c); } } catch (IOException e) {} } }
SerialExample代码展示如下:
import serial.*; import java.io.*; /** * * This is an example of how to use the SerialBean. It opens COM1 and reads * six messages with different length form the serial port. * */ class SerialExample { public static void main(String[] args) { //TO DO: Add your JAVA codes here SerialBean SB = new SerialBean(1); String Msg; SB.Initialize(); for (int i = 5; i <= 10; i++) { Msg = SB.ReadPort(i); SB.WritePort("Reply: " + Msg); } SB.ClosePort(); } }
以上就是关于java中ReadSerial及SerialExample的详细介绍以及实际的代码展示。如果你对java知识感兴趣,想要了解更多java基础和常见问题,敬请关注奇Q工具网。
推荐阅读: