Arduino Modbus测试
接线:
LED :13
Modbus串口:0 1
按键:8
项目-》加载库-》管理库:搜索安装ArduinoModbus、ArduinoRS485两个库文件
打开modbusrtuserverled 烧录
#include
#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
连接
Setup下的功能全都不要为勾选
点击functions-》write single coil 对灯进行控制
点on或者off 然后点send
Address为0控制13管脚对应的灯
Uno主 pc slave测试
效果:按键-》灯亮-》发送数据到PC,slave软件界面变化对M
#include
#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]