- 21
- 0
- 约4.96千字
- 约 6页
- 2018-01-04 发布于河南
- 举报
基于java的zigbee串口通讯的多线程
import gnu.io.CommPortIdentifier;import gnu.io.PortInUseException;import gnu.io.SerialPort;import java.io.BufferedInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.concurrent.CountDownLatch;import com.serotonin.io.serial.SerialParameters;public class SerialCommcation implements Runnable{//对象的声明private String result=;static SerialPort serialPort;static OutputStream out;static InputStream in;String portName = null;private static int portID=2;private float airtemperature;private float airhumidity;private float soiltemperature;private float soilmoisture;private float windvelocity;private double rainfall;private Thread myThread;@Overridepublic void run() {// TODO Auto-generated method stub}public SerialCommcation(){portName = COM+portID; SerialParameters serialParameters = new SerialParameters(); System.out.println(系统应用的端口为: + portName); //设定通讯的串行口 serialParameters.setCommPortId(portName);//设定成无奇偶校验serialParameters.setParity(0);//设定数据位是8位serialParameters.setDataBits(8);//设定一个停止位serialParameters.setStopBits(1);serialParameters.setPortOwnerName(Numb nuts);//串行口上的波特率serialParameters.setBaudRate(9600);myThread = new Thread(){public void run() {while (true) { update(); closeSer(); try { sleep(1);}catch (InterruptedException e) {// TODO Auto-generated catch block//e.printStackTrace();System.out.println(InterruptedException+e);}}}};myThread.start();}//读取串口数据private synchronized void update(){// TODO Auto-generated method stubtry {try{Enumeration? portList = CommPortIdentifier.getPortIdentifiers();CommPortIdentifier portId = null;while(portList.hasMoreElements()){portId = (CommPortIdentifier) portList.nextElement();if (portId.getName().equalsIgnoreCase(COM2)){serialPort = (SerialPort) portId.open(,2000); //open方法打开通讯端口,得到一个CommPort对象,它使程序独占端口//System.out.print(serialPort); } }}catch (PortInUseException e) {// TODO: handle exceptionSystem.out.println(PortInUseException+e);}//用字节输入流in调用read()
原创力文档

文档评论(0)