As the title mentioned, I am looking for a way to read and write a coils in arduino with Modbus
#include <modbus.h>
#include <modbusDevice.h>
#include <modbusRegBank.h>
#include <modbusSlave.h>
#define RS485TxEnablePin 8
#define RS485Baud 9600
#define RS485Format SERIAL_8N2
modbusDevice regBank;
modbusSlave slave;
int LEDpin = 3;
int buttonPin = 2;
int brightness = 0;
int buttonValue = 0;
int dutyCycle = 0;
void setup() {
pinMode(LEDpin,OUTPUT);
pinMode(buttonPin,INPUT);
regBank.setId(1);
regBank.add(40001);
slave._device = ®Bank;
slave.setBaud(&Serial,RS485Baud,RS485Format,RS485TxEnablePin);
Serial.flush();
}
void loop() {
dutyCycle = regBank.get(40001);
buttonValue = digitalRead(buttonPin);
if(buttonValue == HIGH){
analogWrite(LEDpin,255);
delay(10000);
}
analogWrite(LEDpin,dutyCycle);
slave.run();
}
I have try to use another code to read coil but the result show as below :
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
import time
scale = ModbusClient(method='rtu', port='/dev/ttyUSB0', parity='N', baudrate=9600, bytesize=8, stopbits=2, timeout=1)
connection = scale.connect()
scale.write_coil(0, True, unit=1)
time.sleep(1)
rr = scale.read_coils(0, 8, unit=1)
print(rr.bits)
Output:
[False, False, False, False, False, False, False, False]
Anyone have any suggestion? Thank you~