低碳科技
您的当前位置:首页串口通信

串口通信

来源:低碳科技


串口通信

include"dos.h"

include"stdlib.h"

include"stdio.h"

definePORT0

voidSendFile(charfname);/发送文件

voidSend(ints);/发送一个字节

voidSendFileName(charfname);/发送文件名

voidReceiveFile();/接收文件

voidGetFileName(charf);/接收文件名

voidInitPort(intport,unsignedcharpara);/初始化端口/voidSendPort(intport,charc);/端口发送

intReadPort(intport);/读端口字节

intCheckState(intport);/检查端口状态

intReceive(intport,intG);/接收一个字节

main(intargc,charargv[])

if(argc<2){

printf("PleaseinputR(receive)orS(sent)parametre:");e_it(1);

InitPort(PORT,231);

if(argv[1]==''''S'''')/检查选择的有效性

SendFile(argv[2]);

elseif(argv[1]==''''R'''')

ReceiveFile();

else{

printf("XXX.");

e_it(1);

voidSendFile(charfname){

FILEfp;

intch,s;

if((fp=fopen(fname,"rb"))==NULL)

printf("Can''''topenthefile. ");

e_it(1);

SendFileName(fname);

ch=(int)getc(fp);

if(ferror(fp)){

printf("Errorreadingfile. ");

break;

s=ch%16;/取文件中一个字节的低4位/Send(s);

s=ch/16;/取文件中一个字节的高4位/Send(s);

}while(!feof(fp));

s=46;/发送文件结束信息

Send(s);

Send(s);

fclose(fp);

voidSend(s)

ints;

intG;

SendPort(PORT,s);

G=ReadPort(PORT);/等待握手信号

if(s!=G)

s=s+16;

SendPort(PORT,s);

G=ReadPort(PORT);/等待握手信号

}while(s!=G);

voidSendFileName(fname)

charfname;

ints,ch;

printf("XXX...");while(fname){

ch=(int)fname++;

s=ch%16;/取文件名中一个字节的低4位/Send(s);

s=ch/16;

Send(s);/取文件名中一个字节的低4位/}

s=32;/发送文件名结束标志

Send(s);

Send(s);

voidReceiveFile(){

FILEfp;

charch;

intG1,G2,G3;

charfname[15];

GetFileName(fname);

printf("Receivingfile%s. ",fname);

remove(fname);

if((fp=fopen(fname,"wb"))==NULL)

printf("Can''''topenoutputfile. ");

e_it(1);

/循环为检测每次接受的数据是否为新数据,如果不是,则用此次接收的数据覆盖上次接收的数据

G1=ReadPort(PORT);

G2=Receive(PORT,G1);

G3=Receive(PORT,G2);

ch=(char)(G1%16+G216);/恢复分开的数据,组合高4位和低4位/putc(ch,fp);

if(ferror(fp)){

printf(" Errorwritingfile.");

e_it(1);

G2=Receive(PORT,G3);

G1=G3;

}while(G1/16!=48);

printf(" Transmitfinished.");

fclose(fp);

intReceive(port,G)

intport,G;

intGM;

SendPort(port,G);

GM=ReadPort(port);

if(GM/16==0)

returnGM;

elseif(GM/16==1){

G=GM;

SendPort(port,GM);

GM=ReadPort(port);

}while(GM/16==1);

returnGM;

voidGetFileName(charf)

intG1,G2,G3;

charch;

G1=ReadPort(PORT);

G2=ReadPort(PORT);

G3=Receive(PORT,G3);

ch=(char)(G1%16+G2/16);

f=ch;

f++;

G2=Receive(PORT,G3);

G1=G3;

}while(G1/16!=32);

printf("Filenametransmitfinished. ");}

voidInitPort(port,para)

intport;

unsignedcharpara;

unionREGSreg;

XXX;

XXX;

XXX;

int86(0_14,,);

voidSendPort(port,c)

intport;

charc;

unionREGSreg;

XXX;

XXX;

XXX;

int86(0_14,,);

if(XXX){

printf(" Sendmistakes!");

e_it(1);

intReadPort(port)

intport;

unionREGSreg;

while(!(CheckState(port)256)){

if(kbhit()){/如端口长期无数据可人为终止等待/printf("Pressanykeytoe_it.");

getch();

e_it(1);

XXX;

XXX;

int86(0_14,,);

if(XXX){

printf(" Readmistake!");

e_it(1);

XXX;

intCheckState(port)

intport;

unionREGSreg;

XXX;

XXX;

int86(0_14,,);

XXX;

显示全文