HANDLE hcom;//global variable serial handle commtimeouts TIMEOUTS;DCB DCB; Button code () {Hcom=createfile (L "COM1",//serial name generic_read| generic_write,//allow read and write 0,//exclusive mode null, open_existing,//open instead of Create 0,//synchronization method null);/////////////////////////////////////// if (hcom== (HANDLE)-1) {MessageBox (L "Open COM failed!");} Setupcomm (hcom,1024,1024);//input buffer and output buffer size are 1024//set read timeout timeouts.readintervaltimeout=1000; timeouts.readtotaltimeoutmultiplier=500; timeouts.readtotaltimeoutconstant=5000;//set write timeout timeouts.writetotaltimeoutmultiplier=500; timeouts.writetotaltimeoutconstant=2000; SetCommTimeouts (hcom,&timeouts); Getcommstate (HCOM,&DCB);d CB. baudrate=9600;//baud softball rate is 9600DCB. The bytesize=8;//has 3 8-bit DCB per byte. parity=noparity;//no parity bit DCB. stopbits=twostopbits;//two stop bit setcommstate (HCOM,&DCB); PurgeComm (hcom,purge_txclear| purge_rxclear);//com Synchronous Message Write-in ()//com synchronous message read out ()//close Com ();} Com Synchronous Message Write () {char lpoutbuffer[100]={"%01#wcsy00080**\r"};//need to nsend the number of the cache to write the buffer size dwbyteswrite=100;// ComstaT;dword Dwerrorflags; BOOL Bwritestat; Clearcommerror (Hcom,&dwerrorflags,&comstat); Bwritestat=writefile (hcom,lpoutbuffer,dwbyteswrite,& Dwbyteswrite,null);//write into the digital if (!bwritestat) {MessageBox (L "Write serial failed!");}} Com synchronization Message read () {char str[100]={""};//initializes the DWORD wcount;//reads the number of bytes bool Breadstat;breadstat=readfile (hcom,str,100,& Wcount,null);//Read the digital if (!breadstat) {MessageBox (L "failed reading serial port!"); return;} CloseHandle (HCom);//Close the serial port} close COM () {CloseHandle (HCOM);//Close the serial port}
VC COM Communication instance