7/5/2024 4:05 AM | |
Joined: 7/5/2024 Last visit: 7/5/2024 Posts: 1 Rating: (0) |
I established communication between an ESP32 (acting as a Modbus master) and the Modsim32 software (acting as a Modbus slave) using the Modbus protocol. The components involved in this setup are:
I had write the code code . #include<ModbusMaster.h> // Define RS485 control pins #defineMODBUS_DIR_PIN4// DE & RE connected to GPIO 4 #defineMODBUS_RX_PIN16// RO (Receiver Output) to GPIO 16 #defineMODBUS_TX_PIN17// DI (Data Input) to GPIO 17 #defineMODBUS_BAUD9600// Baud rate for communication // Create ModbusMaster object ModbusMaster node; // Callback functions to control RS485 transceiver direction voidpreTransmission() { digitalWrite(MODBUS_DIR_PIN, HIGH); } voidpostTransmission() { digitalWrite(MODBUS_DIR_PIN, LOW); } voidsetup() { // Initialize serial communication Serial.begin(115200); // Initialize RS485 control pins pinMode(MODBUS_DIR_PIN, OUTPUT); digitalWrite(MODBUS_DIR_PIN, LOW); // Initialize Serial2 for RS485 Serial2.begin(MODBUS_BAUD, SERIAL_8N1, MODBUS_RX_PIN, MODBUS_TX_PIN); // Initialize Modbus communication with slave ID 1 node.begin(1, Serial2); // Set RS485 control callbacks node.preTransmission(preTransmission); node.postTransmission(postTransmission); } voidloop() { uint8_tresult; uint16_tdata[2]; Serial.println("Requesting data from slave..."); // Attempt to read 1 register from address 0x0000 result =node.readInputRegisters(0x0000,1); if(result ==node.ku8MBSuccess) { Serial.println("Success, received data:"); data[0] =node.getResponseBuffer(0x00);// Get the first register value Serial.println(data[0], HEX); }else{ Serial.print("Failed, Response Code: "); Serial.println(result, HEX); Serial.println("Possible reasons:"); if(result ==node.ku8MBIllegalFunction)Serial.println("Illegal function"); elseif(result ==node.ku8MBIllegalDataAddress)Serial.println("Illegal data address"); elseif(result ==node.ku8MBIllegalDataValue)Serial.println("Illegal data value"); elseif(result ==node.ku8MBSlaveDeviceFailure)Serial.println("Slave device failure"); elseif(result ==node.ku8MBInvalidSlaveID)Serial.println("Invalid slave ID"); elseif(result ==node.ku8MBInvalidFunction)Serial.println("Invalid function"); elseif(result ==node.ku8MBResponseTimedOut)Serial.println("Response timed out"); elseif(result ==node.ku8MBInvalidCRC)Serial.println("Invalid CRC"); } delay(3000);// Increased delay to 3 seconds } this is the code i have written.the code giving Response timed out .how to resolve this .i want to go into the IF condition.please help me. ------------------------------------------------------------------------------------------ |
Last edited by: Wit_Moderator at: 07/05/2024 14:01:36New subject after splitting |
|
Follow us on