當前位置:首頁 > 嵌入式 > 嵌入式硬件

先上代碼吧:

/*--------------------------------------------------------------日期:2012/1/1功能:串口接收轉(zhuǎn)發(fā)到網(wǎng)絡--------------------------------------------------------------*/#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";/*網(wǎng)口實現(xiàn)部分*/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);/*網(wǎng)口部分*///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");/*網(wǎng)口部分*/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

再看效果圖:

本站聲明: 本文章由作者或相關(guān)機構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點,本站亦不保證或承諾內(nèi)容真實性等。需要轉(zhuǎn)載請聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請及時聯(lián)系本站刪除。
換一批
延伸閱讀

9月2日消息,不造車的華為或?qū)⒋呱龈蟮莫毥谦F公司,隨著阿維塔和賽力斯的入局,華為引望愈發(fā)顯得引人矚目。

關(guān)鍵字: 阿維塔 塞力斯 華為

加利福尼亞州圣克拉拉縣2024年8月30日 /美通社/ -- 數(shù)字化轉(zhuǎn)型技術(shù)解決方案公司Trianz今天宣布,該公司與Amazon Web Services (AWS)簽訂了...

關(guān)鍵字: AWS AN BSP 數(shù)字化

倫敦2024年8月29日 /美通社/ -- 英國汽車技術(shù)公司SODA.Auto推出其旗艦產(chǎn)品SODA V,這是全球首款涵蓋汽車工程師從創(chuàng)意到認證的所有需求的工具,可用于創(chuàng)建軟件定義汽車。 SODA V工具的開發(fā)耗時1.5...

關(guān)鍵字: 汽車 人工智能 智能驅(qū)動 BSP

北京2024年8月28日 /美通社/ -- 越來越多用戶希望企業(yè)業(yè)務能7×24不間斷運行,同時企業(yè)卻面臨越來越多業(yè)務中斷的風險,如企業(yè)系統(tǒng)復雜性的增加,頻繁的功能更新和發(fā)布等。如何確保業(yè)務連續(xù)性,提升韌性,成...

關(guān)鍵字: 亞馬遜 解密 控制平面 BSP

8月30日消息,據(jù)媒體報道,騰訊和網(wǎng)易近期正在縮減他們對日本游戲市場的投資。

關(guān)鍵字: 騰訊 編碼器 CPU

8月28日消息,今天上午,2024中國國際大數(shù)據(jù)產(chǎn)業(yè)博覽會開幕式在貴陽舉行,華為董事、質(zhì)量流程IT總裁陶景文發(fā)表了演講。

關(guān)鍵字: 華為 12nm EDA 半導體

8月28日消息,在2024中國國際大數(shù)據(jù)產(chǎn)業(yè)博覽會上,華為常務董事、華為云CEO張平安發(fā)表演講稱,數(shù)字世界的話語權(quán)最終是由生態(tài)的繁榮決定的。

關(guān)鍵字: 華為 12nm 手機 衛(wèi)星通信

要點: 有效應對環(huán)境變化,經(jīng)營業(yè)績穩(wěn)中有升 落實提質(zhì)增效舉措,毛利潤率延續(xù)升勢 戰(zhàn)略布局成效顯著,戰(zhàn)新業(yè)務引領(lǐng)增長 以科技創(chuàng)新為引領(lǐng),提升企業(yè)核心競爭力 堅持高質(zhì)量發(fā)展策略,塑強核心競爭優(yōu)勢...

關(guān)鍵字: 通信 BSP 電信運營商 數(shù)字經(jīng)濟

北京2024年8月27日 /美通社/ -- 8月21日,由中央廣播電視總臺與中國電影電視技術(shù)學會聯(lián)合牽頭組建的NVI技術(shù)創(chuàng)新聯(lián)盟在BIRTV2024超高清全產(chǎn)業(yè)鏈發(fā)展研討會上宣布正式成立。 活動現(xiàn)場 NVI技術(shù)創(chuàng)新聯(lián)...

關(guān)鍵字: VI 傳輸協(xié)議 音頻 BSP

北京2024年8月27日 /美通社/ -- 在8月23日舉辦的2024年長三角生態(tài)綠色一體化發(fā)展示范區(qū)聯(lián)合招商會上,軟通動力信息技術(shù)(集團)股份有限公司(以下簡稱"軟通動力")與長三角投資(上海)有限...

關(guān)鍵字: BSP 信息技術(shù)
關(guān)閉
關(guān)閉