Home

PIC16 MCU Serial Communication with PC Hardware and Software circuit

PIC16 MCU Serial Communication with P Hardware and Software

Abstract To introduce a usePIC16F84MCU and thePCserial communication, and gives the hardware interface circuit and communication source.
    Introduction
   American Microchip's PIC16 MCU CMOS technology is a new 8-bit microcontroller. Which, PIC16FXX microcontroller program memory is electrically erasable flash memory (flash), can modify the program several times, and even online programming. PIC16F83 and PIC16F84 chip data memory RAM in addition, there are 64 bytes of EEPROM, can be used as general or non-volatile data memory use, simple and convenient. It also has on-chip power-on reset delay circuit, the watchdog circuit. In addition, PIC16 MCU power consumption is very low, so it is a very suitable for use in a variety of portable devices the high cost of the microcontroller, and has been more widely used.
   However, the use of many compute-intensive, also requires the help of powerful computer data processing capabilities. This must be achieved through the communication circuit PIC MCU and reliable data transfer between computer. Some PIC16 microcontroller does not provide serial port, serial communication must therefore design their own hardware and communication software.
   Here are achieved by querying method for asynchronous serial communication. PIC16F84 microcontroller also given by the two I / O port analog 2-wire serial port hardware interface circuit, the program flow diagram, single chip microcomputer in the communication process and communication procedures.
    2 hardware method and circuit
    PIC16F84 program memory by the 1K × 14 of the flash (flash) memory structure, it is only 13 I / O port, a timer, microcontroller hardware and software in order to save resources as much as possible, using the following method of asynchronous Serial Communication .
   Shown in Figure 1, PIC16F84 in the 4MHz clock, using half-duplex mode, enabling serial 9600 baud asynchronous data communication, 1 stop bit, 8 data bits, no parity. Receive and transmit to the earlier low (normal mode), using software delay. To save space, the communication program in the microcontroller does not provide any handshake protocol, the user can according to their needs by adding software handshaking.
    Since PIC16F84 does not have a dedicated serial port, where the use of its I / O port to simulate the serial port function.
   PC Serial interface is consistent with EIA RS-232C standard interface to external bus standards. RS-232C uses a negative logic, the logic "1":-5V to-15V; logic "0": +5 V to +15 V. The level is CMOS: Logic "1": 4.99V, Logic "0": 0.01V; TTL level logic "1" and "0" were 2.4V and 0.4V. Therefore, with the RS-232C serial communication bus circuit when an external level shifter. At the transmitter with a drive to convert TTL or CMOS level to RS-232C level, at the receiver the receiver will use the RS-232C and then converted to a TTL level or CMOS level.
   MAXIM chosen here to be the company's MAX202E level conversion. MAX202E is MAXIM's Universal Serial Receive / Transmit driver chip. The peripheral circuit is simple, just four 0.1µF external capacitor can be shown in Figure 1.

Figure 2 receiver to send subroutine subroutine block diagram in Figure 3 Block Diagram
    3 PIC16F84 microcontroller communication program
  Figures 2 and 3, respectively, send and receive serial flow chart of a subroutine. Sent when the data is sent through the low end and maintain B DX seconds (9600 baud when 104µs) to send the start bit. B seconds each subsequent set or cleared through the end of the DX data sent. Where B is the duration of a (B = 1 / baud rate). Received, the data receiver to DR about every B / 2 second (9600 baud rate is 52µs) check to detect a start bit, if it detects the start bit, about 1.5B in the second (9600 baud rate to 156µs) after the detection of the first data bit, and then tested once every other second B data bits.
   The corresponding source code is as follows:
; To receive routine         
Rcvr

goto
Xnext    ; Bit count is not 0
          ; The next data bit sent
Xstop         
call
Delay    ; Delay B / 2 ?
call
Delay    ; Delay B / 2 ?
Bsf
RA, DX    ; Send stop bit
Retlw
0    ; Back
; Delay subroutine         
Delay         
movlw
12    ; 52µS delay
movwf
DCNT    ;
Dnext         
decfsz
DCNT    
goto
Dnext    ;
retlw 0
     ;

