這次使用Arduino UNO + RS485 的模組,來實現Modbus Slave 的通訊
Pin Name | Pin Description |
VCC | 5V |
A | Non-inverting Receiver Input Non-Inverting Driver Output |
B | Inverting Receiver Input Inverting Driver Output |
GND | GND (0V) |
R0 | Receiver Out (RX pin) |
RE | Receiver Output (LOW-Enable) |
DE | Driver Output (HIGH-Enable) |
DI | Driver Input (TX pin) |
接線圖
Arduino UNO | MAX-485 TTL to RS-485 Converter Module |
0(RX) | RO |
1(TX) | DI |
4 | DE & RE |
+5V | VCC |
GND | GND |
#include<ModbusRtu.h>
//定義MAX485 TTL到RS-485轉換器模塊和Arduino UNO之間連接的引腳名稱。 #define TXEN 2 Modbus slave(1,Serial,TXEN); //初始化類ModbusMaster的節點對象,從站ID 1。
uint16_t au16data[100] = { 0 }; //宣告資料陣列 for Registers
void setup() {
//將波特率設置為9600
Serial.begin(9600);
slave.start(); //啟動Slave
}
void loop(){ slave.poll( au16data, 100); //帶入資料陣列, 陣列長度
au16data[10] = 1212; //Registers 40010 = 1212 au16data[11] = au16data[31]; //Registers 40011 = 40031 }