⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 readserial.java.bak

📁 用java实现串口通信 用java实现串口通信
💻 BAK
字号:
package communication;
import java.io.*;
/**
* This class reads message from the specific serial port and save
* the message to the serial buffer.
*/
//如何单独编译此文件,因为private中有别的类SerialBuffer???????????????


class SerialBuffer
{
	private String Content = "";
	private String CurrentMsg, TempContent;
	private boolean available = false;
	private int LengthAlready =0;
/**
* This function returns a string with a certain length from the incomin
* messages.
* @param Length The length of the string to be returned.读取length个字符 赋给Msg
*/
	public synchronized String GetMsg()
	{
		//LengthNeeded = Length;
		//if (LengthNeeded > Content.length())
		//{
			available = false;
			while (available == false)
			{
				//try
				//{
					//wait();
					for(int i=0;i<30000000;++i)//<20000000出现乱码!!!!!!!!!!!!!!!!!不稳定!!随着进程数而变化!!
						;
					//break;
				//} catch (InterruptedException e) {System.out.println("SerialBuffer.GetMsg() is not waiting"); }
			}
		//}
		CurrentMsg = Content.substring(0,LengthAlready);
	TempContent = Content.substring(LengthAlready);
	//str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str;
	//str=str.substring(int beginIndex,int endIndex);截取str中从beginIndex开始至endIndex-1结束时的字符串,并将其赋值给str;

	Content = "";
	LengthAlready = 0;
	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());
		System.out.println(d);
		++LengthAlready;
		//System.out.println(LengthAlready);
		//收到回车符,表一段信息提取完毕,这时才能读出该信息
		if (c==0x0d)
		{
		available = true;//修改available,V,P标志(操作系统,控制并发)
		//System.out.println("true");
		}
		notifyAll();
	}
}




public class ReadSerial extends Thread
{
	private SerialBuffer ComBuffer;//ComBuffer是存储串口传来数据的缓冲区!!!!
	private InputStream inPort;
/**
* 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;
	inPort = Port;
	}
	public void run()
	{
	int c;
	try
	{
		while (true)
		{
			c = inPort.read();//读完inPort的一段内容后,会不会有等待?等待
			//System.out.println((char)c);
			ComBuffer.PutChar(c);//InputStream中的内容
			//System.out.println((char)c);
		}
	} catch (IOException e) {}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -