ubuntu上使用485通信

  • Post author:
  • Post category:其他


前段时间发现把yolov3程序弄完之后,还得把485通信加上,这样才能与远端进行协调,达到通信的目的。不然只能再本地上面看看,显然是不合理的。写了个通信demo,初步能够485进行收发的操作。

/*************************************************************************
	> File Name: client.c
	> Author: fqlovetb
	> Created Time: Wed 21 August 2019 03:45:21 PM 
 ************************************************************************/
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netinet/in.h>

//5004 is to port1 
//IP address 192.168.1.125
const int port = 5004;
const char* ip = "192.168.1.125"; 
 
int main()
{
	  //create socket 
	  int clt_sock = socket(AF_INET, SOCK_STREAM, 0); 
	  if(clt_sock < 0)
	  {

		  perror("socket");
		  return 1;
	  }
 
	  //name is socket 
	  struct sockaddr_in addr; 
	  addr.sin_family = AF_INET; 
	  addr.sin_port = htons(port); 
	  //IPv4 address
	  addr.sin_addr.s_addr = inet_addr(ip); 

          //struct sockaddr_in peer;
	  socklen_t addr_len = sizeof(addr);
	  int connect_fd = connect(clt_sock, (struct sockaddr*)&addr, addr_len);
	  if(connect_fd < 0)
	  {
		  perror("connect");
		  return 2;
	  }
	  char buf[1024];
 
	  while(1)
	  {
		  memset(buf, '\0', sizeof(buf));
		  printf("client please enter: ");
		  fflush(stdout);
		  ssize_t size = read(0, buf, sizeof(buf) - 1);
		  if(size > 0)
		  {
			  buf[size - 1] = '\0';
		  }
		  else if(size == 0)
		  {
			  printf("read is done...\n");
			  break;
		  }
		  else
		  {
			  perror("read");
			  return 4;
		  }
		 // printf("client: %s\n", buf);
          write(clt_sock, buf, strlen(buf));
		  size = read(clt_sock, buf, sizeof(buf));
		  if(size > 0)
		  {
		 	  buf[size] = '\0';
		  }
		  else if(size == 0)
		  {
			  printf("read is done...\n");
			  break;
		  }
		  else 
		  {
			  perror("read");
			  return 5;
		  }
		  printf("server: %s\n", buf);
	   }
	  close(clt_sock);
	  return 0;
}



版权声明:本文为fqlovetb原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。