smarmengol / Modbus-Master-Slave-for-Arduino

Modbus Master-Slave library for Arduino
GNU Lesser General Public License v2.1
473 stars 328 forks source link

I can´t read data with FC03 function #36

Closed JoaquinElvirasoft closed 5 years ago

JoaquinElvirasoft commented 6 years ago

Hi,

I have an arduino MEGA and i implementing your library as master R485. I don´t have problems to write data to my device... but i can´t read data... here is my code.. please help me.

include

uint16_t au16data[16]; //!< data array for modbus network sharing uint8_t u8state; //!< machine state uint8_t u8query; //!< pointer to message query

/* Modbus object declaration u8id : node id = 0 for master, = 1..247 for slave u8serno : serial port (use 0 for Serial) u8txenpin : 0 for RS-232 and USB-FTDI or any pin number > 1 for RS-485 / Modbus master(0, 1, 2); // this is master and RS-232 or USB-FTDI

/* This is an structe which contains a query to an slave device / modbus_t telegram[2];

unsigned long u32wait;

void setup() { // telegram 0: read registers telegram[0].u8id = 1; // slave address telegram[0].u8fct = 3; // function code (this one is registers read) telegram[0].u16RegAdd = 680;// start address in slave telegram[0].u16CoilsNo = 2; // number of elements (coils or registers) to read telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

// telegram 1: write a single register telegram[1].u8id = 1; // slave address telegram[1].u8fct = 16; // function code (this one is write a single register) telegram[1].u16RegAdd = 682; // start address in slave telegram[1].u16CoilsNo = 2; // number of elements (coils or registers) to write telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino*/

master.begin( 38400 ); // baud-rate at 19200 master.setTimeOut( 5000 ); // if there is no answer in 5000 ms, roll over u32wait = millis() + 1000; //polling cada 1 segundo u8state = u8query = 0;

Serial.begin(19200); Serial.setTimeout(1000);

pinMode(12,OUTPUT); pinMode(13,OUTPUT);

}

void loop() { int i; switch ( u8state ) { case 0: if (millis() > u32wait) u8state++; // wait state digitalWrite(13,LOW); break; case 1: master.query( telegram[u8query] ); // send query (only once) u8state++; u8query++; if (u8query > 2) u8query = 0; break; case 2: master.poll(); // check incoming messages if (master.getState() == COM_IDLE) {

    Serial.println("POLLING...");
    Serial.print("STATE:");
    Serial.println(master.getState());
    Serial.print("ERROR:");
    Serial.println(master.getLastError());
    Serial.print("DATA READ:");
    for (i=0;i<2;i++)
      Serial.print(au16data[i]);
    Serial.println("");
    if (bitRead(au16data[0],12)==1){
      digitalWrite(13,HIGH);
      delay(1000);  
    }

    u32wait = millis() + 1000;
    u8state = 0;
  }
  break;

}

/ else digitalWrite(12,LOW);/

au16data[4] = 7; au16data[5] = analogRead( 0 )*16.117; //