If you are looking for serial Transmit and Receive routines for PIC chips that don't already have a hardware USART built-in, this code can be useful. The code shown below is simple and does not call any other routines so it can be called by another calling routine (for the 2-level-call-stack PICs) and is based on example code seen in AN510, AN555 and a few other application notes you may have read.
If you did not notice, receiving a byte is called at RxByte, not at RxLoop.
This code also makes use of the Delay Macro described on another page.
You can download RS232 transmit/receive routines, or you can copy and paste the code shown below into your ASM code editor.
w equ 0 f equ 1 ; ;portA bit definitions DXbit equ 0 ;transmit pin (Bit0 of PortA) DRbit equ 1 ;receive pin (Bit1 of PortA) ; ; ____ ____ ; --|a2 \/ a1|<- !Rx ; --|a3 a0|-> !Tx ; ->|TOC osc1|<- XTAL ;!reset ->|MCLR osc2|-> XTAL ; gnd ->|Vss Vdd|<- +5v ; --|b0 b7|-- ; --|b1 b6|-- ; --|b2 b5|-- ; --|b3 b4|-- ; ---------- ;timing values RSbitC equ 4800000/1200/4 ;cycles for RS232 bit @4.8MHz RSbitC equ 6144000/1200/4 ;cycles for RS232 bit @6.144MHz ; ;--------------------------------------------------------------- org 08H ;register area DlyCnt res 2 ;delay wait counter RcvReg res 1 ;data received XmtReg res 1 ;data to be transmitted Count res 1 ;counter for #of Bits Transmit/Receive ;*************************************************************** ;RS232 Receive Byte, enter thru RXbyte ;enter: ;exit: w=byte received ;ram: RcvReg,Count,DlyCnt ;call: none ; RXloop DelayM RSbitC/2-3 ;wait 0.5bit time RXbyte btfsc PORTA,DRbit ;check for a Start Bit goto RXloop ;delay for 0.5 bit time DelayM RSbitC+RSbitC/4-7 ;delay for 1.25bit time movlw 8 ;prepare to receive 8 data bits movwf Count RXbits rrf RcvReg,f ;shift RXed byte - left to right bcf RcvReg,7 ;set bit7 of RXed byte to 0 btfsc PORTA,DRbit ;check RXed bit bsf RcvReg,7 ;set to 1bit if logic 1 DelayM RSbitC-7 ;wait until time for next bit decfsz Count,f ;loop until all 8 bits done goto RXbits movf RcvReg,w ;return with w=RS232byte return ;--------------------------------------------------------------- ;RS232 Transmit Byte ;enter: w=RS232byte to send ;exit: ;ram: XmtReg,Count,DlyCnt ;call: none ; TXbyte movwf XmtReg ;this is the byte to transmit movlw 8 ;prepare to send 8 data bits movwf Count bcf PORTA,DXbit ;send start bit DelayM RSbitC-4 TXbits rrf XmtReg,f ;get next bit to send (1 or 0) skpnc bsf PORTA,DXbit skpc bcf PORTA,DXbit bcf XmtReg,7 ;set XmtReg to 0 as we go... DelayM RSbitC-9 ;wait until time for next bit decfsz Count,f ;loop until all 8 bits done goto TXbits bsf PORTA,DXbit ;send 2 stop bits DelayM RSbitC*2 retlw 0 |
Other PIC Related Pages On This Web Site | ||||
---|---|---|---|---|
Home Page | A/B Long Term Timer | ASCII To MorseCode | Clear RAM Macro | Cylon Eye |
Delay Macro | Random Number Generator (RNG) | 7.96Hz Sinewave Generator | Table Array FSR Macro | PicDis Disassembler |