您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 企业文档 > 一个c语言的串口通信程序范例
#includestdio.h#includedos.h#includeconio.h#includestring.h#defineCOM2320x2f8#defineCOMINT0x0b#defineMaxBufLen500#definePort82590x20#defineEofInt0x20staticintcomportaddr;staticcharintvectnum;staticunsignedcharmaskb;staticunsignedcharBuffer[MaxBufLen];staticintCharsInBuf,CircIn,CircOut;staticvoid(interruptfar*OldAsyncInt)();staticvoidinterruptfarAsyncInt(void);voidInit_COM(intComPortAddr,unsignedcharIntVectNum,intBaud,unsignedcharData,unsignedcharStop,unsignedcharParity){unsignedcharHigh,Low;intf;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;elseif(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);elseoutp(Port8259+1,maskb&0xf7);}staticvoidinterruptfarAsyncInt(void){disable();if(CharsInBufMaxBufLen)Buffer[CircIn]=inp(comportaddr);if(CircInMaxBufLen-1)CircIn++;elseCircIn=0;if(CircIn==CircOut)CircOut++;elseCharsInBuf++;enable();outp(Port8259,EofInt);}voidRestore(void){setvect(intvectnum,OldAsyncInt);outp(Port8259+1,maskb);}intGetCharInBuf(unsignedchar*Char){intFlag;Flag=-1;if(CharsInBuf0){(*Char)=Buffer[CircOut];if(CircOutMaxBufLen-1)CircOut++;elseCircOut=0;CharsInBuf--;Flag=0;}returnFlag;}intSendChar(unsignedcharChar){if((inp(comportaddr+5)&0x20)==0)return-1;outp(comportaddr,Char);return0;}main(){inti,c;unsignedcharInChar;Init_COM(COM232,COMINT,1200,8,1,0);while(1){if(kbhit()){if((InChar=getch())==27)break;elsewhile(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf(%c,InChar);}Restore();}
本文标题:一个c语言的串口通信程序范例
链接地址:https://www.777doc.com/doc-7028924 .html