简言
在 Modbus RTU 通信中,主机(Master)指的是发起请求并控制通信的设备,而 从机(Slave)是响应请求并提供数据的设备。
接线图
TTL to RS485
- TX(TTL485)→ RX(Arduino Nano)
- RX(TTL485)→ TX(Arduino Nano)
- GND(TTL485)→ GND(Arduino Nano)
- VCC(TTL485)→ 5V(Arduino Nano)
- A(TTL485)→ A+(RS485 通信线路)
- B(TTL485)→ B-(RS485 通信线路)
为什么转换?: 如果不转换直接用TTL去连接主站可能会因为线太长度影响到信号传输不稳定情况
代码
开源库地址https://github.com/arduino-libraries/ArduinoModbus/tree/master
#include <ArduinoRS485.h> // ArduinoModbus depends on the ArduinoRS485 library
#include <ArduinoModbus.h>
const int numRegs = 10;
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("Modbus RTU Server Kitchen Sink");
// start the Modbus RTU server, with (slave) id 42
if (!ModbusRTUServer.begin(42, 9600)) {
Serial.println("Failed to start Modbus RTU Server!");
while (1);
}
// configure coils at address 0x00
ModbusRTUServer.configureCoils(0x00, numRegs);
// configure discrete inputs at address 0x00
ModbusRTUServer.configureDiscreteInputs(0x00, numRegs);
// configure holding registers at address 0x00
ModbusRTUServer.configureHoldingRegisters(0x00, numRegs);
// configure input registers at address 0x00
ModbusRTUServer.configureInputRegisters(0x00, numRegs);
}
void loop() {
for (int i = 0; i < 10; i++) {
ModbusRTUServer.coilWrite(i,0x01);
int randomHoldingValue = random(0, 1000);
ModbusRTUServer.holdingRegisterWrite(i, randomHoldingValue);
int randomInputValue = random(0, 355);
ModbusRTUServer.inputRegisterWrite(i, randomInputValue);
bool randomDiscreteValue = random(0, 2);
ModbusRTUServer.discreteInputWrite(i, randomDiscreteValue);
}
// poll for Modbus RTU requests
ModbusRTUServer.poll();
delay(1000);
}