Implementation between PCs and MCUs with VC ++ 6.0

zhaozj2021-02-11  240

Implementing serial communication between PC and single-chip microcontrollers with VC 6.0 Hunan University (Changsha 410082) Hunan University (Changsha 410082) is in detail in WINDOWS environment, and several serials in the Windows environment. The communication method gives a PC program written in Visual C 6.0 and a single-chip communication program written in C51. The actual application system is running stable and reliable. Key words Visual C serial communication

Industrial Control areas (such as DCS systems) often involve serial communication issues. In order to realize data exchange between microcomputer and microcontrollers, people use a variety of different methods to implement serial communication, such as the assembly language or C language under DOS, but there are some difficulties and shortcomings in the Windows environment. In the case of the dominant dominance of the Windows operating system (not to mention, some systems do not support DOS such as Windows2000) Developing Windows Environments, serial communication technology is increasingly important. VC 6.0 is a development environment launched in 1998 with its powerful function, friendly interface, 32-bit object-oriented programming and Active X's flexibility, and is favored by software developers. Widely used in various fields. Application VC development serial communication is currently usually the following methods: First, use the Windows API communication function; Second, use the VC standard communication function _inp, _inpw, _inpd, _outp, _outpw, _outpd, etc. to operate directly; three It is a communication control (MSCOMM) using Microsoft Visual C ; four is the communication class written by third parties. In the above methods, the first kind of use is wide, but due to the more complex, the degree of specialization is high, it is difficult to use; the second need to understand the principle of hardware circuit structure; the third method seems to be simple, only need The serial port is simple, but it is not easy to use because of the use of a puzzled Variant class; the fourth method is to use a CSerial class for serial communication (this class is provided by a third party), as long as it is understood Several member functions of the type can be convenient. The author uses the CSerial class to facilitate communication in a fixed EBM aerosol fire extinguishing system partition starter (single chip system) and host machine. The following will be combined with examples to give several methods for realizing serial communication. 1 Windows API communication function method has 26 Windows API functions related to communication, but mainly related to: createfile () uses "COMN" as the file name as the file name. ReadFile () reads the serial port. Writefile () write serial port. CloseHandle () Close the serial port handle. Atternuration When you should pay attention to the serial port sharing mode in the createfile () function, the serial port is a non-shared device, and the other is similar to the general file reading. The source code implemented by the API is given below.

1.1 // declaration transmitted routine global variable HANDLE m_hIDComDev; OVERLAPPED m_OverlappedRead, m_Over lappedWrite; // initialize the serial port void CSerialAPIView :: OnInitialUpdate () {CView :: OnInitialUpdate (); Char szComParams [50]; 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_OVERLAPPED . Read 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 [20] = "Thank you very much"; dword dwbyteswritten; for (int i = 0; I

NO, ODD, Even, Mark, Space * / setcommstate (hcom, & comdcb);} // Set new communication parameters receive DWord Dread, DREADNUM; Unsigned Char Buff [200]; DREAD = Readfile (HCOM) , BUFF, 100, & DREADNUM, NULL; // Receive 100 characters, // DREADNUMs for the actual receiving byte number 2 Take the port function directly to use two port functions _inp (), _outp () Implement the read and write to the serial port, where the prototype of the port port function is: int _inp (unsigned Shot Port) This function reads a byte from the port, and the port number is 0 ~ 65535. The function prototype of the port port is: int _outp (unsigned shot port, int database "This function writes a byte to the specified port. Different computer serial port addresses may not be the same. By reading and writing to the control and transceiver registers to the serial port, the flexible serial communication function can be realized, and the discussion involving specific hardware circuits is more complicated, and will not be described here. 3 MSCOMM Control MSCOMM control is a dedicated communication control developed by Microsoft, encapsulates all functions of the serial port, which is very convenient, but carefully configures its properties in practical applications. This type of application is described in detail below. 3.1 Attributes of MSCOMM Controls CommPort: Set the serial number, Type Short: 1-COMM1 2-COMM2. Settings: Set the serial port communication parameters, type cstring: B baud rate, P parity (N no check, E duplicate check, O rating), D byte effective bits, S stop bit. Portopen: Set or return to the serial port status, type bool: Ture is open, false is closed. INPUTMODE: Sets the format of the data from the receive buffer, the type long: 0-text 1-bin. INPUT: Reads data from the received buffer, type Variant. InbufferCount: The number of bytes in the buffer is received, and the type: short. Inbuffersize: The size of the buffer is received, the type: short. Output: Write the data to the send buffer, type: Variant. OutbufferCount: Send the number of bytes in the buffer, type: short. Outbuffersize: Send the size of the buffer, type: short. Inputlen: Set or return the number of bytes read from INPUT, Type: Short. Commevent: Serial Events, Type: Short.

