in the field of industrial control (such as DCS system), often involving serial communication problems. In order to achieve single-chip computer and data exchange between people with a variety of methods to achieve strings lines of communication, such as the adoption of DOS assembly language or C language, but in the Windows environment, but there are still some difficulties and shortcomings. In Windows The dominant operating system has been the case under (not to mention some of the fundamental systems such as DOS does not support Windows2000) to develop Windows Serial communication technology environment has become increasingly important. VC 6.0 is Microsoft in 1998, launched a development environment, its powerful features and friendly interface, 32-bit object-oriented programming and the flexibility of Active X by the majority of software developers in favor, been widely used in various fields. VC the application development of the current serial communication usually follows several ways: First, the use of the Windows API communication functions; Second, the use of the VC's standard communications function inp, inpw, inpd, outp, outpw, outpd such as direct-to-serial operate; Third, the use of Microsoft Visual C communications control (MSComm); Fourth, the use of third-party prepared by the communications category. Over the first several ways to use a far more complicated, but more complex, a higher degree of specialization, the use of the more difficult; the need for a second solution The principle structure of the hardware; third method appears to be more simple, just a simple serial port for configuration, but hard to understand because of the use of the VARIANT type of use of capacity is not very easy; The fourth way is to use a Serial communication for the CSerial category (this category is provided by a third party), as long as this kind of understanding of a few members of the function, you can easily make use. I use CSerial category easily realized in the fixed-EBM aerosol fire-extinguishing system partition starter (single-chip system) and PC communications. The following examples will be combined, serial communication to achieve given the several ways.
1 Windows API function communication methods
and communication The Windows API function 26, but the principal has:
CreateFile () with "comn" (n for the serial number) as the file name can open a serial port. ReadFile () serial time. WriteFile () to write serial port. CloseHandle () to close serial port handle. should pay attention to initialize CreateFile () function in a way that is set to share serial port 0, for the serial port can not share equipment, and other paper-like reading and writing. API is given below is the source code.
1.1 routines send the
/ / global variables statement
HANDLE m_hIDComDev; OVERLAPPED m_OverlappedRead, m_Over lappedWrite;
/ / initialize serial
void CSerialAPIView:: OnInitialUpdate () ( CView:: OnInitialUpdate (); Char szComParams; DCB dcb; Memset(&m_OverlappedRead, 0, sizeof (OVERLAPPED)); Memset(&m_OverlappedWrite, 0, sizeof (OVERLAPPED));
m_hIDComDev = NULL; m_hIDComDev = CreateFile ( "COM2", GENERIC_READ GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL FILE_FLAG_OVERLAPPED, NULL);
if (m_hIDComDev == NULL) ( AfxMessageBox (" Can not open serial port! "); goto endd; )
memset(&m_OverlappedRead, 0, sizeof (OVERLAPPED)); memset(&m_OverlappedWrite, 0, sizeof (OVERLAPPED)); COMMTIMEOUTS CommTimeOuts; CommTimeOuts.ReadIntervalTimeout = 0 × FFFFFFFF; CommTimeOuts.ReadTotalTimeoutMultiplier = 0; CommTimeOuts. ReadTotalTimeoutConstant = 0; CommTimeOuts.WriteTotalTimeoutMultiplier = 0; CommTimeOuts.WriteTotalTimeoutConstant = 5000; SetCommTimeouts(m_hIDComDev, &CommTimeOuts); Wsprintf (szComparams, "COM2: 9600, n, 8, 1");
m_OverlappedRead. HEvent = CreateEvent (NULL, TRUE, FALSE, NULL); m_OverlappedWrite. HEvent = CreateEvent (NULL , TRUE, FALSE, NULL);
dcb. DCBlength = sizeof (DCB); GetCommState(m_hIDComDev, &dcb); dcb. BaudRate = 9600;
dcb. ByteSize = 8; unsigned char ucSet;
ucSet = (unsigned char) ((FC_RTSCTS&FC_DTRDSR) != 0); ucSet = (unsigned char) ((FC_RTSCTS&FC_RTSCTS) ! = 0); ucSet = (unsigned char) ((FC_RTSCTS&FC_XONXOFF) ! = 0);
if (!SetCommState(m_hIDComDev, &dcb) ! SetupComm (m_hIDComDev, 10000,10000) m_OverlappedRead. HEvent == NULL m_OverlappedWrite. HEvent == NULL) ( DWORD dwError = GetLastError (); if ( m_OverlappedRead. hEvent! = NULL) CloseHandle (m_OverlappedRead. hEvent); if (m_OverlappedWrite. hEvent! = NULL) CloseHandle ( m_OverlappedWrite. hEvent);
CloseHandle (m_hIDComDev); ) endd: ; )
/ / send data
void CSerialAPIView:: OnSend () ( char szMessage = "thank you very much";
DWORD dwBytesWritten;
for (int i = 0; i<sizeof(szMessage); i++) ( WriteFile(m_hIDComDev, (LPSTR)&szMessage[i], 1, &dwBytesWritten, &m_OverlappedWrite);
if (WaitForSingleObject (m_OverlapperWrite, hEvent, 1000)) dwBytesWritten = 0; else ( GentOverlappedResult(m_hIDComDev, &m_OverlappedWrite, &dwBytesWritten, FALSE); m_OverlappedWrite. Offset = dwBytesWritten; )
dwBytesWritten; ) )
1.2 to receive routine
DCB ComDcb; / / device control block
HANDLE hCom; / / global handle
hCom = CreateFile ( "COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hCom == INVALID_HANDLE_value) ( AfxMessageBox ( "Can not open serial port"); ) else ( COMMTIMEOUTS CommTimeOuts; SetCommMask (hCom, EV_RXCHAR); SetupComm (hCom, 4096, 4096); / * Set up to send and receive buffer size 4K * / PurgeComm (hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); / / send and receive clearance of the buffer zone
/ / following the initial Variable structure CommTimeOuts, setting the parameters of overtime CommTimeOuts.ReadIntervalTimeout = 0 × FFFFFFFF;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0; CommTimeOuts.ReadTotalTimeoutConstant = 4000; CommTimeOuts.WriteTotalTimeoutMultiplier = 0; CommTimeOuts.WriteTotalTimeoutConstant = 4000; SetCommTimeouts(hCom, &CommTimeOuts ); // ComDcb.DCBlength = sizeof (DCB); GetCommState( hCom, &ComDcb ); // ComDcb.BaudRate = 9600; / / baud rate ComDcb.ByteSize = 8; / / data- ComDcb.Parity = 0; / * Check 0 ~ 4 = no, odd, even, mark, space * / SetCommState(hCom, &ComDcb ) ;
) / / Set the new parameters of the communications can be used to receive thread or timer, and so on
DWORD dRead, dReadNum;
unsigned char buff;
dRead=ReadFile(hCom, buff, 100, &dReadNum, NULL); // 100
/ / dReadNum for The actual number of bytes received
2 port use of direct operate function
in this way is the main function of the two ports _inp (), _outp () for the realization of string I read and write, read port function as a prototype:
int _inp (unsigned shot port)
the Function to read a bit from the port, port number for 0 ~ 65535.
to write a prototype for the function of ports:
int _outp (unsigned shot port, int databyte)
the functions assigned to the port written into a byte.
different address of the computer serial port may not be the same, through Serial control and transceiver register for reading and writing, can be flexible serial communication function, which will involve specific hardware to discuss the more complex pieces of circuitry, not to go into details here.
3 MSComm control
MSComm control is the development of Microsoft's exclusive control communications, a package serial All the features, easy to use, but in practical applications to be careful of their property configuration. The following detailed detailed description of such applications .
3.1 MSComm control the properties of
CommPort: serial port settings, the type of short :1-comm1 2-comm2. Settings: Set serial communication parameters, the type of CString: B baud rate, P parity (N-free check, E dual check, O odd check), D-byte effective The median, S-stop. PortOpen: serial port settings or to return to the state, type BOOL: TURE open, FALSE closed. InputMode: receiving from the buffer zone set up to read the data format, the type of long: 0-Text 1-Bin. Input: receiving from the buffer to read data types VARIANT. InBufferCount: to receive the buffer zone in the number of bytes, type: short. InBufferSize : Receive buffer size, type: short. Output: to send data into the buffer zone, type: VARIANT. OutBufferCount: send the buffer zone in the number of bytes, type: short. OutBufferSize: send buffer size, type: short. InputLen: set to return to Input or read the number of bytes, type: short. CommEvent: serial port, type: short.
3.2 sample program
initialization serial
if (! M_comm.GetPortOpen ()) m_comm.SetPortOpen (TURE); / * Open the serial port * /
m_comm.SetSettings ( "4800 , n, 8,1 "); / * serial port parameters set * / m_comm.SetInputMode (0); / * set TEXT input buffer * / m_comm.SetRthresHold (1); / * each character is excited to receive a OnComm () events * /
receive data
m_comm.SetInputLen (1); / * read every time a character VARINAT V1 = m_comm. GetInput ();
/ * read characters * /
m_V1 = V1.bstrval;
Send characters m_comm.SetOutput (Colevariant ( "Hello"); / * send "Hello" * /
3.3 attention
SetOutput can transfer text data or binary data. SetOutput using text data transfer method, a definition must include a string of Variant. send binary data, we must send a byte array that contains the Variant to the Output properties. Under normal circumstances, if an ANSI string to send applications , can Data sent in the form of text. If you send contain embedded control characters, Null characters, and other data, it is necessary to send a binary form. Wang aroused the attention of readers here, pen those who have been at fault here.
4 VC-type CSerial
4.1 Serial communication CSerial About
Cserial by MuMega Technologies offers a free class of VC can be easy to achieve serial communication. Following is a description of some of these definitions.
class CSerial ( public: CSerial (); ~ CSerial (); BOOL Open (int nPort = 2, int nBaud = 9600); BOOL Close (void); int ReadData (void *, int); int SendData (const char *, int); int ReadDataWaiting (void); BOOL IsOpened (void) (Return (m_bOpened);) protected: BOOL WriteCommByte (unsigned char ); HANDLE m_hIDComDev; OVERLAPPED m_OverlappedRead, m_OverlappedWrite; BOOL m_bOpened;
)
4.2 serial communication function of the members of the Class Cserial About
1. CSerial:: Cserial is the type of structure Function without parameters, responsible for the initialization of all the members of the class of variables.
2. CSerial:: Open the members of the function to open communications port. With two parameters, is the first port, RMS is 1-4 and the second parameter is the baud rate, a return to the cloth volume of Seoul.
3 . CSerial:: Close close the communications port function. Class destructor call this function, so there is no need for explicit call this function.
4. CSerial:: SendData function to data from the buffer zone wrote a serial port . It brought the first parameter is a pointer of the buffer zone, which contains the information to be sent; this function has returned to port wrote the actual number of bytes.
5. CSerial:: ReadDataWaiting function in the communications port to wait for the return of the data in the buffer zone, with no parameters. 6. CSerial:: ReadData function from the port to receive data into the buffer time. The first parameter is a void * pointer of the buffer zone, the data will be placed in the buffer zone; second Senate Is a whole number value, given the size of the buffer zone.
4.3 Application category VC an example of
1. Fixed aerosol fire-extinguishing system EBM About
fixed EBM aerosol fire-fighting equipment is to start district EBM for fire-fighting equipment designed for automatic control equipment. With the two-wire temperature, supporting the use of smoke detectors, when the supervisor test site when the fire occurred, the detector signal sent to the boot partition, after the judge issued by the logic of sound, light and alarm, the delay after the automatic fire-fighting equipment to start EBM. In order to facilitate the fire after the accident, the need for major fire incidents and critical operations records, records from the PC should be machine-readable out; PC control function, system-wide coordination of the work, the involve communications. Starters this case using RS-485 communication interface, the system mainly from the network, PC to PC machine.'s Specific communication protocol: (1) place under the plane up from time to time to send records of the incident; (2) response sent , That is, PC-to-date case records to be confidential, and the transmission time before when, PC machine to send an order under the crew received orders to-date records to the PC; (3) other PC send a command such as school, start and stop , Hand / automatic, and so on.
2. Communication Programming
part of the PC program
(1) command to send the word procedure, the following code
void CCommDlg:: OnSend () (
CSerial Serial;
/ / serial-type structure, the initial Serial port of
if (Serial.Open (2,9600)) / / if-1
/ / open the serial port 2, for the baud rate 9600bps ( static char szMessage = "0";
/ / command code (defined a variety of command code) int nBytesSent; int count = 0; resend:
nBytesSent = Serial.SendData (szMessage, strlen (szMessage));
/ / Send command code char rdMessage; if (Serial.ReadDataWaiting ()) / / if-2 ( Serial. ReadData (rdMessage, 88); / / rdMessage accept the definition of bytes of storage areas for the global variable / /
if ((rdMessage!=0x7f)&&(count<3)) ( count; goto resend )
if(count>=3) MessageBox ( "Send the word failure of command"); )
else / / if-2 MessageBox ( "receive data error");
) else / / if-1 MessageBox ( "Serial I failed to open "); )
under-machine communication program:
# include<reg51.h> # include<stdlib.h> # include<stdio.h>
# define count 9 # define com_code 0x00 # define com_code1 0xff
unsigned char buffer [count]; int po, year, month, date, hour; int minute, second, recordID; int sum;
main () ( ...
/ * Initialize the timer and serial port * /
TMOD = 0 × 20; TH1 = 0 × fd; TR1 = 0 × 01; ET1 = 0 × 00; ES = 1; EA = 1;
/ * send data to be sent to buffer * /
buffer = 0 × ff; / / signature data buffer = count 1; / / data length of buffer = year; / / In buffer = month ; / / buffer = date; / / day buffer = hour; / / When buffer = minute; / / sub- buffer = second; / / seconds buffer = recordID; / / events,
for (po = 0; po<count;po++) sum = buffer [po];
buffer = sum; / / Check and ...
)
/ * Send interruption of service program * /
void send (void) interrupt 4 using 1 ( int i;
RI = 0; EA = 0; do ( for(i=0;i<=count;i++) ( SBUF = buffer [i]; / / send data and the checksum / / while (TI == 0); TI = 0; ) while (RI == 0); RI = 0; ) while (SBUF! = 0); / / host does not receive the right to re-send / /
EA = 1;
Return; )
5 application summary of
according to the different needs, choose the right way. We have chosen to use VC-type realization of the PC and next-bit machine serial communication method is simple to use, convenient procedures for the preparation of characteristics. After more than six months EBM fire-extinguishing system used in the case, the methods to achieve stable and reliable operation of the system, should be promoted as a simple method of communication.
|