c语言串口通信范例.docx
《c语言串口通信范例.docx》由会员分享,可在线阅读,更多相关《c语言串口通信范例.docx(20页珍藏版)》请在冰豆网上搜索。
![c语言串口通信范例.docx](https://file1.bdocx.com/fileroot1/2023-6/16/1f07a311-1db7-408a-b784-4fa22bb2f82c/1f07a311-1db7-408a-b784-4fa22bb2f82c1.gif)
c语言串口通信范例
一个c语言的串口通信程序范例
标签:
c语言
串口通信
通信程序
it
分类:
技术笔记
最近接触一个项目,用HL-C1C激光位移传感器+易控组态软件完成生产线高度跳变检测,好久没有接触cc#,一些资料,找来做个记录,也许大家用的着
#include
#include
#include
#include
#defineCOM232?
0x2f8
#defineCOMINT 0x0b
#defineMaxBufLen 500
#definePort8259 0x20
#defineEofInt 0x20
staticint comportaddr;
staticcharintvectnum;
staticunsignedcharmaskb;
staticunsignedcharBuffer[MaxBufLen];
staticint CharsInBuf,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(CharsInBuf Buffer[CircIn]=inp(comportaddr);
if(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(CharsInBuf>0)
{
(*Char)=Buffer[CircOut];
if(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();
}
接收程序:
#include
#include
#include
#include
#include
#include
#defineRXD0//接收
#defineTXD0//发送
#defineLSB0//波特率调节低8位
#defineMSB1//波特率调节高8位
#defineIER1//中断起用寄存器
#defineIIR2//中断标识寄存器
#defineLCR3//线路控制寄存器
#defineMCR4//调制解调器控制寄存器
#defineLSR5//线路状态寄存器
#defineMSR6//调制解调器状态寄存器
#defineIERV1
#defineOUT20x08
#defineERTS2
#defineEDTR1
#defineEMPTY0X20
#defineREADY0X30
#defineICREG0X20
#defineIMASKREG0X21
#defineEOI0X20
#defineWAITCOUNT5000
#defineBUFFLEN2048//用于存储字符的数组的界
#defineALTE0X12
#defineALTQ0X10
#defineSER_BAUD_120096
#defineSER_BAUD_240048
#defineSER_BAUD_96000x0C
#defineSER_BAUD_192006
#defineSER_STOP_10/*/1stopbitpercharacter*/
#defineSER_STOP_24/*/2stopbitspercharacter*/
#defineSER_BITS_50/*/send5bitcharacters*/
#defineSER_BITS_61/*/send6bitcharacters*/
#defineSER_BITS_72/*/send7bitcharacters*/
#defineSER_BITS_83/*/send8bitcharacters*/
#defineSER_PARITY_NONE0/*/noparity*/
#defineSER_PARITY_ODD8/*/oddparity*/
#defineSER_PARITY_EVEN24/*/evenparity*/
intport;
intComNum;
unsignedportaddr;
unsignedportf;
unsignedintbaudtable[]={0x180,0xc0,0x60,0x30,0x18,0x0c,0x06};
unsignedcharparitytable[]={0x08,0x18,0x00,0x28,0x38};
unsignedcharbuffer[BUFFLEN];//recvbuf
intbuffin=0;
intbuffout=0;
intincount=0;
intoutcount=0;
voidinterrupt(*vect_com)(...);
voidputb(unsignedcharch)//writeachartotherecvbuf将中断得到的数据写到缓冲区
{
inttemp;
temp=buffin;
if(++buffin==BUFFLEN)
buffin=0;
if(buffin!
=buffout)
{buffer[buffin]=ch;
//printf("bufferin[%d]=%c",buffer[buffin]);
//getch();
}
else
buffin=temp;
};
unsignedchargetb()//readacharfromtherecvbuf
{
if(buffout!
=buffin)
{
if(++buffout==BUFFLEN)
buffout=0;
//printf("bufferout[%d]=%c",buffout,buffer[buffout]);
return(buffer[buffout]);
}
else
return(0xff);
};
/*unsignedcharsender(unsignedcharch)
{
outportb(portaddr2+TXD,ch);
printf("\nsenderoutportdata=%c\n",ch);
outcount++;
return
(1);
};
*/
voidinterruptreceiver(...)
{
unsignedcharch;
ch=inportb(portaddr+RXD);
putb(ch);
incount++;//记录接收了多少个数据。
outportb(ICREG,EOI);
};
voidSerInit(intbaud,intconfiguration)
{
disable();
outportb(portaddr+LCR,0x80);
outportb(portaddr+LSB,baud);
outportb(portaddr+MSB,0x00);
outportb(portaddr+LCR,configuration);
enable();
};
voidSerOpen(void)
{
vect_com=getvect(portf+8);
disable();
inportb(portaddr+RXD);
inportb(portaddr+MSR);
inportb(portaddr+LSR);
inportb(portaddr+IIR);
outportb(portaddr+IER,IERV);
outportb(portaddr+MCR,OUT2|ERTS|EDTR);
outportb(IMASKREG,inportb(IMASKREG)&(~(1< setvect(portf+8,receiver);
enable();
};
voidSerClose(void)
{
disable();
outportb(portaddr+IER,0);
outportb(portaddr+MCR,0);
outportb(IMASKREG,inportb(IMASKREG)|(1< enable();
setvect(portf+8,vect_com);
};
voidGetportaddr(intport)
{
switch(port)
{
case0:
portaddr=0x3F8;break;
case1:
portaddr=0x2F8;break;
case2:
portaddr=0x3E8;break;
case3:
portaddr=0x2E8;break;
}
portf=(port==0)?
4:
3;
};
voidInt()
{
unsignedcharkey,key2;
port=ComNum-1;
if(peek(0x40,port*2)==0)
{
printf("havenospecialcom.\n");
exit
(1);
}
else
{
printf("Theusedportis:
COM%d\n",ComNum);
};
Getportaddr(port);//得到串口地址
SerInit(SER_BAUD_9600,SER_PARITY_EVEN|SER_BITS_8|SER_STOP_1);//初始化串口,设置波特率等
SerOpen();
do
{
if(kbhit())
{
key2=getch();
if(key2==27){break;}
};
key=getb();
if(key!
=0xff)
{
printf("%x\t",key);
FILE*fp;
fp=fopen("C:
\\Receivedata.dat","ab");//可选择接收数据的存放文件路径和文件名
if(fp==NULL)printf("Fileopenerror!
");
//fputc(key,fp);
fwrite(&key,sizeof(unsignedchar),1,fp);
fclose(fp);
}
}while(key2!
=27);
SerClose();
//printf("%dcharhasbeenreceived\n",incount);
//printf("%dcharhasbeensended\n",outcount);
//printf("\nsum=%d\n",sum);
}
voidmain()//com1receive
{
printf("PleaseinputthereceiveCOMnum:
(1~4)\n");
cin>>ComNum;
printf("thecurrentcomsetis:
9600,even,databits8,stop1,");
Int();
printf("\n\nOVER\n");
exit(0);
};
---------------
发送文件程序
#include
#include
#include
#include
#include
#include
#ifdef__cplusplus
#define__CPPARGS...
#else
#define__CPPARGS
#endif
#defineSER_RBF0
#defineSER_THR0
#defineSER_IER1
#defineSER_IIR2
#defineSER_LCR3
#defineSER_MCR4
#defineSER_LSR5
#defineSER_MSR6
#defineSER_DLL0
#defineSER_DLH1
#defineSER_BAUD_120096
#defineSER_BAUD_240048
#defineSER_BAUD_960012
#defineSER_BAUD_192006
#defineSER_GP028
#defineCOM_10x3F8
#defineCOM_20x2F8/*/baseportaddressofport1*/
#defineCOM_30x3E8
#defineCOM_40x2E8
#defineSER_STOP_10/*/1stopbitpercharacter*/
#defineSER_STOP_24/*/2stopbitspercharacter*/
#defineSER_BITS_50/*/send5bitcharacters*/
#defineSER_BITS_61/*/send6bitcharacters*/
#defineSER_BITS_72/*/send7bitcharacters*/
#defineSER_BITS_83/*/send8bitcharacters*/
#defineSER_PARITY_NONE0/*/noparity*/
#defineSER_PARITY_ODD8/*/oddparity*/
#defineSER_PARITY_EVEN24/*/evenparity*/
#defineSER_DIV_LATCH_ON128/*/usedtoturnreg0,1intodivisorlatch*/
#definePIC_IMR0x21/*/pic'sinterruptmaskreg.*/
#definePIC_ICR0x20/*/pic'sinteruptcontrolreg.*/
#defineINT_SER_PORT_00x0C/*/port0interruptcom1&3*/
#defineINT_SER_PORT_10x0B/*/port0interruptcom2&4*/
#defineSERIAL_BUFF_SIZE128/*/currentsizeofcirculatingreceivebuffer*/
voidinterruptfar(*Old_Isr)(__CPPARGS);/*/holdsoldcomportinterrupthandler*/
charser_buffer[SERIAL_BUFF_SIZE];/*/thereceivebuffer*/
intser_end=-1,ser_start=-1;/*/indexesintoreceivebuffer*/
intser_ch,char_ready=0;/*/currentcharacterandreadyflag*/
intold_int_mask;/*/theoldinterruptmaskonthePIC*/
intopen_port;/*/thecurrentlyopenport*/
intserial_lock=0;/*/serialISRsemaphoresothebuffer*/
/*/isn'talteredwillitisbeingwritten*/
/*/tobytheISR*/
/*-------------写串口-----------------*/
voidinterruptfarSerial_Isr(__CPPARGS)
{
serial_lock=1;
ser_ch=inp(open_port+SER_RBF);
if(++ser_end>SERIAL_BUFF_SIZE-1)
ser_end=0;
ser_buffer[ser_end]=ser_ch;
++char_ready;
outp(PIC_ICR,0x20);
serial_lock=0;
}
intReady_Serial()
{
return(char_ready);
}
/*--------------读串口--------------*/
intSerial_Read()
{
intch;
while(serial_lock){}
if(ser_end!
=ser_start)
{
if(++ser_start>SERIAL_BUFF_SIZE-1)
ser_start=0;
ch=ser_buffer[ser_start];
printf("%x",ch);
if(char_ready>0)
--char_ready;
return(ch);
}
else
return(0);
}
/*--------------写串口-----------------*/
Serial_Write(charch)
{
while(!
(inp(open_port+SER_LSR)&0x20)){}