#include <ModbusRTUSlave.h>
#include <Servo.h>
#define POTENTIOMETER_ADDRESS 0x00
#define SERVO_ADDRESS 0x01
#define POTENTIOMETER_PIN A0
#define SERVO_PIN 9
ModbusRTUSlave modbus;
Servo servo;
int potValue = 0;
void setup() {
modbus.configure(9600, 1, 2, 3, 4); // Configure Modbus (baudrate, TX pin, RX pin, DERE pin, LED pin)
modbus.addHreg(POTENTIOMETER_ADDRESS); // Add Holding Register for potentiometer value
modbus.addHreg(SERVO_ADDRESS); // Add Holding Register for servo position
servo.attach(SERVO_PIN); // Attach servo to pin
}
void loop() {
modbus.task(); // Handle Modbus communication
// Read potentiometer value
int newPotValue = analogRead(POTENTIOMETER_PIN);
if (newPotValue != potValue) {
potValue = newPotValue;
modbus.Hreg(POTENTIOMETER_ADDRESS, potValue); // Update Modbus register with new potentiometer value
}
// Read servo position from Modbus register and set servo position
int servoPosition = modbus.Hreg(SERVO_ADDRESS);
servo.write(map(servoPosition, 0, 65535, 0, 180)); // Map Modbus register value to servo position
}