Arduino Modbus测试 Modbus poll Modbus slave

Arduino Modbus测试

硬件连接

接线:
LED :13
Modbus串口:0 1
按键:8

灯和按键接法:
Arduino Modbus测试 Modbus poll Modbus slave_第1张图片

库安装

项目-》加载库-》管理库:搜索安装ArduinoModbus、ArduinoRS485两个库文件

测试灯

打开modbusrtuserverled 烧录
#include // ArduinoModbus depends on the ArduinoRS485 library
#include

const int ledPin1 = 13;

void setup() {
Serial.begin(9600);

Serial.println(“Modbus RTU Server LED”);

// start the Modbus RTU server, with (slave) id 1
if (!ModbusRTUServer.begin(1, 9600)) {
Serial.println(“Failed to start Modbus RTU Server!”);
while (1);
}

// configure the LED
pinMode(ledPin1, OUTPUT);
digitalWrite(ledPin1, LOW);

// configure a single coil at address 0x00
ModbusRTUServer.configureCoils(0x00, 1);
}

void loop() {
// poll for Modbus RTU requests
ModbusRTUServer.poll();

// read the current value of the coil
int coilValue1 = ModbusRTUServer.coilRead(0x00);

if (coilValue1) {
// coil value set, turn LED on
digitalWrite(ledPin1, HIGH);
} else {
// coild value clear, turn LED off
digitalWrite(ledPin1, LOW);
}

}

打开mosbus poll
连接
Arduino Modbus测试 Modbus poll Modbus slave_第2张图片
Setup下的功能全都不要为勾选
Arduino Modbus测试 Modbus poll Modbus slave_第3张图片
点击functions-》write single coil 对灯进行控制
点on或者off 然后点send
Address为0控制13管脚对应的灯
Arduino Modbus测试 Modbus poll Modbus slave_第4张图片
Arduino Modbus测试 Modbus poll Modbus slave_第5张图片

测试按键

Uno主 pc slave测试

效果:按键-》灯亮-》发送数据到PC,slave软件界面变化对M
Arduino Modbus测试 Modbus poll Modbus slave_第6张图片

Arduino Modbus测试 Modbus poll Modbus slave_第7张图片

#include // ArduinoModbus depends on the ArduinoRS485 library
#include

const int ledPin1 = 13;
const int key = 10;
boolean ledstate=0;

void setup() {
Serial.begin(9600);
while (!Serial);

Serial.println(“Modbus RTU Client Toggle”);

// start the Modbus RTU client
if (!ModbusRTUClient.begin(9600)) {
Serial.println(“Failed to start Modbus RTU Client!”);
while (1);
}
pinMode(ledPin1,OUTPUT);
pinMode(key,INPUT_PULLUP);

digitalWrite(ledPin1,0);
}

void loop() {

if(digitalRead(key)==0)
{
delay(20);
if(digitalRead(key)==0)
{
ledstate = !ledstate;
//led状态变化
digitalWrite(ledPin1,ledstate);

  //发送led状态到PC端modbus slave软件
  // for (slave) id 1: write the value of 0x01, to the coil at address 0x00 
  if (!ModbusRTUClient.coilWrite(1, 0x00, ledstate)) {
    Serial.print("Failed to write coil! ");
    Serial.println(ModbusRTUClient.lastError());
  }
  while(digitalRead(key)==0);
}

}
/if (!ModbusRTUClient.coilWrite(1, 0x00, 0x01)) {
Serial.print("Failed to write coil! ");
Serial.println(ModbusRTUClient.lastError());
}
delay(1000);
if (!ModbusRTUClient.coilWrite(1, 0x00, 0x00)) {
Serial.print("Failed to write coil! ");
Serial.println(ModbusRTUClient.lastError());
}
delay(1000);
/
}

my email:
[email protected]

你可能感兴趣的:(开源硬件)