小白求助,在linux系统使用rs485进行控制,发现write函数每次返回值都为1,少于需要写入的字节数

rose0101 2019-04-16 05:15:14
在电脑端linux系统使用rs485进行控制,需要通过usb转485转换器向485串口写控制指令。使用write函数向串口写命令,发现write函数每次返回值都为1,少于需要写入的字节数.求大佬帮忙看看应该如何解决。
程序如下:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <fcntl.h> // open() close()
#include <unistd.h> // read() write()

#include <termios.h> // set baud rate

#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>


#define DEVICE_TTYUSB "/dev/ttyUSB0"
#define MY_BAUD_RATE B9600

#define RECEIVE_BUF_WAIT_1S 1
#define RECEIVE_BUF_WAIT_2S 2
#define RECEIVE_BUF_WAIT_3S 3
#define RECEIVE_BUF_WAIT_4S 4
#define RECEIVE_BUF_WAIT_5S 5
int func_485_transfer(int fd)
{
int ret;
//ssize_t ret;
char rcv_buf[1024];
int i;

char send_buf[14] = {0};
send_buf[0] = 0xFF;
send_buf[1] = 0x00;
send_buf[2] = 0x00;
send_buf[3] = 0x20;
send_buf[4] = 0x3F;
send_buf[5] = 0x3F;
send_buf[6] = 0x9E;
bzero(rcv_buf,sizeof(rcv_buf));

while(1) {
ret = write(fd,send_buf,strlen(send_buf));
printf("%d\n",sizeof(send_buf));
printf("%d\n",ret);
if (ret == -1) {
printf ("write device %s error\n", DEVICE_TTYUSB);
return -1;
}
return -1;
}

return 0;

}


//------------------------------------- init seriel port ---------------------------------------------------
void init_ttyS(int fd)
{
struct termios options;

bzero(&options, sizeof(options)); // clear options

cfsetispeed(&options,MY_BAUD_RATE); // setup baud rate
cfsetospeed(&options,MY_BAUD_RATE);

options.c_cflag |= ( CS8 | CREAD);//( CS8 | CLOCAL | CREAD);
//options.c_iflag = IGNPAR;

tcflush(fd, TCIFLUSH);

tcsetattr(fd, TCSANOW, &options);

}


//------------------------------------- main ----------------------------------------------------------------
int main(void)
{
int fd;

printf("\n RS485 TRANSFERS DATAS \n\n");

// open seriel port
fd = open(DEVICE_TTYUSB, O_RDWR);

if (fd == -1) {
printf("open device %s error\n",DEVICE_TTYUSB);
}
else {
init_ttyS(fd); // init device
func_485_transfer(fd); // 485 functions
sleep(0.05);

if (close(fd)!=0) printf("close device %s error",DEVICE_TTYUSB);
}

return 0;
}// end main
...全文
34 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

27,375

社区成员

发帖
与我相关
我的任务
社区描述
硬件/嵌入开发 单片机/工控
社区管理员
  • 单片机/工控社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