当前位置:首页 > 嵌入式 > 嵌入式硬件

先上代码吧:

/*--------------------------------------------------------------日期:2012/1/1功能:串口接收转发到网络--------------------------------------------------------------*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include "rs232.h"#include <errno.h>#include <sys/wait.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <unistd.h>#include <signal.h>#define PORT 3000//#define PACKET_SIZE 8192 #define PACKET_SIZE 6 static int count=0;static unsigned int second;static unsigned int sum;void display(){printf("n");printf("Transfer complete !n");printf("Total size:%d !n",sum);printf("Speed:%d Mbpsn",8*sum/second/0x100000);exit(0);}/*-----------------------------------------client 192.168.2.111 –t 1 –p 1argv[0] = client argv[1] = 172.16.22.155argv[2] = –targv[3] = 1argv[4] = -pargv[5] = 1------------------------------------------*/void Tcp(){int argc_data;char *argv_data[6];int sockfd;int recv_bytes;//unsigned int buf[PACKET_SIZE];unsigned int *Tcp_buf;struct hostent *he;struct sockaddr_in srvaddr;unsigned int uiip;unsigned int nsecond,packet_size;sum=0;argc_data = 6;argv_data[0] = "client";argv_data[1] = "172.16.22.155";argv_data[2] = "-t";argv_data[3] = "1";argv_data[4] = "-p";argv_data[5] = "1";if(argc_data< 4 ){perror("Usage: client <hostIP>  -t time -p PACKET_SIZEn");exit(2);}packet_size=PACKET_SIZE;second=atoi(argv_data[3]);if(argc_data==6)    packet_size=atoi(argv_data[5]);printf("packet_size=%dn",packet_size);Tcp_buf = malloc(packet_size);he=gethostbyname(argv_data[1]);sockfd=socket(AF_INET,SOCK_STREAM,0);bzero(&srvaddr,sizeof(srvaddr));srvaddr.sin_family=AF_INET;srvaddr.sin_port=htons(PORT);srvaddr.sin_addr=*((struct in_addr *)he->h_addr);//aiptoi(argv[1],&uiip);//srvaddr.sin_addr.s_addr=uiip;if(connect(sockfd,(struct sockaddr *) &srvaddr, sizeof(struct sockaddr))== -1){perror("Connect error!n");exit(1);}        //nsecond = htonl(second);      nsecond = 0x01020304;if(write(sockfd,&nsecond,sizeof(nsecond))== -1){perror("Error when send second!n");exit(1);}printf("Data Transfering!n");/*while (1){ if((recv_bytes=read(sockfd,buf,packet_size))<=0){printf("Connection closed!n");break;}sum+=recv_bytes;}*/while(1){write(sockfd, &nsecond, sizeof(nsecond));sleep(5);}close(sockfd);free(Tcp_buf);display();//return 0;}main(int argc, char *argv[]){int ret,portno,nWritten,nRead;char buf[5] = "hell";/*网口实现部分*/int argc_data;char *argv_data[6];int sockfd;int recv_bytes;//unsigned int buf[PACKET_SIZE];unsigned int *Tcp_buf;struct hostent *he;struct sockaddr_in srvaddr;unsigned int uiip;unsigned int nsecond,packet_size;sum=0;argc_data = 6;argv_data[0] = "client";argv_data[1] = "172.16.22.155";argv_data[2] = "-t";argv_data[3] = "1";argv_data[4] = "-p";argv_data[5] = "1";portno=0;if(argc_data< 4 ){perror("Usage: client <hostIP>  -t time -p PACKET_SIZEn");exit(2);}packet_size=PACKET_SIZE;second=atoi(argv_data[3]);if(argc_data==6)    packet_size=atoi(argv_data[5]);printf("packet_size=%dn",packet_size);Tcp_buf = malloc(packet_size);he=gethostbyname(argv_data[1]);sockfd=socket(AF_INET,SOCK_STREAM,0);bzero(&srvaddr,sizeof(srvaddr));srvaddr.sin_family=AF_INET;srvaddr.sin_port=htons(PORT);srvaddr.sin_addr=*((struct in_addr *)he->h_addr);//aiptoi(argv[1],&uiip);//srvaddr.sin_addr.s_addr=uiip;if(connect(sockfd,(struct sockaddr *) &srvaddr, sizeof(struct sockaddr))== -1){perror("Connect error!n");exit(1);}        //nsecond = htonl(second);  /*    nsecond = 0x01020304;if(write(sockfd,&nsecond,sizeof(nsecond))== -1){perror("Error when send second!n");exit(1);}printf("Data Transfering!n");*//*while (1){ if((recv_bytes=read(sockfd,buf,packet_size))<=0){printf("Connection closed!n");break;}sum+=recv_bytes;}*//*while(1){write(sockfd, &nsecond, sizeof(nsecond));sleep(5);}close(sockfd);free(Tcp_buf);display();*///return 0;/*--------------------------------------------------------------------*/while(1){ret=OpenCom(portno,"/dev/ttyS1",115200);if(ret==-1){perror("The /dev/ttyS1 open error.");exit(1);}/*while(1){nWritten=ComWrt(portno,"abc",3);}*/printf("n/dev/ttyS1 has send %d chars!n",nWritten);printf("nRecieving data!***n");fflush(stdout);//buf[5] = "hell";while(1){/*nRead=ComRd(0,buf,256,3000);if(nRead>0){printf("*****OKn");nWritten = ComWrt(portno, buf, sizeof(buf));}*/printf("******start***********n");printf("*****ComRd*****n");//ComRd(0, buf, 256, 3000);nRead = ComRd(0, buf, 256, 3000);if(nRead > 0){printf("The Rddata is: %sn",buf);/*---串口部分-----*/ComWrt(portno, buf, sizeof(buf));printf("The ComWrt data is: %sn",buf);/*网口部分*///nsecond = 0x01020304;if(write(sockfd,buf,sizeof(buf))== -1){perror("Error when send second!n");exit(1);}//printf("Data Transfering!n");write(sockfd, buf, sizeof(buf));printf("send to sockfd :%sn",buf);sleep(1);printf("*****************end*****************n");}/*elseprintf("Timeoutn");*/}if((ret=CloseCom(portno)==-1)){perror("Close com");exit(1);}printf("nn");}printf("Exit now.n");/*网口部分*/close(sockfd);//free(Tcp_buf);display();/*----------------------------------*/return;}

上面就是全部的主程序代码了

还有一个是RS232串口部分的代码:

/*** File: rs232.c**** Description:**      Provides an RS-232 interface that is very similar to the CVI provided**      interface library*/#include <stdio.h>#include <assert.h>#include "rs232.h" #include <sys/time.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <termios.h>#define DEBUGstruct PortInfo ports[MAX_PORTS];/*** Function: OpenCom**** Description:**    Opens a serial port with default parameters**** Arguments:**    portNo - handle used for further access**    deviceName - the name of the device to open**** Returns:**    -1 on failure*/int OpenCom(int portNo, const char deviceName[],long baudRate){    return OpenComConfig(portNo, deviceName, baudRate, 1, 8, 1, 0, 0);}/**/long GetBaudRate(long baudRate){    long BaudR;    switch(baudRate)    {case 115200:BaudR=B115200;break;case 57600:BaudR=B57600;break;case 19200:BaudR=B19200;break;case 9600:BaudR=B9600;break;default:BaudR=B0;    }    return BaudR;}/*** Function: OpenComConfig**** Description:**    Opens a serial port with the specified parameters**** Arguments:**    portNo - handle used for further access**    deviceName - the name of the device to open**    baudRate - rate to open (57600 for example)**    parity - 0 for no parity**    dataBits - 7 or 8**    stopBits - 1 or 2**    iqSize - ignored**    oqSize - ignored**** Returns:**    -1 on failure**** Limitations:**    parity, stopBits, iqSize, and oqSize are ignored*/int OpenComConfig(int port,                  const char deviceName[],                  long baudRate,                  int parity,                  int dataBits,                  int stopBits,                  int iqSize,                  int oqSize){    struct termios newtio;    long BaudR;    ports[port].busy = 1;    strcpy(ports[port].name,deviceName);    if ((ports[port].handle = open(deviceName, O_RDWR, 0666)) == -1)    {        perror("open");       // assert(0);    }    /* set the port to raw I/O */    newtio.c_cflag = CS8 | CLOCAL | CREAD ;    newtio.c_iflag = IGNPAR;//    newtio.c_oflag = 0;//    newtio.c_lflag = 0;    newtio.c_oflag = ~OPOST;    newtio.c_lflag = ~(ICANON | ECHO | ECHOE | ISIG);    newtio.c_cc[VINTR]    = 0;    newtio.c_cc[VQUIT]    = 0;    newtio.c_cc[VERASE]   = 0;    newtio.c_cc[VKILL]    = 0;    newtio.c_cc[VEOF]     = 4;    newtio.c_cc[VTIME]    = 0;    newtio.c_cc[VMIN]     = 1;    newtio.c_cc[VSWTC]    = 0;    newtio.c_cc[VSTART]   = 0;    newtio.c_cc[VSTOP]    = 0;    newtio.c_cc[VSUSP]    = 0;    newtio.c_cc[VEOL]     = 0;    newtio.c_cc[VREPRINT] = 0;    newtio.c_cc[VDISCARD] = 0;    newtio.c_cc[VWERASE]  = 0;    newtio.c_cc[VLNEXT]   = 0;    newtio.c_cc[VEOL2]    = 0;    cfsetospeed(&newtio, GetBaudRate(baudRate));    cfsetispeed(&newtio, GetBaudRate(baudRate));    tcsetattr(ports[port].handle, TCSANOW, &newtio);    return 0;}/*** Function: CloseCom**** Description:**    Closes a previously opened port**** Arguments:**    The port handle to close****    Returns:**    -1 on failure*/int CloseCom(int portNo){    if (ports[portNo].busy)    {        close(ports[portNo].handle);        ports[portNo].busy = 0;        return 0;    }    else    {        return -1;    }}/*** Function: ComRd**** Description:**    Reads the specified number of bytes from the port.**    Returns when these bytes have been read, or timeout occurs.**** Arguments:**    portNo - the handle**    buf - where to store the data**    maxCnt - the maximum number of bytes to read**** Returns:**    The actual number of bytes read*/int ComRd(int portNo, char buf[], int maxCnt,int Timeout){    int actualRead = 0;    fd_set rfds;    struct timeval tv;    int retval;    if (!ports[portNo].busy)    {        assert(0);    }    /* camp on the port until data appears or 5 seconds have passed */    FD_ZERO(&rfds);    FD_SET(ports[portNo].handle, &rfds);    tv.tv_sec = Timeout/1000;    tv.tv_usec = (Timeout%1000)*1000;    retval = select(16, &rfds, NULL, NULL, &tv);    if (retval)    {        actualRead = read(ports[portNo].handle, buf, maxCnt);    }    #ifdef DEBUGif(actualRead>0)    {        unsigned int i;        for (i = 0; i < actualRead; ++i)        {            if ((buf[i] > 0x20) && (buf[i] < 0x7f))            {//                printf("<"%c"", buf[i]);                  printf("%c",buf[i]);            }            else            {//                printf("<%02X", buf[i]);                  printf("%02X",buf[i]);            }        }printf("n");    }    fflush(stdout);#endif /* DEBUG */    return actualRead;}/*** Function: ComWrt**** Description:**    Writes out the specified bytes to the port**** Arguments:**    portNo - the handle of the port**    buf - the bytes to write**    maxCnt - how many to write**** Returns:**    The actual number of bytes written*/int ComWrt(int portNo, const char *buf, int maxCnt){    int written;    if (!ports[portNo].busy)    {        assert(0);    }#ifdef DEBUG    {        int i;        for (i = 0; i < maxCnt; ++i)        {            if ((buf[i] > 0x20) && (buf[i] < 0x7f))            {//                printf(">"%c"", buf[i]);                  printf("%c",buf[i]);            }            else            {//                printf(">%02X", buf[i]);                  printf("%02X",buf[i]);            }        }printf("n");    }    fflush(stdout);#endif /* DEBUG */        written = write(ports[portNo].handle, buf, maxCnt);    return written;}

然后再看头文件:

#ifndef _RS232_H_#define _RS232_H_/* the maximum number of ports we are willing to open */#define MAX_PORTS 4/*this array hold information about each port we have opened */struct PortInfo{int busy;char name[32];int handle;};int OpenCom(int portNo,const char deviceName[],long baudRate);int CloseCom(int portNo);int ComRd(int portNo,char buf[],int maxCnt,int Timeout);int ComWrt(int portNo,const char * buf,int maxCnt);//long GetBaudRate(long baudRate);//int OpenComConfig(int port,//                  const char deviceName[],//                  long baudRate,//                  int parity,//                  int dataBits,//                  int stopBits,//                  int iqSize,//                  int oqSize);#endif

再看效果图:

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

北京——2024年4月30日 亚马逊云科技持续引领云上数据服务创新,助力企业构建全面的数据基座以充分发挥数据潜力,加速生成式AI技术落地。在生成式AI时代,数据是企业脱颖而出的关键——基础模型依赖于大规模高质量数据集,生...

关键字: 生成式AI 数据 模型

全新的专有模型导入功能让客户更轻松地将其专属模型导入到Amazon Bedrock中,从而充分利用Amazon Bedrock的强大功能。全新的模型评估功能使客户能够广泛且便捷地选择完全托管模型,包括RAG优化的新版Am...

关键字: 生成式AI 基础模型 数据

2024年4月17日,中国 – 服务多重电子应用领域、全球排名前列的半导体公司意法半导体(STMicroelectronics,简称ST;纽约证券交易所代码:STM)将在2024年4月25日欧洲证券交易所开盘前公布202...

关键字: 半导体 数据

数据占满我们的电子设备已成常态,为了满足广大用户的需求,NAS应运而生。然而,对于许多普通用户来说,NAS设备的设置和使用却常常令人望而却步。不过,铁威马TOS 6的出现,不仅功能强大,而且操作简便,即使是初次接触NAS...

关键字: 数据 电子设备 NAS

机器学习作为人工智能领域的重要组成部分,其过程涉及到多个核心环节。本文将详细阐述机器学习的四个主要步骤:数据准备、模型选择、模型训练与评估,以及模型部署与应用,以揭示机器学习从数据到应用的完整流程。

关键字: 数据 人工智能 机器学习

机器学习算法是人工智能领域中的核心技术之一,它通过对大量数据进行学习,自动发现数据中的规律和模式,从而实现对新数据的预测、分类、聚类等任务。本文将深入探讨机器学习算法的基本过程,包括数据准备、模型选择、训练与评估等关键步...

关键字: 数据 人工智能 机器学习

随着人工智能(AI)技术的迅速发展,人们对于通用人工智能(AGI,即Artificial General Intelligence)的期待也日益高涨。通用人工智能指的是具备像人类一样全面智能的计算机系统,能够执行各种复杂...

关键字: 人工智能 计算机 数据

蓝牙网关的应用更多的是在宽带家庭网络无线接入网络,而蓝牙mesh网关除了家庭网络之外,在社区网络和企业网络的应用上也非常多,蓝牙mesh网关的无线接入网络非常丰富。

关键字: 蓝牙网关 蓝牙mesh 网关

虽然说蓝牙网关也是网关,但是就使用场景和功能上还是有区别的,不然也不会有区别于通常意义上的网关的蓝牙网关,那么具体蓝牙网关会有哪些不一样的地方呢?

关键字: 蓝牙网关 wifi网关 网关

物联网终端的种类非常多,包括物联网网关、通信模块以及大量的行业终端,其中尤以行业终端的种类最为丰富。

关键字: 物联网 通信协议 网关
关闭
关闭