C语言串口通信-源代码
#include
#include
#include
#include
#define COM232 0x2f8
#define COMINT 0x0b
#define MaxBufLen 500
字符串长度c++#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;
f=(Baud/100);
f=1152/f; High=f/256;
Low=f-High*256;
outp(ComPortAddr+3,0x80);
outp(ComPortAddr,Low);
outp(ComPortAddr+1,High);
Data=(Data-5)|((Stop-1)*4);
if(Parity==2) Data=Data|0x18;
else if(Parity==1) Data=Data|0x8;
outp(ComPortAddr+3,Data);
outp(ComPortAddr+4,0x0a);
outp(ComPortAddr+1,0x01);
disable();
OldAsyncInt=getvect( IntVectNum );
setvect( IntVectNum, AsyncInt );
enable();
maskb=inp(Port8259+1);
if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); else outp(Port8259+1,maskb&0xf7);
}
static void interrupt far AsyncInt(void)
{
disable();
if(CharsInBuf<maxbuflen)< p="">
Buffer[CircIn]=inp(comportaddr);
if(CircIn<="" p="">
else CircIn=0;
if(CircIn==CircOut) CircOut++;
else CharsInBuf++;
enable();
outp(Port8259,EofInt);
}
void Restore(void)
{
setvect(intvectnum,OldAsyncInt);
outp(Port8259+1,maskb);
}
int GetCharInBuf(unsigned char *Char)
{
int Flag;
Flag=-1;
if(CharsInBuf>0)
{
(*Char)=Buffer[CircOut];
if(CircOut<maxbuflen-1)circout++;< p="">
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)
printf("%c",InChar);
}
Restore();
}
接收程序:
#include
#include
#include
#include
#include
#include
#define RXD 0 //接收
#define TXD 0 //发送
#define LSB 0 //波特率调节低8位
#define MSB 1 //波特率调节高8位
#define IER 1 // 中断起用寄存器
#define IIR 2 //中断标识寄存器
#define LCR 3 //线路控制寄存器
#define MCR 4 //调制解调器控制寄存器
#define LSR 5 //线路状态寄存器
#define MSR 6 //调制解调器状态寄存器
#define IERV 1
#define OUT2 0x08
#define ERTS 2
#define EDTR 1
#define EMPTY 0X20
#define READY 0X30
#define ICREG 0X20
#define IMASKREG 0X21
#define EOI 0X20
#define WAITCOUNT 5000
#define BUFFLEN 2048 //用于存储字符的数组的界
#define ALTE 0X12
#define ALTQ 0X10
#define SER_BAUD_1200 96
#define SER_BAUD_2400 48
#define SER_BAUD_9600 0x0C

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。