資源簡介
從串口讀取傳感器采集到的溫濕度數據,然后存入數據庫,代碼可以運行我采集成功了
代碼片段和文件信息
import?java.io.*;
import?java.util.*;
import?javax.comm.*;
import?java.util.ArrayList;
import?java.sql.*;
public?class?SimpleRead?implements?Runnable?SerialPortEventListener?{
????static?CommPortIdentifier?portId;
????static?Enumeration ??????portList;
????InputStream ??????inputStream;
????SerialPort ??????serialPort;
????Thread ??????readThread;
????SensorNode?sn;
int?flag;
int?id;
String??i;
static?Statement?stmt;
static?double?tmaxhmax;
????public?static?void?main(String[]?args)?{
????boolean ??????portFound?=?false;
????String ??????defaultPort?=?“COM1“;
? if?(args.length?>?0)?{
????defaultPort?=?args[0];
}?
portList?=?CommPortIdentifier.getPortIdentifiers();
while?(portList.hasMoreElements())?{
????portId?=?(CommPortIdentifier)?portList.nextElement();
????if?(portId.getPortType()?==?CommPortIdentifier.PORT_SERIAL)?{
if?(portId.getName().equals(defaultPort))?{
????System.out.println(“Found?port:?“+defaultPort);
????portFound?=?true;
????SimpleRead?reader?=?new?SimpleRead();
}?
????}?
}?
if?(!portFound)?{
????System.out.println(“port?“?+?defaultPort?+?“?not?found.“);
}?
?
????}?
????
????public?SimpleRead()?{
???? flag=0;
???? sn=new?SensorNode();
try?{
????serialPort?=?(SerialPort)?portId.open(“SimpleReadApp“?2000);
}?catch?(PortInUseException?e)?{}
try?{
????inputStream?=?serialPort.getInputStream();
}?catch?(IOException?e)?{}
try?{
????serialPort.addEventListener(this);
}?catch?(TooManyListenersException?e)?{}
serialPort.notifyondataavailable(true);
try?{
????serialPort.setSerialPortParams(9600?SerialPort.DATABITS_8?
???SerialPort.STOPBITS_1?
???SerialPort.PARITY_NONE);
}?catch?(UnsupportedCommOperationException?e)?{}
readThread?=?new?Thread(this);
readThread.start();
}
???
????public?void?run()?{
try?{
????Thread.sleep(20000);
}?catch?(InterruptedException?e)?{}
????}?
????
????public?void?serialEvent(SerialPortEvent?event)?{
switch?(event.getEventType())?{
case?SerialPortEvent.BI:
case?SerialPortEvent.OE:
case?SerialPortEvent.FE:
case?SerialPortEvent.PE:
case?SerialPortEvent.CD:
case?SerialPortEvent.CTS:
case?SerialPortEvent.DSR:
case?SerialPortEvent.RI:
case?SerialPortEvent.OUTPUT_BUFFER_EMPTY:
????break;
case?SerialPortEvent.DATA_AVAILABLE:
????byte[]?readBuffer?=?new?byte[20];
????String?ts=new?String();
????try?{
while?(inputStream.available()?>?0)?{
????int?numBytes?=?inputStream.read(readBuffer);
????ts=ts+toHex(readBuffernumBytes);
????
?}
?if(flag==0){
? if(ts.startsWith(“37“)){
? flag=1;
? sn.clearAll();
? sn.setType(swap(ts.sub
- 上一篇:基于P2P的局域網即時通信系統 java實現源碼
- 下一篇:文件輸出與讀入
評論
共有 條評論