4780 views|3 replies

1379

Posts

0

Resources
The OP
 

Application skills/Software and hardware implementation of serial communication between PIC16 series microcontroller and PC [Copy link]

Abstract: This paper introduces a method of using PIC16F84 microcontroller to realize serial communication with PC, and gives its hardware interface circuit and communication source program.

Keywords: asynchronous serial communication sending and receiving VB4 Win95 serial port query method Author: Department of Electronics, Department of Biomedical Engineering, Xi'an Fourth Military Medical University (710032) Jiao Chunchen Martin Li Hongyi
1 Introduction

The PIC16 series microcontroller of Microchip Company of the United States is a new type of 8-bit microcontroller with CMOS technology. Among them, the program memory of the PIC16FXX microcontroller is an electrically erasable flash memory (flash), which can modify the program many times and even be programmed online. In addition to RAM, the on-chip data memory of PIC16F83 and PIC16F84 also has 64 bytes of EEPROM, which can be used as a general or non-volatile data memory, which is simple and convenient. It also has on-chip power-on reset, delay circuit, watchdog circuit, etc. In addition, the PIC16 series microcontroller has extremely low power consumption, so it is a cost-effective microcontroller that is very suitable for use in various portable devices and has been increasingly widely used.
However, in many applications that require a lot of calculations, it is also necessary to rely on the powerful data processing capabilities of the microcomputer. In this way, reliable data transmission between the PIC microcontroller and the microcomputer must be achieved through a communication circuit. Some PIC16 microcontrollers do not provide serial ports, so serial communication must be achieved through self-designed hardware circuits and communication software.
The following introduces the method of realizing asynchronous serial communication using the query method. At the same time, the hardware interface circuit, program flow chart, communication program within the microcontroller and communication program within the microcomputer are given to use the two I/O ports of the PIC16F84 microcontroller to simulate the 2-wire serial port.

2 Hardware Implementation Method and Circuit

The program memory of PIC16F84 is composed of 1K×14 flash memory. It has only 13 I/O ports and 1 timer. In order to save the software and hardware resources of the microcontroller as much as possible, the following asynchronous serial communication implementation method is adopted.
As shown in Figure 1, PIC16F84 uses half-duplex mode at a 4MHz clock to achieve asynchronous serial data communication at a baud rate of 9600, 1 stop bit, 8 data bits, and no check bit. Receiving and sending are low-order first (general mode), and software delay is used. In order to save space, no handshake protocol is provided in the communication program in the microcontroller. Users can add handshake methods in the software according to their needs.

Since PIC16F84 itself does not have a dedicated serial port, its I/O port is used here to simulate the function of the serial port.
The serial interface of the PC is an external bus standard interface that complies with the EIA RS-232C specification. RS-232C uses negative logic, that is, logic "1": -5V to -15V; logic "0": +5V to +15V. The CMOS level is: logic "1": 4.99V, logic "0": 0.01V; the logic "1" and "0" of the TTL level are 2.4V and 0.4V respectively. Therefore, when using the RS-232C bus for serial communication, an external circuit is required to achieve level conversion. A driver is used at the sending end to convert the TTL or CMOS level to the RS-232C level, and a receiver is used at the receiving end to convert the RS-232C level to the TTL or CMOS level.
Here, MAXIM's MAX202E is selected for level conversion. MAX202E is a general-purpose serial receiving/transmitting driver chip of MAXIM. Its peripheral circuit is simple and only requires four 0.1μF capacitors to be connected externally, as shown in Figure 1.

images/yyjq8101.GIF (2374 bytes)

Figure 1 Interface schematic diagram

3 Design of communication program in PIC16F84 microcontroller

 

jc1.GIF (4938 bytes)

Figure 2 Receive subroutine diagram Figure 3 Send subroutine diagram

Figures 2 and 3 are the subroutine flow charts for serial transmission and reception, respectively. When transmitting, the start bit is sent by making the data transmission terminal DX low and maintaining it for B seconds (104μs at 9600 baud rate). Then the data is sent out every B seconds by setting or clearing the DX terminal. Here B refers to the duration of one bit (B=1/baud rate). When receiving, the data receiving terminal DR queries approximately every B/2 seconds (52μs at 9600 baud rate) to detect the start bit. If the start bit is detected, the first data bit is detected after approximately 1.5B seconds (156μs at 9600 baud rate), and then the other data bits are detected every B seconds.
The corresponding source program is as follows:

;Receive subroutine
Rcvr

clrwdt

; Clear the watchdog in the film
;Timer

btfsc

