Realization of Read-write serial port (i.)

Source: Internet
Author: User
Tags sprintf

windows open serial port, read and write serial port, automatic identification serial port

This serial port reads and writes asynchronously, namely the non-blocking mode reads and writes the serial port

Serial name such as: "COM3", "COM4", "COM22" and so on

Where COM1 to COM9 can be successfully opened, but COM10 and above open are failed, need special treatment

And COM10 above the open Way is: "\\\\.\\COM10", "\\\\.\\com11", "\\\\.\\COM22" and so on, which is COM10 that the above serial name open mode



Open the serial port:

Open the UART
bool Openuartport (char *uartportname)
{
	bool bresult = true;
	Hcomm = CreateFile (
					  uartportname, 
					  generic_write | Generic_read,	//Access
					  0,							//Do not share
					  NULL,							//The handle returned does not allow the quilt process
					  to inherit open_existing,
					  file_flag_ OVERLAPPED,							//0: Synchronous mode, file_flag_overlapped: Asynchronous mode
					  0								//Do not use temporary file handle
					  );
	if (Invalid_handle_value = = Hcomm)
	{
		printlogcom ("Open Failed!!! \ n ");
		Bresult = false;
	}
	else
	{
		printlogcom ("Open successfully!!! \ n ");
		if (Inituartport (Hcomm, 9600, 8, noparity, onestopbit))
		{
			printlogcom ("Init Uart Port OK!!! \ n ");
		}
		else
		{
			//printlogcom ("Init Uart Port Failed!!! \ n ");
			Bresult = false;
			Close_uartport ();
		}
	}

	return bresult;
}

Initialize the serial port:

Init UART BOOL inituartport (HANDLE hcomm, DWORD baudrate, byte bytesize, byte Parity, byte stopbits) {BOOL bresult = t
	Rue

	Char buffer[50]= "";
	Sets the size of the receive buffer and output buffer DWORD dwinqueue = 1024;
	DWORD dwoutqueue = 1024; if (! Setupcomm (Hcomm, Dwinqueue, Dwoutqueue)) {//printlogcom ("Set in and out Buffer Failed!!!
		\ n ");
	Bresult = false; } else {//printlogcom ("Set Input and Output Buffer OK!!!

		\ n ");
		Set the read-write timeout time to calculate commtimeouts timeouts in milliseconds; For read readtotaltimeouts = ReadTotalTimeoutMultiplier * toreadbytenumber + readtotaltimeoutconstant, timeouts.					ReadIntervalTimeout = Maxdword; Receives a maximum time-out between two characters timeouts.			ReadTotalTimeoutMultiplier = 0; The coefficient timeouts to multiply by reading the number of bytes to read.				ReadTotalTimeoutConstant = 0; Read total time-out constant//for write writetotaltimeouts = writetotaltimeoutmultiplier * Towritebytenumber + Writetotaltimeoutconstan T//timeouts.
		WriteTotalTimeoutMultiplier = 0; Timeouts.

		writetotaltimeoutconstant = 0; if (!
			SetCommTimeouts (Hcomm, &timeouts)) {Printlogcom ("Set read/write timeouts Failed!!!
			\ n ");
		Bresult = false; } else {//printlogcom ("Set read/write timeouts OK!!!
			\ n ");
			Set DCB (device-control-block) DCB DCB; if (! Getcommstate (Hcomm, &DCB)) {//printlogcom ("Get Com DCB Failed!!!
				\ n ");
			Bresult = false; } else {//printlogcom ("Get Com DCB successfully!!!
\ n "); /* sprintf (buffer, "baudrate =%ld", DCB.
				baudrate);
				printlogcom (buffer); sprintf (buffer, "bytesize =%u\n", DCB.
				ByteSize);
				printlogcom (buffer); sprintf (buffer, "Parity =%u\n", DCB.
				Parity);
				printlogcom (buffer); sprintf (buffer, "stopbits =%u\n", DCB.
				StopBits);
				printlogcom (buffer); sprintf (buffer, "XonChar =%d\n", DCB.
				XonChar);
printlogcom (buffer);
				*/memset (&DCB, 0, sizeof (DCB)); Dcb.
				BaudRate = baudrate; Dcb.
				ByteSize = ByteSize; Dcb.
				Parity = Parity; Dcb.
				StopBits = StopBits; Dcb.
	
				XonChar = 1; if (! SetCommState (Hcomm, &DCB)) {//printlogcom ("Set CoM Failed!!!
					\ n ");
				Bresult = false; } else {//printlogcom ("Set Com successfully!!!

					\ n "); Empty the buffer if (!) of the receive cache and output cache. PurgeComm (Hcomm, Purge_rxclear | Purge_txclear)) {//printlogcom ("Clean up in buffer and out buffer Failed!!!
						\ n ");
					Bresult = false; } else {//printlogcom ("Clean on buffer and out buffer OK!!!
					\ n ");
}}}}} return bresult;
 }

Read serial

BOOL Rcvdatafromuartport (HANDLE hcomm, void *rcvbuf, DWORD Torcvdatalen, DWORD *rcveddatalen, lpoverlapped lpoverlapped)
{
	BOOL bresult = true;
	DWORD dwtemprcveddatalen = 0;
	DWORD dwerror;

	if (Clearcommerror (hcomm,&dwerror,null))
	{
		PurgeComm (Hcomm,purge_txabort | purge_txclear);
	}

	if (hcomm! = Invalid_handle_value)
	{
		if (! ReadFile (Hcomm, Rcvbuf, Torcvdatalen, &dwtemprcveddatalen, lpoverlapped))
		{
			if (getlasterror () = = ERROR _io_pending)
			{while
				(! GetOverlappedResult (Hcomm,lpoverlapped,&dwtemprcveddatalen,false))
				{
					if (getlasterror () = = ERROR_IO _incomplete)
					{
						continue;
					}
					else
					{
						clearcommerror (hcomm,&dwerror,null);
						Bresult = false;
						Break
	;
	}}}} else
	{
		bresult = false;
	}
	*rcveddatalen = Dwtemprcveddatalen;
	return bresult;
}

Write serial

BOOL Senddatatouartport (HANDLE hcomm, void *sndbuf, DWORD Senddatalen, DWORD *sentdatalen, lpoverlapped lpoverlapped) 
  {
	BOOL bresult = true;
	DWORD Dwtempsnddatalen;
	DWORD dwerror;

	if (Clearcommerror (hcomm,&dwerror,null))
	{
		PurgeComm (Hcomm,purge_txabort | purge_txclear);
	}

	if (hcomm! = Invalid_handle_value)
	{
		if (! WriteFile (Hcomm, Sndbuf, Senddatalen, &dwtempsnddatalen, lpoverlapped))
		{
			if (getlasterror () = = ERROR_ io_pending)
			{while
				(! GetOverlappedResult (Hcomm,lpoverlapped,&dwtempsnddatalen,false))
				{
					if (getlasterror () = = ERROR_IO_ Incomplete)
					{
						continue;
					}
					else
					{
						clearcommerror (hcomm,&dwerror,null);
						Bresult = false;
						Break
	;
	}}}} else
	{
		bresult = false;
	}
	*sentdatalen = Dwtempsnddatalen;

	return bresult;
}





















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.