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

先上代码吧:

/*--------------------------------------------------------------日期: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

再看效果图:

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

9月2日消息,不造车的华为或将催生出更大的独角兽公司,随着阿维塔和赛力斯的入局,华为引望愈发显得引人瞩目。

关键字: 阿维塔 塞力斯 华为

加利福尼亚州圣克拉拉县2024年8月30日 /美通社/ -- 数字化转型技术解决方案公司Trianz今天宣布,该公司与Amazon Web Services (AWS)签订了...

关键字: AWS AN BSP 数字化

伦敦2024年8月29日 /美通社/ -- 英国汽车技术公司SODA.Auto推出其旗舰产品SODA V,这是全球首款涵盖汽车工程师从创意到认证的所有需求的工具,可用于创建软件定义汽车。 SODA V工具的开发耗时1.5...

关键字: 汽车 人工智能 智能驱动 BSP

北京2024年8月28日 /美通社/ -- 越来越多用户希望企业业务能7×24不间断运行,同时企业却面临越来越多业务中断的风险,如企业系统复杂性的增加,频繁的功能更新和发布等。如何确保业务连续性,提升韧性,成...

关键字: 亚马逊 解密 控制平面 BSP

8月30日消息,据媒体报道,腾讯和网易近期正在缩减他们对日本游戏市场的投资。

关键字: 腾讯 编码器 CPU

8月28日消息,今天上午,2024中国国际大数据产业博览会开幕式在贵阳举行,华为董事、质量流程IT总裁陶景文发表了演讲。

关键字: 华为 12nm EDA 半导体

8月28日消息,在2024中国国际大数据产业博览会上,华为常务董事、华为云CEO张平安发表演讲称,数字世界的话语权最终是由生态的繁荣决定的。

关键字: 华为 12nm 手机 卫星通信

要点: 有效应对环境变化,经营业绩稳中有升 落实提质增效举措,毛利润率延续升势 战略布局成效显著,战新业务引领增长 以科技创新为引领,提升企业核心竞争力 坚持高质量发展策略,塑强核心竞争优势...

关键字: 通信 BSP 电信运营商 数字经济

北京2024年8月27日 /美通社/ -- 8月21日,由中央广播电视总台与中国电影电视技术学会联合牵头组建的NVI技术创新联盟在BIRTV2024超高清全产业链发展研讨会上宣布正式成立。 活动现场 NVI技术创新联...

关键字: VI 传输协议 音频 BSP

北京2024年8月27日 /美通社/ -- 在8月23日举办的2024年长三角生态绿色一体化发展示范区联合招商会上,软通动力信息技术(集团)股份有限公司(以下简称"软通动力")与长三角投资(上海)有限...

关键字: BSP 信息技术
关闭
关闭