ModbusMaster
ModbusMaster copied to clipboard
Modbus function 0x01 Read Coils is incorrect ?
#include <ModbusMaster.h>
ModbusMaster node;
#include <SoftwareSerial.h> SoftwareSerial MySerial(10,11);
void setup() {
Serial.begin(9600);
MySerial.begin(9600);
node.begin(1, Serial);
}
void loop() {
uint8_t j, result;
result = node.readCoils(0, 6);
if (result == node.ku8MBSuccess)
{
for (j = 0; j < 6; j++)
{
MySerial.println( node.getResponseBuffer(j));
}
}
}
My bug
- response incorrectly from coil 1 to .
Coil 1 desire is 1 but response is 2 Coil 2 desire is 1 but response is 4 Coil 3 desire is 1 but response is 9
- All response now only show in
node.getResponseBuffer(0) , someone can help me fix this?
- this is video my test
https://youtu.be/YTzsSAuBlP8
Hi, coils are individual bits, the first 16 are retrieved in first word (2 bytes, uint16_t), so setting coils 0 and 1 yelds 0b00000000 0b00000011, being 3 decimal, and then setting coil 2 then yelds 0b00000000 0b00000111, being 7 decimal https://en.wikipedia.org/wiki/Modbus#Function_code_1_(read_coils)and_function_code_2(read_discrete_inputs) /Per-Ake
Hi.....haidvams This is code for reading coil register and Multiple slave reading
Thank you...
Hope it's useful
#include <ModbusMaster.h> ModbusMaster node; static const uint8_t ku8MBReadCoils = 0x01; static uint8_t SlaveAddr1 = 1; //static uint8_t SlaveAddr2 = 2; //static uint8_t SlaveAddr3 = 3;
#include <SoftwareSerial.h> SoftwareSerial MySerial(D5, D6);
#define EN D1 #define MAX485_RE_NEG D2
#define LED_Status D4 float Reg1,Reg2;
uint16_t DO1,DO2,DO3,DO4; void preTransmission() { digitalWrite(EN, 1); digitalWrite(MAX485_RE_NEG, 1); }
void postTransmission() { digitalWrite(EN, 0); digitalWrite(MAX485_RE_NEG, 0); }
void setup() { pinMode(LED_Status,OUTPUT); pinMode(EN, OUTPUT); pinMode(MAX485_RE_NEG, OUTPUT); // Init in receive mode digitalWrite(MAX485_RE_NEG, 0); digitalWrite(EN, 0);
MySerial.begin(57600); // baudrate pzem Serial.begin(9600);
node.preTransmission(preTransmission); node.postTransmission(postTransmission);
}
void loop() { Read_Data1(SlaveAddr1); //Read_Data2(SlaveAddr2); //Read_Data3(laveAddr3);
}
void Read_Data1(byte addr){ Serial.print("baca pzem addr: "); Serial.println(addr);
node.begin(addr, MySerial); uint8_t result;
DO1 = node.readCoils(0, 1); Serial.print("Coils1: "); Serial.println(node.getResponseBuffer(DO1)); node.clearResponseBuffer();
DO2 = node.readCoils(1,1); Serial.print("Coils2: "); Serial.println(node.getResponseBuffer(DO2)); node.clearResponseBuffer();
DO3 = node.readCoils(2,1); Serial.print("Coils3: "); Serial.println(node.getResponseBuffer(DO3)); node.clearResponseBuffer();
DO4 = node.readCoils(3,1); Serial.print("Coils4: "); Serial.println(node.getResponseBuffer(DO3)); node.clearResponseBuffer();
delay(1000);// delay
}
void Read_Data2(byte addr){ //Add this code for reading register next slave addres copy from ( void Read_Data1) }