3.2 Program Example Serial Port Initialization IF (! M_comm.getPortopen ()) m_comm.setportopen (TURE); / * Open Serial Port * / m_comm.setSettings ("4800, N, 8, 1"); / * Serial port parameter setting * / m_comm .SetInputMode (0); / * Set the Text buffer input mode * / m_comm.sethreshold (1); / * Excorple the oncomm () event * / receive data m_comm.setInputlen (1) each time each receives a character. Read a character varinat v1 = m_comm.getinput (); / * Read characters * / m_v1 = v1.bstrval; send characters m_comm.setoutput (Colevariant ("Hello"); / * Send "Hello" * / 3.3 Note SetOutput Method can transmit text data or binary data. Transport text data with setOutput method, you must define a variant that contains a string. Send binary data, you must pass a Variant to Output property containing byte array. Under normal circumstances, if you send one ANSI string to the application, can be sent in the form of text data. If you send data containing embedded control characters, NULL characters, etc., you should send it in binary form. This point is that the reader is noted, and the author has made mistakes. 4 VC class CSERIAL 4.1 Serial Communication CSERIAL Introduction CSERIAL is a free VC class provided by Mumega Technologies, which is convenient to serial communication. The following is the description of this class. Class CSerial {public: cserial (); ~ CSerial (); BOOL Open (int NPORT = 2, INT NBAUD = 9600); Bool Close (void); int readdata (invication); int tentdatawaiting (void); Bool Isople (void) {RETURN (M_Bopened);} protected: BOOL WRITECOMMBYTE (Unsigned Char); Handle M_ Hidcomdev; Overlapped M_Overlapped, M_Overlapped;} 4.2 Serial Communication CSERIAL Member Function Introduction 1. CSerial :: CSerial is a class constructor, without parameters, responsible for initializing all kinds of member variables. 2. CSERIAL :: Open This member function opens the communication port. Bring two parameters, the first is the number, the effective value is 1 to 4, the second parameter is the baud rate, returns a booler. 3. CSERIAL :: Close function Turn off the communication port. The classification function calls this function, so this function can be invoked without explicitly. 4. CSERIAL :: Senddata function writes the data from a buffer to the serial port. The first parameter it belongs is the buffer pointer, which contains the information to be sent; this function returns the number of actual bytes written to the port. 5. cserial :: readdataWaiting function Returns the data waited in the communication port buffer without parameters. 6. CSERIAL :: ReadData function The buffer read data from the port. The first parameter is a VOID * buffer pointer, the data will be placed in the buffer; the second parameter is a hinge value to give the buffer size.

4.3 An example of applying VC class 1. Fixed EBM aerosol fire extinguishing system Introduction The fixed EBM aerosol fire extinguishing device partition launcher is an automatic control device designed for EBM fire extinguishing means. It can be used with two-wire thermos, and the smoke detector is used. When the monitoring site has fire, the detector issues an electrical signal to the partition launcher. After logic judgment, the light alarm, the light alarm, the delay is automatically launched EBM fire Device. In order to facilitate the analysis of the fire accident, it is necessary to record important fire events and key operations. The record should be read from the PC; the PC function control, coordinates the entire system, which involves communication. In this example, the launcher uses the RS-485 communication interface, the system is the main source network, and the PC is a host computer. The specific communication protocol is: (1) Event of the recording in the next machine; (2) A answer transmission, that is, the PC should get the latest event record, and the transfer time is not arriving, the PC sends a command, after receiving the command Put the latest record to the host computer; (3) The upper machine sends other commands, such as school, start, stop, hand / automatic, etc.

2. Communication program design Some upper host program (1) Send a command word program, code as follows void ccommdlg :: Onsend () {cserial serial; // Constructs serial port class, initializing the serial port IF (Serial.Open (2,9600) ) // IF-1 // Open Serial port 2, baud rate is 9600bps {static char szmessage [] = "0"; // command code (can define various command code) int NBytessent; int count = 0; Resend: nbytessent = serial.senddata (Szmessage, Strlen); // Send command code char RDMESSAGE [20]; if (serial.readdatawaiting ()) // IF-2 {serial.readdata (RdMessage, 88); // RdMessage defines the receiving byte memory area for global variables // if ((RDMessage [0]! = 0x7f) && (count <3)) {Count ; goto resend} if (count> = 3) MessageBox ("Send Command word failed ");} else // IF-2 MessageBox (" Receive Data Error ");} Else // IF-1 MessageBox (" Serial Oral Open Fail ");} Underline Communication Program: #include #include #include #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 () {... / * initializing serial port and timer * / tmod = 0 × 20; TH1 = 0 × FD; TR1 = 0 × 01; ET1 = 0 × 00; ES = 1; EA = 1; / * Waiting to send data to send buffer * / buffer [0] = 0 × ff; // data signage buffer [1] = count 1; // data length buffer [2] = year; // year Buffer [3] = month; // month buffer [4] = DATE; / / day buffer [5] = Hour; // time buffer [6] = minute; // points buffer [7] = second; // second buffer [8] = RecordID; // event number For (PO = 0; PO

转载请注明原文地址:https://www.9cbs.com/read-4333.html

New Post(0)