java串口编程案例代码
xiaopingtou 2022-05-20

1. SerialBean


SerialBean是本类库与其他应用程序的接口。该类库中定义了SerialBean的构造方法以及初始化串口,从串口读取数据,往串口写入数据以及关闭串口的函数。具体介绍如下:

public SerialBean(int PortID)
本函数构造一个指向特定串口的SerialBean,该串口由参数PortID所指定。PortID = 1 表示COM1,PortID = 2 表示COM2,由此类推。

public int Initialize()
本函数初始化所指定的串口并返回初始化结果。如果初始化成功返回1,否则返回-1。初始化的结果是该串口被SerialBean独占性使用,其参数被设置为9600, N, 8, 1。如果串口被成功初始化,则打开一个进程读取从串口传入的数据并将其保存在缓冲区中。

public String ReadPort(int Length)
本函数从串口(缓冲区)中读取指定长度的一个字符串。参数Length指定所返回字符串的长度。

public void WritePort(String Msg)
本函数向串口发送一个字符串。参数Msg是需要发送的字符串。

public void ClosePort()


本函数停止串口检测进程并关闭串口。


package serial;
import java.io.*;
import java.util.*;
import javax.comm.*;
/**
*
* This bean provides some basic functions to implement full dulplex
* information exchange through the srial port.
*
*/
public class SerialBean
{
static String PortName;
CommPortIdentifier portId;
SerialPort serialPort;
static OutputStream out;
static InputStream  in;
SerialBuffer SB;
ReadSerial   RT;
/**
*
* Constructor
*
* @param PortID the ID of the serial to be used. 1 for COM1,
* 2 for COM2, etc.
*
*/
public SerialBean(int PortID)
{
PortName = "COM" + PortID;
}
/**
*
* This function initialize the serial port for communication. It startss a
* thread which consistently monitors the serial port. Any signal capturred
* from the serial port is stored into a buffer area.
*
*/
public int Initialize()
{
int InitSuccess = 1;
int InitFail    = -1;
try
{
portId = CommPortIdentifier.getPortIdentifier(PortName);
try
{
serialPort = (SerialPort)
portId.open("Serial_Communication", 2000);
} catch (PortInUseException e)
{
return InitFail;
}
//Use InputStream in to read from the serial port, and OutputStream
//out to write to the serial port.
try
{
in  = serialPort.getInputStream();
out = serialPort.getOutputStream();
} catch (IOException e)
{
return InitFail;
}
//Initialize the communication parameters to 9600, 8, 1, none.
try
{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e)
{
return InitFail;
}
} catch (NoSuchPortException e)
{
return InitFail;
}
// when successfully open the serial port,  create a new serial buffer,
// then create a thread that consistently accepts incoming signals from
// the serial port. Incoming signals are stored in the serial buffer.
SB = new SerialBuffer();
RT = new ReadSerial(SB, in);
RT.start();
// return success information
return InitSuccess;
}
/**
*
* This function returns a string with a certain length from the incomin
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public String ReadPort(int Length)
{
String Msg;
Msg = SB.GetMsg(Length);
return Msg;
}
/**
*
* This function sends a message through the serial port.
*
* @param Msg The string to be sent.
*
*/
public void WritePort(String Msg)
{
int c;
try
{
for (int i = 0; i            out.write(Msg.charAt(i));
} catch (IOException e)  {}
}
/**
*
* This function closes the serial port in use.
*
*/
public void ClosePort()
{
RT.stop();
serialPort.close();
}

}


2. SerialBuffer

SerialBuffer是本类库中所定义的串口缓冲区,它定义了往该缓冲区中写入数据和从该缓冲区中读取数据所需要的函数。

public synchronized String GetMsg(int Length)
本函数从串口(缓冲区)中读取指定长度的一个字符串。参数Length指定所返回字符串的长度。

public synchronized void PutChar(int c)
本函数望串口缓冲区中写入一个字符,参数c 是需要写入的字符。

在往缓冲区写入数据或者是从缓冲区读取数据的时候,必须保证数据的同步,因此GetMsg和PutChar函数均被声明为synchronized并在具体实现中采取措施实现的数据的同步。
package serial;
/**
*
* This class implements the buffer area to store incoming data from the serial
* port.
*
*/
public class SerialBuffer
{
private String Content = "";
private String CurrentMsg, TempContent;
private boolean available = false;
private int LengthNeeded = 1;
/**
*
* This function returns a string with a certain length from the incomin
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public synchronized String GetMsg(int Length)
{
LengthNeeded = Length;
notifyAll();
if (LengthNeeded > Content.length())
{
available = false;
while (available == false)
{
try
{
wait();
} catch (InterruptedException e) { }
}
}
CurrentMsg  = Content.substring(0, LengthNeeded);
TempContent = Content.substring(LengthNeeded);
Content = TempContent;
LengthNeeded = 1;
notifyAll();
return CurrentMsg;
}
/**
*
* This function stores a character captured from the serial port to the
* buffer area.
*
* @param t The char value of the character to be stored.
*
*/
public synchronized void PutChar(int c)
{
Character d = new Character((char) c);
Content = Content.concat(d.toString());
if (LengthNeeded      {
available = true;
}
notifyAll();
}

}


3. ReadSerial


ReadSerial是一个进程,它不断的从指定的串口读取数据并将其存放到缓冲区中。

public ReadSerial(SerialBuffer SB, InputStream Port)
本函数构造一个ReadSerial进程,参数SB指定存放传入数据的缓冲区,参数Port指定从串口所接收的数据流。

public void run()
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) {}
}
}


