Dear all:
I am trying to use some function I downloaded from the internet to connect to a modbus meter, the connection is fine, but when I try to read the data off the registers, it kept returning -1, reading unsuccessful
Code:int readState = modbus_read_holding_registers(2, 0, 2, mbusRegisters);
Meter register map:
Address word Item(description) Code Unit Sign 0000H 2 Watt Hour 03H WH Unsigned 0002H 1 Watt 03H W Unsigned 0003H 1 Voltage 03H V Unsigned 0004H 1 Currant 03H A Unsigned
Below is the source code of the function I used (open source) :
(from Modbus master C library/code for Linux serial device)
Am I using the function wrong, or it's a modbus thing?Code:int modbus_read_holding_registers(unsigned char slave_id, unsigned char start_address, unsigned int num_registers, unsigned short * modbus_registers) { unsigned char transmit[255]; //check return values unsigned char *retValue; int i; retValue = transmit; transmit[0] = slave_id; // printf("slave_id: %c", transmit[0]); transmit[1] = MB_READ_HOLDING_REGISTERS; transmit[2] = start_address >> 8; transmit[3] = start_address & 0xFF; transmit[4] = num_registers >> 8; transmit[5] = num_registers & 0xFF; short crc = CRC16(transmit, 6); transmit[6] = crc; transmit[7] = crc >> 8; for (i=0; i<8; i++) { printf("return value [%d] = %x\n", i, *(retValue+i)); } if (write(fd, transmit, 8) == -1) { perror("Unable to write to serial device"); mb_datagram_status = MB_ERROR; return -1; } mb_waiting_for_reply = 1; struct timespec time; clock_gettime(CLOCK_REALTIME, &time); time.tv_sec += 1; /* Time out here if no bytes have been received within the time out period */ if (pthread_cond_timedwait(&datagram_start_receiving, &waiting_for_reply, &time) == ETIMEDOUT) { mb_datagram_status = MB_TIMEOUT; timeout_error_count++; return -1; } printf("after pthread_cond_timedwait()\n"); pthread_cond_wait(&datagram_finished_receiving, &waiting_for_reply); mb_waiting_for_reply = 0; if (mb_datagram_status == MB_OK) { unsigned char byte_count = modbus_read_num_bytes(datagram); mb_datagram_status = MB_OK; unsigned char * datagram_data = datagram + 3; int i; for(i = 0; i < byte_count / 2; i++) { modbus_registers[i] = datagram_data[i * 2] << 8 | datagram_data[i * 2 + 1]; } return byte_count / 2; } else { return mb_datagram_status; } }
Any help is appreciated, thanks.
barramundi9



LinkBack URL
About LinkBacks



