Serial communication instance under Windows CE
Serial communication is the most basic communication method of computer, communication, and control. In the 9CBS "Embedded Development / Wince" community, some people often ask where to find a serial communication example, in fact, I have asked myself. :) The general answer is to provide you with a Pocket PC 2002 SDK example. But the SDK's program and the MFC structure are very different, and it is not very convenient for those who want to write a communication program with MFC.
On the other hand, since Windows CE is a Unicode-based operating system, and Windows CE does not support serial communication overlapping I / O modes for Windows, there are some serial communication classes under Windows CEs with some desktop Windows. different places.
The following is the MFC examples I have changed from the SDK program, I hope to communicate a lot of friends who are committed to WinCE development. Because I am scattered, there are many imperfect places in the process, please correct. My program is based on the assumption of "active send request, passive reception response", so I only set a thread that receives data.
Thanks to the "Embedded Development / Wince" community to provide friends with SDK examples, thanks to all the enthusiastic friends on the 9CBS, I wish China's hardware and hardware levels can be squeezed in the world.
Header file serial.h
// serial.h: interface for the cserial class.
//
//
#if! defined (AFX_SERIAL_H__59575586_AAA9_4FEF_B2A7_E089553698EF__INCLUDED_)
#define AFX_SERIAL_H__59575586_AAA9_4FEF_B2A7_E089553698EF__INCLUDED_
#iF _MSC_VER> 1000
#pragma overce
#ENDIF / / 100 m _ _ _
DWORD WINAPI READPORTTTHREAD (LPVOID LPVOID); // Read Data Thread
Class CSerial
{
PUBLIC:
BOOL INITCOMMTIMEOUTS (); // Setting timeout parameters
BOOL INITDCB (); // Configure serial port
BOOL M_BCONNECTED;
Bool Closeport (Handle Hcommport); // Close the serial port
DWORD WRITEPORT (TCHAR * BUF, DWORD DWBYTESTOWRITE); // Write data
Bool OpenPort (LPTSTSTSTSTSTSZPORTNAME); / / Open the serial port
CSERIAL ();
Handle hreadthread;
Virtual ~ cserial ();
}
#ENDIF /! Defined (AFX_SERIAL_H__59575586_AAA9_4FEF_B2A7_E089553698EF__INCLUDED_)
Source file: serial.cpp
// serial.cpp: Implementation of the cserial class.
//
//
#include "stdafx.h"
#include "serial.h"
#ifdef _Debug
#undef this_file
Static char this_file [] = __ file__;
#define new debug_new
#ENDIF
Handle Hport;
Cstring strinchar;
//
// construction / destruction
//
CSerial :: CSerial ()
{
}
CSerial :: ~ cserial ()
{
IF (hport! = invalid_handle_value)
Closeport (HPORT);
Bool CSERIAL :: OpenPort (LPTSTR LPSZPORTNAME)
{
DWORD DWERROR,
DWTHREADID;
IF (HPORT)
{
Return False;
}
// Open the serial port
Hport = createfile (lpszportname, generic_read | generic_write,
0, NULL, OPEN_EXISTING, 0, NULL);
// If you open an error, return false
IF (hport == invalid_handle_value)
{
/ / Can't open the port
Cstring strerror;
STRERROR.FORMAT (_T ("Unable to open% s, error no. =% d"),
LPSZPortName, getLastError ());
MessageBox (NULL, STRERROR, TEXT ("Error"), MB_OK;
Return False;
}
/ / Specify the event set monitored by port
Setcommmask (Hport, EV_RXCHAR);
// Distribution equipment buffer
SetupComm (Hport, 512, 512);
/ / Initialize the information in the buffer
PurgeComm (HPORT, PURGE_TXCLEAR | PURGE_RXCLEAR);
// Configure the serial port
IF (! initdcb ())
Return False;
// Set the port timeout value
IF (! INITCOMMTIMEOUTS ())
Return False;
/ / Set the status of the specified signal on the port
// setdtr: Send DTR (DATA-TERMINAL-READY) signal
// setRTS: Send RTS (Request-to-send) signal
EscapeCommfunction (HPORT, SETDTR);
EscapeCommfunction (HPORT, SETRTS);
// Create a thread that reads data from the serial port
IF (hreadthread = CreateThread (Null, 0, ReadportThread, 0, 0,
& dwthreadid))
{
}
Else
{
/ / Can't create threads
MessageBox (NULL, Text ("Unable to create the read thread",
Text ("Error"), MB_OK;
Dwerror = getLastError ();
Return False;
}
m_bconnected = true;
Return True;
}
DWORD CSERIAL :: Writeport (Tchar * BUF, DWORD DWCHARTOWRITE)
{
Bool fwritestate;
DWORD DWBYTESWRITTEN
//data input
FWRITESTATE = Writefile (Hport, BUF, DWCHARTOWRITE * SIZEOF (TCHAR), & DWBYTESWRITEN, NULL
IF (! fwritestate)
{
// Do not write data
MessageBox (NULL, Text ("Can't Write String to Comm", Text ("Error"), MB_OK;
DWBYTESWRITEN = 0;
}
Return dwbyteswritten;
}
DWORD WINAPI ReadportThread (LPVOID LPVOID)
{
Bool FreadState;
DWORD DWCOMMMODEMSTATUS;
DWORD DWLENGTH;
COMSTAT COMSTAT; DWORD DWERRORFLAGS;
While (hport! = invalid_handle_value)
{
// Waiting for the event of the serial port
Waitcommevent (Hport, & dwcommodemstatus, 0);
IF (DWcommmodemStatus & Ev_RxCha)
{
Clearcommrror (Hport, & Dwerrorflags, & Comstat);
// cbinque Returns the number of characters in the serial driver input queue
DWLENGTH = Comst.cbinque;
IF (DWLENGTH> 0)
{
/ / Read data from serial port
Tchar * buf = new tchar [256];
FreadState = Readfile (Hport, BUF, DWLENGTH, & DWLENGTH, NULL);
IF (! freadState)
{
/ / Do not read data from serial ports
MessageBox (NULL, TEXT ("ERROR in Read from Serial Port", Text ("Read Error", MB_OK);
}
Else
{
// assign data to global variables
Strinchar = BUF;
}
DELETE [] BUF;
}
}
GetcommmodemStatus (Hport, & dwcommodemstatus);
}
Return 0;
}
Bool CSERIAL :: Closeport (Handle Hcommport)
{
IF (hcommport! = invalid_handle_value)
{
/ / Set the connection attribute to false
m_bconnected = false;
// End Waitcommmevent in the thread
Setcommmask (HPORT, 0);
// block to thread stop
IF (HREADTHREAD)
{
TerminateThread (Hreadthread, 0);
CloseHandle (HREADTHREAD);
}
/ / Clear the status of the specified signal on the port
EscapeCommfunction (HPORT, CLRDTR);
EscapeCommfunction (HPORT, CLRRTS);
/ / Clear the sending and receiving queue inside the driver
PurgeComm (HPORT, PURGE_TXCLEAR | PURGE_RXCLEAR);
// Turn off the serial port
CloseHandle (hcommport);
hcommport = invalid_handle_value;
Return True;
}
Else
{
Return True;
}
}
Bool CSerial :: initdcb ()
{
DCB portdcb;
DWORD DWERROR;
Portdcb.dcblength = sizeof (dcb);
// Get the default setting information of the port
Getcommstate (HPORT, & PortDCB);
// Change DCB structure settings
Portdcb.baudrate = 19200; // baud rate
Portdcb.fbinary = true; // Win32 does not support non-binary serial transfer mode, must be true
Portdcb.fparity = true; // Enable parity
Portdcb.foutxctsflow = true; // The output of the serial port is controlled by CTS line
Portdcb.foutxdsrflow = false; // Close the DSR stream control of the serial port
Portdcb.fdtrControl = DTR_CONTROL_ENABLE; / / Enable DTR line portdcb.fdsrsensitivity = false; // If set to true will ignore any input bytes unless the DSR line is enabled
//Portdcb.ftxcontinueonxoff = true; // When the reception buffer is full and the driver has transmitted Xoff characters, the driver will stop the transmitted character.
Portdcb.ftxcontinueonxoff = false;
Portdcb.foutx = false; // Set to true Specify XON / XOFF Control to Control Serial Output
Portdcb.finx = false; // Set to true Specify XON / XOFF control to control serial input
Portdcb.ferrorchar = false; // WINCE Serial driver's default execution will ignore this field
Portdcb.fnull = false; // Set to true will ignore the serial driver ignore the received empty byte
Portdcb.frtscontrol = RTS_Control_enable; // Enable RTS line
Portdcb.fabortonerror = false; // WINCE Serial Driver's default execution will ignore this field
Portdcb.bytesize = 8; / / // number of bits per byte
Portdcb.parity = noparity; // No parity check
Portdcb.stopbits = onestopbit; // a stop bit per byte
/ / Founded according to DCB structure
IF (! setcommstate (hport, & portdcb))
{
/ / Can't configure serial port
MessageBox (NULL, Text ("Unable to Configure the Serial Port),
Text ("Error"), MB_OK;
Dwerror = getLastError ();
Return False;
}
Return True;
}
Bool CSerial :: INITCOMMTIMEOUTS ()
{
CommTIMEOUTS COMMTIMEOUTS;
DWORD DWERROR;
// Get timeout parameters
Getcommtimeouts (HPORT, & COMMTIMEOUTS);
// Change the CommTIMEOUTS structure setting
CommTIMEOUTS.Readintervaltimeout = Maxdword;
CommTIMEOUTS.ReadtotalTimeoutMultiplier = 0;
CommTIMEOUTS.ReadtotalTimeoutConstant = 0;
CommTIMEOUTS.WRITETOTIMEOUTMULTIPLIER = 10;
CommTIMEOUTS.WRITETOTALTIMEOUTCONSTANT = 1000;
// Set the port timeout value
IF (! setcommtimeouts (hport, & commtimeout))
{
/ / Can't set the timeout value
MessageBox (NULL, Text ("Unable to set the time-out parameters),
Text ("Error"), MB_OK;
Dwerror = getLastError ();
Return False;
}
Return True;
}
The above class code is passed on Embedded Visual C 4.0 and ARM9-based Samsung S3C2410 development board (running Windows CE.NET 4.1).