public class SimpleCommIO implements Runnable {
static CommPortIdentifier portId;
static String cmdHand = "I\r\n";
static String cmdWeight = "WX\r\n";
static SerialPort serialPort;
static OutputStream outputStream;
static String comm="COM11";
InputStream inputStream;
Thread readThread;
public void run() {
while (true) {
try {
byte[] readBuffer = new byte[200];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
System.out.print("收到数据:"+new String(readBuffer));
}
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void initComm() {
try{
portId = CommPortIdentifier.getPortIdentifier(comm);
serialPort = (SerialPort) portId.open("SimpleCommIO",2000);
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}catch(Exception e){
e.printStackTrace();
}
}
public void writeComm(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SimpleCommIO reader = new SimpleCommIO();
reader.initComm();
Thread readThread = new Thread(reader);
readThread.start();
System.out.println("发出指令:"+cmdHand);
reader.writeComm(cmdHand);
//暂停一会儿
try {
Thread.sleep ( 2000 ) ;
} catch (InterruptedException ie)
{
}
System.out.println("发出指令:"+cmdWeight);
reader.writeComm(cmdWeight);
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。