我正在尝试使用串行通信向微控制器发送命令,我可以编译并运行以下代码而没有任何错误,但值没有被写入寄存器。我究竟做错了什么?
代码
import java.io.*;
import javax.comm.*;
import net.wimpi.modbus.net.SerialConnection;
import net.wimpi.modbus.util.SerialParameters;
import java.util.*;
public class SerTest {
public static void main(String[] args) {
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
while (portIdentifiers.hasMoreElements())
{
CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
pid.getName().equals("COM4"))
{
portId = pid;
break;
}
}
if(portId == null)
{
System.err.println("Could not find serial port "); // + wantedPortName);
System.exit(1);
}
SerialPort port = null;
try {
port = (SerialPort) portId.open(
"name", // Name of the application asking for the port
10000 // Wait max. 10 sec. to acquire port
);
} catch(PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(1);
}
try {
port.setSerialPortParams(
9600 , SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_EVEN);
} catch (UnsupportedCommOperationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader is = null;
PrintStream os = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream: write-only");
is = null;
}
try {
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Actual data communication would happen here
os.print("08050080FF008D4B");
os.flush();
if (is != null)
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (os != null) os.close();
if (port != null) port.close();
}
}
我怀疑问题出在这一行
os.print("08050080FF008D4B");
这是向微控制器发送命令的正确方法吗?
命令的含义
08- Controller ID,
05- MODBUS function for coil writing,
0080- Address of a register where value is to be written,
FF00- Boolean value,
8D4B- CRC checksum ,