RA, DR ; Detection start position

goto

Rcvr ; Start bit not detected

movlw

8 ; Start bit detected

movwf

R_CNT ; 8 data bits
Rnext

call

Delay ; Delay B/2 seconds

bcf

STATUS,C ; Clear carry flag

rrf

RevReg ; LSB first

btfsc

RA,DR ; This bit is 0

 

; still 1

bsf

RcvReg,MSB ; is 1

call

Delay ; Delay B/2 seconds

decfsz

R_CNT

goto

Rnext

retlw0

;return
; Send subroutine
Xmtr

clrwdt

; Clear the watchdog in the film
;Timer

movlw

8 ;The number of bits sent is 8

movwf

X_CNT

bcf

RA, DX ; Send start bit
Xnext

call

Delay ; Delay B/2 seconds

call

Delay ; Delay B/2 seconds

rrf

XmtReg ; LSB first

btfsc

STATUS,C ; Detection will be sent

 

; Data bits

bsf

RA,DX ; Data bit is 1

btfss

STATUS, C

bcf

RA, DX ; Data bit is 0

decfsz

X_CNT ; If the bit count is 0
; Send stop bit

goto

Xnext ; The bit count is not 0
; then send the next data bit
Xstop

call

Delay ; Delay B/2 seconds

call

Delay ; Delay B/2 seconds

Bsf

RA,DX ; Send stop bit

Retl

0 ;return
; Delay subroutine
Delay

movlw

12 ;52μS delay

movwf

DCNT ;
Dnext

decfsz

DCNT

goto

Dnext ;

retlw 0

;

4 Win95 serial communication mechanism and the principle of serial port query method

Commonly used DOS systems mainly work in response to interrupts. Most PC serial communication programs use the INT14H interrupt of their BIOS block to complete asynchronous serial communication by querying the serial port.
Windows system functions include communication support interrupt functions. Win95 system opens up user-defined input and output buffers (i.e. read/write buffers) for each communication device, and data entering and exiting the communication port are completed by the system background. The application only needs to complete the operation of the input and output buffers. The actual process is that a low-level hardware interrupt is generated every time a character is received, and the serial driver in the Win95 system takes control and puts the received character into the input data buffer. Then the control is returned to the running application. If the input buffer data is full, the serial driver uses the currently defined flow control mechanism to notify the sender to stop sending data. The data in the queue is processed in the order of "first in, first out".
(1) Initialize and open the serial port according to the protocol settings. This notifies Windows that this application needs this serial port and blocks other applications so that they cannot use this serial port.
(2) Configure this serial port.
(3) Transmit data back and forth on the serial port and perform verification during the transmission process.
(4) When the serial port is not needed, close it. That is, release the serial port for use by other applications.
Among these four steps, the main program code is concentrated in step (3).
The serial port query method is an implementation method that mainly works in the query mode. When the communication program works in the "query" mode, the process and thread issues of Win95 can be ignored. Only when there is data in the serial port, read the serial port buffer, as shown in Figure 4. Under this method, determining the timing of serial port reading, the implementation of handshake protocol and software error correction are the main issues that programmers should consider.

 jimages/yyjq8103.GIF (1145 bytes)

Figure 4 Flow chart of reading receive buffer data

 

jc3.GIF (1515 bytes)

Figure 5 Serial port initialization process

Since this method mainly works in the query mode, the programmer must complete a considerable part of the communication status detection work, and many details (even including the conversion of character attributes during the communication process) must also be completed through program code. This query method is particularly dependent on the protocol of the two communicating parties. The agreement of the communication protocol between the two parties has a great influence on the difficulty of program implementation.
In the serial port query method, the general serial port initialization process is shown in Figure 5.
It is worth noting that the agreement of the protocol under this method must meet the following conditions: that is, when Party A sends, Party B must enter the loop receiving state before Party A sends, and jump out of the loop state after receiving the character by judging the return value of the serial port reading function ReadFile .

At the same time, in order to prevent the system from entering a "dead loop" state due to the loop waiting for reception, the number of loops for reading the serial port can be set manually, usually 1000 to 10000 times.
The implementation platform of this program is VB4, which is an extremely flexible high-level language. It can easily introduce the thinking of assembly language and use its GoTo turn statement to conveniently control the flow of the program, which is flexible and convenient.

5 Examples of PC internal communication programs

It is now agreed that Party A is a PC and Party B is a single-chip microcomputer system (such as a card reader). The communication format is set to 2400 baud rate, 8 data bits, 1 stop bit, and no parity check.
The following is a program example with an agreed communication protocol . The protocol flow is shown
in Figure 6. The following are program examples of several sub-functions of Party A ( PC ).

