我正在尝试使用串行通信向微控制器发送命令,我可以编译并运行以下代码而没有任何错误,但是值没有写入寄存器。我做错了什么?
码
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 ,
答案 0 :(得分:3)
您正在发送字符串08050080FF008D4B
。您可能希望将它们作为 bytes 而不是字符串值发送。您要发送到设备的第一个字节是0
,其中十六进制为0x30
。根据您的字符串和命令的含义,您可能希望第一个字节为0x08
。
所以,这样的事情可能会奏效(请注意,如果不知道你正在做什么,我不能肯定地说):
byte[] bytes = new byte[]{ 0x08,0x05,0x00,(byte)0x80,(byte)0xFF,0x00,(byte)0x8D,(byte)0x4B };
//Later on in your code....
os.write( bytes );