4. SerialExample


SerialExample是本类库所提供的一个例程。它所实现的功能是打开串口COM1,
对其进行初始化,从串口读取信息对其进行处理后将处理结果发送到串口。
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      {
Msg = SB.ReadPort(i);
SB.WritePort("Reply: " + Msg);
}
SB.ClosePort();
}
}


本类库中使用了Java Communication API (javax.comm)。这是一个Java扩展类库,并不包括在标准的Java SDK当中。如果你尚未安装这个扩展类库的话,你应该从Sun公司的Java站点下载这个类库并将其安装在你的系统上。在所下载的包里面包括一个安装说明,如果你没有正确安装这个类库及其运行环境的话,运行这个程序的时候你会找不到串口。


正确安装Java Communication API并将上述程序编译通过以后,你可以按如下方法测试这个程序。如果你只有一台机器,你可以利用一条RS-232电缆将COM1和COM2连接起来,在COM1上运行SerialExample,在COM2上运行Windows提供的超级终端程序。如果你有两台机器的话,你可以利用一条RS-232电缆将两台机器的COM1(或者是COM2)连接起来,在一端运行例程,另外一端运行Windows提供的超级终端程序。如果有必要的话,可以对SerialExample中所声明的串口进行相应改动。本程序在Windows 2000 + Java SDK 1.3环境下编译通过并成功运行。
声明: 本文转载自其它媒体或授权刊载,目的在于信息传递,并不代表本站赞同其观点和对其真实性负责,如有新闻稿件和图片作品的内容、版权以及其它问题的,请联系我们及时删除。(联系我们,邮箱:evan.li@aspencore.com )
0
评论
  • 【7.24 深圳】2025国际AI+IoT生态发展大会/2025全球 MCU及嵌入式技术论坛


  • 相关技术文库
  • C语言
  • 编程
  • 软件开发
  • 程序
  • 光立方程序编写步骤

    基于51单片机的4*4*4光立方程序实现原理及程序代码。LED光立方的复位电路、时钟电路、每层LED灯电路控制逻辑,系统总原理图,工作流程及相关C语言源码实现。希望能够对你学习了解LED光立方程序编写及LED立方实体制...

    07-04
  • 封装继承多态

    封装: 封装是实现面向对象程序设计的第一步,封装就是将数据或函数等集合在一个个的单元中(我们称之为类)。被封装的对象通常被称为抽象数据类型。 封装的意义: 封装的意义在于保护或者防止代码(数据)被我们无意中...

    07-04
  • 封装是什么意思?

    即隐藏对象的属性和实现细节,仅对外公开接口,控制在程序中属性的读和修改的访问级别;将抽象得到的数据和行为(或功能)相结合,形成一个有机的整体,也就是将数据与操作数据的源代码进行有机的结合,形成“类”,其中...

    07-04
  • 超声波模块测距51程序_单片机超声波测距c语言

    超声波检测原理 超声波测距的程序流程图 程序如下: //超声波模块程序 //超声波模块程序 //Trig = P2^0 //Echo = P3^2 #include #define uchar unsigned char #define uint unsigned int // void delay(uint z) {...

    07-01
  • 大佬带你看嵌入式系统,嵌入式系统该学习什么?

    嵌入式系统是当今的热门系统之一,在诸多领域,嵌入式系统都有所应用。为增进大家对嵌入式系统的认识,小编将为大家介绍嵌入式系统是一个什么样的专业,以及学习嵌入式系统该学习哪些内容。如果你对嵌入式系统具有...

    06-27
  • c51单片机编程要点总结

    c51单片机编程要点总结 1、头文件:#include (我用的是 STC 89C54RD+) 2、预定义:sbit LED = P1^0// 定义 P1 口的 0 位为 LED 注:“P1^0”这个写法,与 A51 不同(A51 是 P1.0),P1 是一组端口,端口号范围 0~7 注2...

    06-25
  • C语言基础知识点汇总

    总结C语言基础知识点

    06-23
  • Keil使用中的若干问题

      一、混合编程  1、模块内接口:  使用如下标志符:  #pragma asm  汇编语句  #pragma endasm  注意:如果在c51程序中使用了汇编语言,注意在keil编译器中需要激活Properties中的“Generate Assembler...

    06-23
  • ESP32-finsh

    esp32c2添加finsh实现了ping指令和AT指令解析

    06-13
  • 一文讲通C语言位域,快速掌握!

    在嵌入式系统的开发中,内存是最程序员非常需要关注的对象,尤其是MCU开发、网络协议解析、硬件寄存器操作等领域,能否对内存进行高效的利用和合理的管理,将直接影响程序的性能和硬件的稳定性。

    06-10
下载排行榜
更多
评测报告
更多
广告