一个关于PC机通信软件设计

来源:互联网 发布:君子知怕行文思路 编辑:程序博客网 时间:2024/05/20 20:20

老师留下的作业,总结了一下:

函数:bioscom(int cmd,char byte,int port)、

void sport(char ch)、rport()、void sendf(char *fname)、void receivef(char *fname);

软件环境:WIN-TC

注解:bioscom(int cmd,char byte,int port)用于实现由port指定的I/O端口上进行的各种RS-232C异步通信。Port为0表示串口1(COM1),port为1表示串口2(COM2)。

通信类型取决于cmd的值,它实际上是软中断INT14H的子功能号。

表1

cmd

功能

0

初始化串行口port

1

发送一个字符(写串口)

2

接收一个字符(读串口)

3

返回串口当前状态

void sport(char ch),采用查询方式实现从串口1发送一个字符功能的子函数。

rport()利用bioscom函数接收字符的功能,采用查询方式从串口1接收一个字符的子函数。该函数不断查询"数据准备就绪"位,若为1,说明串口收到了一个字符的数据;否则,用按下任意键退出程序的方法避免程序陷入死循环。

void sendf(char *fname)PC机发送子程序。

void receivef(char *fname)PC机接收子程序。

PC机接收、发送子程序mypro.c:

#include<string.h>

#include<conio.h>

#include<dos.h>

#include<io.h>

#include<math.h>

#include<stdio.h>

#include<stdlib.h>

void sport(char ch)

{while(!(bioscom(3,0,0)&0x2000));

if(bioscom(1,ch,0)&0x800)

{printf("time-out error!\n");

exit(1);

}

}

rport()

{int a;

while(!(bioscom(3,0,0)&0x0100))

{if(kbhit())

{getch();

exit(1);

}

a=bioscom(2,0,0)&0x00f;

return(a);

}

}

/*PC机发送子程序*/

void sendf(char *fname)

{FILE *fp;

char ch;

int handle,count,sum=0;

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

{printf("Cannot open the input file!\n");

exit(1);

}

handle=fileno(fp);

count=filelength(handle);

printf("Ready to send files...\n");

do

{ch='?';

sport(ch);

}while(rport()!='.');

sport(count);

rep:

for(;count;count--)

{ch=getc(fp);

sum=sum+ch;

if(ferror(fp))

{printf("Wrong reading files\n");

break;

}

sport(ch);

}

sport(sum);

if(rport()=='F')

{count=filelength(handle); /*filelenth(handle); */

sum=0;

fseek(fp,-count,1);

goto rep;

}

else

{fclose(fp);

printf("End to send the file\n");

}

}

/*PC机接收子程序*/

void receivef(char *fname)

{FILE *fp;

char ch;

int count,temp,sum=0;

remove(fname);

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

{printf("Cannot open file\n");

exit(1);

}

printf("Receiving the file name:%s\n",fname);

while(rport()!='?');

sport('$');

ch='.';

sport(ch);

temp=rport();

count=temp;

rep:

for(;count;count--)

{ch=rport();

putc(ch,fp);

sum=sum+ch;

if(ferror(fp))

{printf("Write documents wrong\n");

exit(1);

}

}

if(rport()!=sum)

{ch='F';

sport(ch);

count=temp;

sum=0;

fseek(fp,-count,1);

goto rep;

}

else

{ch='0';

sport(ch);

fclose(fp);

printf("Receiving the file end\n");

}

}

main(int argc,char *argv[])

{while(argc!=3)

{printf("Command line order wrong,again!\n");

exit(1);

}

bioscom(0,0x83,0);

if(tolower(*argv[1])=='s')

sendf(argv[2]);

else if (tolower(*argv[1])=='r');

receivef(argv[2]);

}

注:这里采用的是带参主函数main(int argc,char *argv[])。agrc是一个整型变量,argv[]是一个字符型指针数组。

在WIN-TC中编译执行上述数据。

打开DOS命令行,将目录确定到你的程序文件夹:

mypro s f1.c 【即从当前盘上将名为f1.c的文件夹从串口发送出去。】

mypro r f2.c 【即从串口发送若干字符,并写入当前盘上名为f2.c 的文件中去。】

这时你打开你的程序文件夹则发现f2.c文件已经收到。

若你的电脑没有COM端口则:

总结:

1、对单片机了解不够,再做一些练习时,没有实物无法判断程序的结果。

2、在C中有很多函数需要记,需要总结。

3、每个程序都需要做一下流程图,根据流程图思路可以更清晰,更完善。