jc4.GIF (2223 bytes)

Figure 6 Communication protocol flow

Private Function OpenThePort(cPort as String, cBaud as String, cParity

as String, cData as String, tStops asString) As Boolean ' Open the sub-process of the serial port

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 the serial port

OpenThePort = False

MsgBox "The serial port may be occupied by another application!"

lResult = CloseHandle (lHandle) 'Close the serial port first and then open it

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) 'Configure a DCB structure according to user settings

If lResult = 0 Then

OpenThePort = False

MsgBox "Unable to create DCB device control block"

Exit Function

End If

lResult = SetCommState (lHandle, DCB_Comm) 'Actually set the DCB of a serial port

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 for sending 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 plug the card reader into serial port 2!",

48, "Prompt Window"

lHandle = OpenThePort(COMM1,2400,None,8,1)

lRet = PurgeComm(lHandle, 1) 'Purge the output buffer

lRet = PurgeComm(lHandle, 0) 'Clear input buffer

lRet = GetCommState (lHandle, lpDCB) 'Get the status of the communication port

Shand:

Writebuff$= Chr$(&H8F)

lRet = WriteFile (lHandle,Writebuff$,1,Nchars,lpOverlapped)

'Send handshake signal into serial port buffer

If lRet <= 0 Then

MsgBox "Send operation error, card handshake signal was not sent successfully", 16

GoTo Shand 'Resend if unsuccessful

Else

GoTo Qtest

End If

GoTo Shand

Qtest:

Readbuff$ = " " 'Clear the buffer to empty

Do While lHandle 'Loop query serial port

RNum = 0 'Set the pointer of serial port reading times to 0

ReadAgain:

lRet = ReadFile(lHandle, Readbuff$, 1, Nchars, lpOverlapped)

If lRet < 0 Then

MsgBox "Error reading response signal", 16

End If

If lRet = 0 Then

If RNum > 1000 Then 'Only read the serial port 1000 times to avoid an infinite loop

MsgBox

"The card is not properly inserted or the card is not connected to the serial port!"

GoTo CloseP

End If

RNum = RNum + 1

GoTo ReadAgain

End If

If Hex$(Asc(Readbuff)) <> Hex$(&HFF) Then GoTo Shand

'If the return code is incorrect, return and continue to send handshake signals

Else

Label1.Caption = "The handshake signal is:"

+Hex$(Asc(Readbuff$))

Msgbox "The handshake signal is correct and the connection is correct"

GoTo CloseP

End If

Loop

CloseP:lRet = CloseHandle( lHandle )

If lRet = 0 Then

MsgBox "Serial communication port closed successfully",

48, "Prompt Window"

End If

End Sub

It should be noted that when the PC communicates with the MCU system, the data in the MCU data storage area (RAM) is hexadecimal, and the data transmitted on the signal line is the binary form of the ASCII code of the hexadecimal number; while the ANSI code is used in the Windows system, and the ANSI code is only the same as the ASCII code in the first 126. That is, the string of ASCII codes of hexadecimal numbers received under Win95 can be converted to ANSI code first and then restored to hexadecimal numbers under Win95.
Specifically: Code$=Hex$(Asc (Readbuff$))
In addition, due to the change in the data type of the 32-bit API function parameter, all integer parameters are converted to long integers (Long) to support 32-bit processing, which is especially true when setting the return value.

6 Conclusion

The above hardware and software have achieved relatively ideal results in our practice. The software saves the hardware cost, and by adding handshake signals in the communication software of the PIC16F84 microcontroller system and the PC, the purpose of software data verification is achieved, and higher communication reliability is obtained.

References

1 MICROCHIP CO. PIC16/17 MICROCO-NTROLLER DATA BOOK. 1995/1996
2 Li Dongxing et al. PIC16CXX Series MCU Application Design. Gaoqi Electronic Technology Co., Ltd., 1996.10
3 Darwin Boyle et al. Visual Basic 4 Developer's Guide. Beijing: Machinery
Industry Press, 1997.

This post is from Microchip MCU

Latest reply

  Details Published on 2015-7-28 17:15
 

136

Posts

0

Resources
2
 
Thanks to the host for the detailed introduction, I learned a lot!
This post is from Microchip MCU
 
 
 

37

Posts

0

Resources
3
 
After reading it, I will support it and study it carefully.
This post is from Microchip MCU
 
 
 

2

Posts

0

Resources
4
 
This post is from Microchip MCU
 
 
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list