WINDOWSAPI Operation Serial Port

Source: Internet
Author: User

#include <windows.h>#include<stdio.h>intMain () {//1. Open the serial portHANDLE HCom; HCom= CreateFile ("COM1", Generic_read|Generic_write,0, NULL, open_existing,0, NULL); if(HCom = = (HANDLE)-1) printf ("failed to open serial port!\n"); Elseprintf ("Open serial port successful!\n"); //2. Initialize the serial portDCB DCB; Getcommstate (HCom,&DCB); Dcb. BaudRate=9600;//baud rate//dcb.fparity = 0;//parity EnableDcb. ByteSize =8;//Data bitsDcb. Parity = noparity;//Parity CheckDcb. StopBits = Onestopbit;//Stop BitSetCommState (HCom, &DCB); Setupcomm (HCom,1024x768,1024x768);    Commtimeouts timeouts; //Set Read TimeoutTimeouts.readintervaltimeout = +; Timeouts.readtotaltimeoutconstant= the; Timeouts.readtotaltimeoutmultiplier= -; //Set Write timeoutTimeouts.writetotaltimeoutconstant = -; Timeouts.writetotaltimeoutmultiplier= -; SetCommTimeouts (HCom,&timeouts); //emptying buffersPurgeComm (HCom, purge_txclear|purge_rxclear); Sleep ( -); //3. Read and write serialUnsignedCharbuf[Ten] = {0x00,0x06,'D','A','T','A'};    BOOL Bwritestat; DWORD Dwbyteswrite=6; Bwritestat= WriteFile (HCom, buf, Dwbyteswrite, &Dwbyteswrite, NULL); if(!Bwritestat) {printf ("failed to write serial port! \ n"); }    Elseprintf ("Write serial port success!\n"); unsignedCharrbuf[1024x768];    BOOL Breadstat;    DWORD dwBytesRead; Breadstat= ReadFile (HCom, RBuf,1024x768, &dwBytesRead, NULL); if(!Breadstat) {printf ("Read serial failed! \ n"); }    Else{printf ("read serial port success!\n"); }     for(DWORD j =0; J < dwBytesRead; J + +) {printf ("%x", Rbuf[j]); } printf ("\ n"); //4. Close the serial portCloseHandle (HCom); return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.