• 大小: 5KB
    文件类型: .java
    金币: 1
    下载: 0 次
    发布日期: 2021-05-10
  • 语言: Java
  • 标签: rs232  温湿度  传感器  

资源简介

从串口读取传感器采集到的温湿度数据,然后存入数据库,代码可以运行我采集成功了

资源截图

代码片段和文件信息


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

评论

共有 条评论