0% found this document useful (0 votes)
6 views2 pages

Arduino RS485 Modbus Example Code

This document contains a code snippet for a Modbus device setup using an Arduino. It defines a register bank and a slave device, configures communication parameters, and manages digital and analog input/output registers. The loop function updates LED states based on register values and reads analog inputs to update the Modbus registers.

Uploaded by

Ngọc Thức
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Arduino RS485 Modbus Example Code

This document contains a code snippet for a Modbus device setup using an Arduino. It defines a register bank and a slave device, configures communication parameters, and manages digital and analog input/output registers. The loop function updates LED states based on register values and reads analog inputs to update the Modbus registers.

Uploaded by

Ngọc Thức
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <modbus.

h>
#include <modbusDevice.h>
#include <modbusRegBank.h>
#include <modbusSlave.h>
modbusDevice regBank;
modbusSlave slave;
#define RS485TxEnablePin 2 // Chân Control#define RS485Baud 9600
#define RS485Format SERIAL_8E1
#define LED1 11
#define LED2 12
void setup ()
{
//Assign the modbus device ID.
[Link](1);
// địa chỉ trạm là 1
/*
modbus registers follow the following format 00001-09999 Digital Outputs, A master device can
read and write to these registers10001-19999 Digital Inputs, A master device can only read the
values from theseregisters30001-39999 Analog Inputs, A master device can only read the values
from theseregisters40001-49999 Analog Outputs, A master device can read and write to these
registersAnalog values are 16 bit unsigned words stored with a range of 0-32767Digital values
are stored as bytes, a zero value is OFF and any nonzer value is ON*/
//Add Analog Input registers to the register bank
[Link](30001);
[Link](30002);
//Add Analog Output registers to the register bank
[Link](40001);
[Link](40002);
slave._device = &regBank;
[Link](&Serial,RS485Baud,RS485Format,RS485TxEnablePin);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);}
void loop()
{
digitalWrite(LED1, [Link](40001));
digitalWrite(LED2, [Link](40002));
//[Link](30001, (word) analogRead(A0)); //from 0 – 1023
[Link](30001, (word) 111); // ghi giá trị 111 vào thanh ghi MODBUS 30001
[Link](30002, (word) analogRead(A1)); //from 0 – 1023
[Link](40001, (word) 112); // ghi giá trị 112 vào thanh ghi MODBUS 40001
[Link]();}

You might also like