c語言串口通信范例_第1頁
c語言串口通信范例_第2頁
c語言串口通信范例_第3頁
c語言串口通信范例_第4頁
c語言串口通信范例_第5頁
已閱讀5頁,還剩5頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

一個(gè)c語言的串口通信程序范例標(biāo) 分類:技術(shù)筆記c語言串口通信通信程序it最近接觸一個(gè)項(xiàng)目,用HL-C1C激光位移傳感器+易控組態(tài)軟件完成生產(chǎn)線高度跳變檢測,好久沒有接觸cc#一些資料,找來做個(gè)記錄,也許大家用的著#include<stdio.h>#include<dos.h>#includevconio.h>#include<string.h>#defineCOM2320x2f8#defineCOMINT0x0b#defineMaxBufLen500#definePort82590x20#defineEofInt0x20staticintcomportaddr;staticcharintvectnum;staticunsignedcharmaskb;staticunsignedcharBuffer[MaxBufLen];staticintCharsInBuf,Circln,CircOut;staticvoid(interruptfar*OldAsynclnt)();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<MaxBufLen)Buffer[CircIn]=inp(comportaddr);if(CircIn<MaxBufLen-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(CharsInBuf>0){(*Char)=Buffer[CircOut];if(CircOut<MaxBufLen-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();}接收程序:#include<dos.h>#include<fstream.h>#include<conio.h>#include<stdio.h>#include<stdlib.h>#include<math.h>#defineRXD0//接收#defineTXD0//發(fā)送#defineLSB0//波特率調(diào)節(jié)低8位#defineMSB1//波特率調(diào)節(jié)高8位#defineIER1//中斷起用寄存器#defineIIR2//中斷標(biāo)識(shí)寄存器#defineLCR3//線路控制寄存器#defineMCR4//調(diào)制解調(diào)器控制寄存器#defineLSR5//線路狀態(tài)寄存器#defineMSR6//調(diào)制解調(diào)器狀態(tài)寄存器#defineIERV1#defineOUT20x08#defineERTS2#defineEDTR1#defineEMPTY0X20#defineREADY0X30#defineICREG0X20#defineIMASKREG0X21#defineEOI0X20#defineWAITCOUNT5000#defineBUFFLEN2048//用于存儲(chǔ)字符的數(shù)組的界#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_6 1 /*/ send 6 bit characters*/#defineSER_BITS_7 2 /*/ send 7 bit characters*/#defineSER_BITS_8 3 /*/ send 8 bit characters*/#define SER_PARITY_NONE 0 /*/ no parity*/#defineSER_PARITY_ODD8 /*/oddparity*/#defineSER_PARITY_EVEN 24 /*/ even parity*/intport;intComNum;unsignedportaddr;unsignedportf;unsignedintbaudtable□={0x180,0xc0,0x60,0x30,0x18,0x0c,0x06};unsignedcharparitytable□={0x08,0x18,0x00,0x28,0x38};unsignedcharbuffer[BUFFLEN];//recvbufintbuffin=0;intbuffout=0;intincount=0;intoutcount=0;voidinterrupt(*vect_com)(...);voidputb(unsignedcharch)//writeachartothere中斷u得到的數(shù)據(jù)寫到緩沖區(qū){inttemp;temp=buffin;if(++buffin==BUFFLEN)buffin=0;if(buffin!=buffout){buffer[buffin]=ch;//printf(〃bufferin[%d]=%c〃,buffer[buffin]);//getch();}elsebuffin=temp;};unsignedchargetb()//readacharfromtherecvbuf(if(buffout!=buffin)(if(++buffout==BUFFLEN)buffout=0;//printf("bufferout[%d]=%c",buffout,buffer[buffout]);return(buffer[buffout]);}elsereturn(0xff);};/*unsignedcharsender(unsignedcharch){outportb(portaddr2+TXD,ch);printf("\nsenderoutportdata=%c\n",ch);outcount++;return(1);};*/voidinterruptreceiver(...){unsignedcharch;ch=inportb(portaddr+RXD);putb(ch);incount++;//記錄接收了多少個(gè)數(shù)據(jù)。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<<portf)));setvect(portf+8,receiver);enable();};voidSerClose(void){disable();outportb(portaddr+IER,0);outportb(portaddr+MCR,0);outportb(IMASKREG,inportb(IMASKREG)|(1<<portf));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);〃初始化串口,設(shè)置波特率等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");//可選擇接收數(shù)據(jù)的存放文件路徑和文件名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);};發(fā)送文件程序#include<dos.h>#include<bios.h>#include<stdio.h>#include<math.h>#include<conio.h>#include<graphics.h>#ifdef__cplusplus#defineCPPARGS...#else#defineCPPARGS#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=T,ser_start=T;/*/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_SIZET)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_SIZET)ser_start=0;ch=ser_buffer[ser_start];printf(〃%x〃,ch);if(char_ready>0)--char_ready;return(ch);}elsereturn(0);}/* 寫串口 */Serial_Write(charch){while(!(inp(open_port+SER_LSR)&0x20)){}asmclioutp(open_port+SER_THR,ch);asmsti}/* 初始化串口 */Open_Serial(intport_base,intbaud,intconfigur{ation)open_port=port_base;disable();outp(port_base+SER_LCR,SER_DIV_LATCH_ON);outp(port_base+SER_DLL,baud);outp(port_base+SER_DLH,0);outp(port_base+SER_LCR,configuration);outp(port_base+SER_MCR,SER_GP02);outp(port_base+SER_IER,1);if(port_base==COM_1||port_base==COM_3){Old_Isr=_dos_getvect(INT_SER_PORT_0);_dos_setvect(INT_SER_PORT_0,Serial_Isr);printf("\nOpeningCommunicationsChannelComPort#1/3...\n〃);}else{Old_Isr=_dos_getvect(INT_SER_PORT_1);_dos_setvect(INT_SER_PORT_1,Serial_Isr);printf("\nOpeningCommunicationsChannelComPort#2/4...\n〃);}old_int_mask=inp(PIC_IMR);outp(PIC_IMR,(port_base==COM_1)?(old_int_mask&0xEF):(old_int_mask&0xF7));enable();}/* 關(guān)閉串口 */Close_Serial(intport_base){outp(port_base+SER_MCR,0);outp(port_base+SER_IER,0);outp(PIC_IMR,old_int_mask);if(port_base==COM_1){_dos_setvect(INT_SER_PORT_0,Old_Isr);printf("\nClosingCommunicationsChannelComPort#1.\n〃);}else{_dos_setvect(INT_SER_PORT_1,Old_Isr);printf("\nClosingCommunicationsChannelComPort#2.\n〃);}}/ 發(fā)送應(yīng)用 */voidmain(intargc,char*argv[]){charch,press;intdone=0;FILE*fp;argc=2;//argv[1]=〃c:\\comfile.c〃;if(argc<2){printf("\nUsage:displayfilename.wav!!!");//exit(1);}if((fp=fopen(argv[1],〃r+b〃))==NULL){printf("cannotopenthefile\n〃);//exit(0);}fseek(fp,0,SEEK_SET);SER_BITS_8Open_Serial(COM_1,SER_BAUD_9600,SER_PARITY_EVENSE

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論