Figure 4 to read receive buffer data flow diagram

Serial port initialization process of Figure 5
    This approach works in the query. Programmer must complete a considerable portion of the communication status detection work, many of the details (even the characters in the communication process, including conversion of property) must be completed through the program code. The agreement between the query methods of communication dependence in particular. The two sides agreed on procedures for communication protocol to achieve a great influence on the degree of difficulty.
    Serial inquiry method, the general process of initializing the serial port as shown in Figure5.
   One thing to note is that the agreement under this method must meet the following conditions: the Party sent, Party B should send the action into the loop before the receiving state until after the character is received through the serial port read functionReadFilereturns value judgments out of the loop state.
   Meanwhile, the general in order not to make the system due to enter circulation waiting to receive the "death cycle" status, you can read the serial port of the artificial cycles, usually1,000~10,000times can be.
   Implementation platform of this procedure is VB4, this is an extremely flexible high-level language, it can easily introduce assembly language of thinking, the use of the GoTo statement is easily turned to the process control program, flexible and convenient.
    5 PC inside an instance of communication program
   Party convention is nowPCmachine, B is a single chip system (such as card readers). Communication format is set to2400baud,8data bits,1stop bit, no parity.
   Here is a good agreement instances of the application protocol, the protocol process in Figure6below.
   Following is a Party (PCmachine) Functions of several instances of the application.

Figure 6 process communication protocol
Private Function OpenThePort (cPort as String, cBaud as String, cParity
as String, cData as String, tStops asString) As Boolean 'Open the serial port of the sub-processes
   Dim lResult as Long
   Dim lHandle as Long
   Dim DCB_COMM as DCB
   Dim cDCBConfig as String
   lHandle = CreateFile (cPort, GENERIC_READ Or GENERIC_WRITE,
   0 &, 0 &, OPEN_EXISTING, 0 &, 0 &)
   If lHandle = -1 Then 'Failed to open serial port
       OpenThePort = False
       MsgBox "serial port may be in use by another application!"
       lResult = CloseHandle (lHandle) 'Close the serial port and then open the first
       If lResult = 0 Then
           OpenThePort
           Exit Function
       End If
   End If
   cDCBConfig.band = 2400 'Set DCB
   cDCBConfig.parity = None
   cDCBConfig.data = 8
   cDCBConfig.stop = 1
   lResult = BuildCommDCB (cDCBConfig, DCB_COMM) 'set by the user to configure a DCB structure
   If lResult = 0 Then
        OpenThePort = False
        MsgBox "Unable to create DCB Device Control Block"
        Exit Function
   End If
   lResult = SetCommState (lHandle, DCB_Comm) 'the actual set up a serial port DCB                   
   If lResult = 0 Then
        OpenThePort = False
        MsgBox "Unable to create DCB Device Control Block"
        Exit Function
   End If
   OpenThePort = True
End Function
Private Sub SendHand () 'sub-process sends handshake signals
   Dim Nchars As Long
   Static Readbuff As String * 1
   Static Writebuff As String * 1
   Dim lpDCB As DCB
   Dim lRet As Long
   Dim lHandle As Long
   Dim lpOverlapped As OVERLAPPED
   Dim RNum As Integer
   MsgBox "Please insert the serial port 2 on the reader!"
                48, "prompt"
   lHandle = OpenThePort (COMM1, 2400, None, 8,1)
   lRet = PurgeComm (lHandle, 1) 'clear output buffer
   lRet = PurgeComm (lHandle, 0) 'clear input buffer
   lRet = GetCommState (lHandle, lpDCB) 'get the state of communication port
Shand:
   Writebuff $ = Chr $ (& H8F)
   lRet = WriteFile (lHandle, Writebuff $, 1, Nchars, lpOverlapped)
                   'Get handshake signals into the serial buffer
      If lRet <= 0 Then
         MsgBox "Error sending operation, the card handshake signal is not sent successfully", 16
         GoTo Shand 'unsuccessful retransmission
      Else
          GoTo Qtest
      End If
   GoTo Shand
