I decide to rewrite the code and the following is what I have done:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h> //set baud rate
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#define device "/dev/ttyUSB0"
#define MyBaudRate 9600
#define rec_buf_wait_2s 2
int read_data_tty (int fd, char *rec_buf, int rec_wait) {
int retval;
fd_set rfds;
struct timeval tv;
int ret, pos;
tv.tv_sec = rec_wait;
tv.tv_usec = 0;
pos = 0;
while (1) {
FD_ZERO (&rfds);
FD_SET (fd, &rfds);
retval = select (fd+1, &rfds, NULL, NULL, &tv);
if (retval == -1) {
perror("select()");
break;
} else if (retval) {
ret = read(fd, rec_buf+pos, 2048);
pos += ret;
if (rec_buf[pos-2] == '\r' && rec_buf[pos-1] == '\n') {
FD_ZERO (&rfds);
FD_SET (fd, &rfds);
retval = select (fd+1, &rfds, NULL, NULL, &tv);
if (!retval) {
break;
}
}
} else {
break;
}
}
return 1;
}
int device_485_receive (int fd) {
ssize_t ret;
char rec_buf[1024];
int i;
char *send_buf = "02030202f925";
for (i=0; i<10; i++) {
ret = write (fd, send_buf, strlen(send_buf));
if (ret == -1) {
printf("write device %s error\n", device);
return -1;
}
if (read_data_tty(fd, rec_buf, rec_buf_wait_2s)) {
printf("%s\n", rec_buf);
} else {
printf("read_error\n");
}
//if ((read(fd, rec_buf, strlen(rec_buf))) == -1) {
// printf("error reading string\n");
// return -1;
//} else {
// printf("%s\n", rec_buf);
}
return 0;
}
int main () {
int fd;
//open serial port
fd = open (device, O_RDWR);
//check if device opened properly
if (fd == -1) {
printf("open device %s error\n", device);
} else {
//set baudrate
struct termios options;
cfsetispeed (&options, MyBaudRate);
cfsetospeed (&options, MyBaudRate);
device_485_receive(fd);
}
if (close(fd) != 0) {
printf("close device error\n");
}
return 0;
}
the send_buf string "02 03 02 02 f9 25" (space included here for clarity)is the modbus command, 02 is the slave id, 03 is function code, the following 02 is the starting address and 02 means 2 registers are to be read and f9 25 are the crc values.
When I execute the program, it keeps returning the value 4, any ideas???
Thanks.
barramundi9
Originally Posted by
barramundi9
Hi, Salem, thanks for the reply, I know it's been a month ...
It was me and I did try swapping the crc bytes but it still returns -1
And I did called modbus_init() first and it was connected, it dies at
Code:
if (pthread_cond_timedwait(&datagram_start_receiving, &waiting_for_reply, &time) == ETIMEDOUT) {
mb_datagram_status = MB_TIMEOUT;
timeout_error_count++;
return -1;
}
Any ideas?
Thanks