通过串口让普通的电路开关控制你的java程序
public class Demo { static SwitchControl control; private InputStream in; private OutputStream os; private SerialPort serialPort; boolean inited = false; boolean stoped = false; long beg = System.currentTimeMillis(); public boolean init() { if (inited) { return true; } try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1"); serialPort = (SerialPort) portId.open("SerialBean", 4000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setDTR(true); in = serialPort.getInputStream(); os = serialPort.getOutputStream(); inited = true; } catch (Exception e) { e.printStackTrace(); return false; } return true; } public void writePort(int s) { try { os.write(s); os.flush(); } catch (Exception e) { e.printStackTrace(); } } public void start() { Thread send = new Thread(new SendData()); Thread recive = new Thread(new ReceiveData()); send.start(); recive.start(); } public void close() { stoped = true; try { Thread.sleep(20); if (in != null) { in.close(); } if (os != null) { os.close(); } if (serialPort != null) serialPort.close(); } catch (Exception e) { e.printStackTrace(); } } class ReceiveData implements Runnable { public void run() { while (true) { if (stoped) { break; } byte[] b = new byte[10]; try { if (in.read(b) == 0) { continue; } long end = System.currentTimeMillis(); //处去噪声影响,通过连续两次接受到数据的时间差来判断是一次长时间的踩踏还是连续2次或者多次踩踏 if (end - beg > 20) { Thread tt = new Thread(new Task()); tt.start(); } Thread.sleep(10); beg = System.currentTimeMillis(); } catch (Exception e) { break; } } } } class SendData implements Runnable { public void run() { while (true) { if (stoped) { break; } writePort(0); try { Thread.sleep(5); } catch (Exception e) { e.printStackTrace(); break; } } } } class Task implements Runnable { public void run() { // 相关任务 System.out.println("捕捉到事件............."); } } public static void main(String[] args) { Demo demo = new Demo(); if (!demo.init()) { System.err.println("初始化串口失败!"); return; } demo.start(); }}?
?
1 楼 mlhorizon 2008-05-06 还是带点编码解码的好!!