1. 程式人生 > >一個C串列埠通訊程式

一個C串列埠通訊程式

#include <stdio.h>
#include <dos.h>
#include <conio.h>
#include <string.h>

#define COM232  0x2f8
#define COMINT  0x0b

#define MaxBufLen      500
#define Port8259       0x20
#define EofInt        0x20

static int  comportaddr;
static char intvectnum;
static unsigned char maskb;
static unsigned char Buffer[MaxBufLen];
static int  CharsInBuf,CircIn,CircOut;

static void (interrupt far *OldAsyncInt)();
static void interrupt far AsyncInt(void);

void Init_COM(int ComPortAddr, unsigned char IntVectNum, int Baud,
       unsigned char Data, unsigned char Stop, unsigned char Parity)
{
 unsigned char High,Low;
 int f;

 comportaddr=ComPortAddr;
 intvectnum=IntVectNum;

 CharsInBuf=0;CircIn=0;CircOut=0;

 /* set baud rate */
 f=(Baud/100);
 f=1152/f; High=f/256;
 Low=f-High*256;
 outp(ComPortAddr+3,0x80);
 outp(ComPortAddr,Low);
 outp(ComPortAddr+1,High);

 /* set data bits,stop bits,and parity */
 Data=(Data-5)|((Stop-1)*4);
 if(Parity==2) Data=Data|0x18;
 else if(Parity==1) Data=Data|0x8;
 outp(ComPortAddr+3,Data);

 /* set MCR(DTR,RTS=0,OUT1,OUT2=1) */
 outp(ComPortAddr+4,0x0a);

 /* set input data ready interrupt mode */
 outp(ComPortAddr+1,0x01);

 /* set 0C interrupt vector */
 disable();
 OldAsyncInt=getvect( IntVectNum );
 setvect( IntVectNum, AsyncInt );
 enable();

 /* open interrupt */
 maskb=inp(Port8259+1);
 if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); /*INT4*/
 else outp(Port8259+1,maskb&0xf7);               /*INT3*/
}

static void interrupt far AsyncInt(void)
{
 disable();

 if(CharsInBuf<MaxBufLen)
  Buffer[CircIn]=inp(comportaddr);
 if(CircIn<MaxBufLen-1) CircIn++;
 else CircIn=0;
 if(CircIn==CircOut) CircOut++;
 else CharsInBuf++;
 enable();
 outp(Port8259,EofInt);
}

void Restore(void)
{
 setvect(intvectnum,OldAsyncInt); /* restore old IRQ4 vector */
 outp(Port8259+1,maskb);  /* restore 8259 mask word */
}
int GetCharInBuf(unsigned char *Char)
{
 int Flag;

 Flag=-1;

 if(CharsInBuf>0)
  {
   (*Char)=Buffer[CircOut];
   if(CircOut<MaxBufLen-1)CircOut++;
   else CircOut=0;
   CharsInBuf--;
   Flag=0;
  }
   return Flag;
}

int SendChar(unsigned char Char)
{
 if((inp(comportaddr+5)&0x20)==0) return -1;
 outp(comportaddr,Char);
 return 0;
}

main()
{
 int i,c;
 unsigned char InChar;

 Init_COM(COM232,COMINT,1200,8,1,0);
 while(1)
  {
   if(kbhit())
     {if((InChar=getch())==27)break;
      else while(SendChar(InChar));
     }
   if(GetCharInBuf(&InChar)==0)  /* displaying input char */
      printf("%c",InChar);
 }
Restore();
}