Qtest:
   Readbuff $ = "" 'Clear the buffer is empty
Do While lHandle 'port cyclic query
   RNum = 0 'set the pointer to read the serial number is 0
ReadAgain:
   lRet = ReadFile (lHandle, Readbuff $, 1, Nchars, lpOverlapped)
   If lRet <0 Then
      MsgBox "An error occurred while reading the response signal", 16
      End If
      If lRet = 0 Then
         If RNum> 1000 Then 'read-only serial port 1000, so as not to fall into infinite loop
             MsgBox
            "Card is not good or plug connected to the serial port on the card does not have!"
            GoTo CloseP
        End If
        RNum = RNum + 1
        GoTo ReadAgain
   End If
   If Hex $ (Asc (Readbuff)) <> Hex $ (& HFF) Then GoTo Shand
        'Back to the send code is not correct to send a handshake signal is returned
   Else
      Label1.Caption = "handshake signals are:"
        + Hex $ (Asc (Readbuff $))
      Msgbox "handshake correctly, have the right line"
      GoTo CloseP
   End If
Loop
CloseP: lRet = CloseHandle (lHandle)
           If lRet = 0 Then
               MsgBox "Close the serial communication port successfully"
                            48, "prompt"
           End If
End Sub
   To note here is: When PC-system communication with the MCU, the MCU data store (RAM) of data is hexadecimal, in the signal transmission line is the hexadecimal ASCII code number in binary form; The Windows system using the ANSI code, ANSI code only the first 126 ASCII codes with the same. That is, in Win95 is to receive the number of ASCII code hex string can be converted to ANSI code under Win95 and then restore in hexadecimal.
   Specifically as: Code $ = Hex $ (Asc (Readbuff $))
   In addition, because 32-bit API function parameter data type change, all shaping parameters are changed to long integer (Long) to support 32-bit processing, which is in the set, especially when the return value.
6 Conclusion
   More hardware and software in our practice to achieve a more satisfactory results. Software saves the cost of hardware, and through the PIC16F84 microcontroller system and PC, both to increase the communication software handshake, to the purpose of data validation software, access to higher communication reliability.
References
1 MICROCHIP CO. PIC16/17 MICROCO-NTROLLER DATA BOOK. 1995/1996  
2 Dong magnitude. PIC16CXX MCU applications. Gao Qi Electronic Science and Technology Corporation, 1996.10
Such as the United States Darwin Boyle 3. Visual Basic 4 Developer's Guide. Beijing: Mechanical Engineering
  Industry Press, 1997
    4 Win95 serial communication mechanism and principle port querying
   The DOS system is mainly used in response to interrupt the work. PC serial communication program block most of the INT14H use its BIOS interrupts, to check the serial port asynchronous serial communication manner.
    Windows system function that includes support for interrupt communication. Win95 system has opened up communications equipment for each user-defined input and output buffers (ie, read / write buffers), data communication port by the system out of the background to complete. Simply complete the application input and output buffers operating on it. The actual process is a character to each receiver generates a low-level hardware interrupt, Win95 system has made the serial driver to control, and received character into the input data buffer. And then return control to the running application. If the input buffer is full, the serial driver with the current definition of the flow control mechanism notifies the sender to stop sending data. The data in the queue by "FIFO" order processing.
   (1) set by the agreement and open the serial port initialization, this is notice of the application requires the Windows serial port, and block other applications so that they can not use this serial port.
   (2) configure the serial port.
   (3) from the serial port to transfer data and verify the transfer process.
   (4) does not require the serial port, close the serial port. The release of the serial port for other applications.
In these four steps, the main focus of code (3) steps.
   Serial query method is a major work in the query mode of implementation. When the communication program work in the "query" mode, you can not consider the Win95 process and thread issues. There is only serial data, read the serial buffer on it, as shown in Figure 4. Under this method to determine the time to read the serial port, the handshake protocol and software implementation of error correction is the programmer should be a major consideration.