autobaud:                       ; autobaud with timer 2
    MOV     T2CON,#00h
; for (i =0 ; i< 8 ; i++) : 8 data bits
    jb      P3.0,$              ; wait for start bit
    jnb     P3.0,$              ; wait for data bit 0 'H'
    mov	    TL2, #00h
    mov     TH2, #00h
    SETB    TR2                 ; start timer
    MOV     R0,#03h
auto_bit:
    jb      P3.0,$              ; wait for data bit 1/3/5 'L'
    jnb     P3.0,$              ; wait for data bit 2/4/6 'H'
    djnz    R0,auto_bit
    jb      P3.0,$              ; wait for data bit 7 'L'
    jnb     P3.0,$              ; wait for stop bit 'H'
    clr     TR2                 ; stop timer
    dec     TL2                 ; remove one cycle of measurement
    mov     A,TL2
    cjne    A,#0FFh,TH2_00
    dec     TH2                 ; remove 1 to TH2 if initially TL2 was equal 00h
;                                 (TH2,TL2:0200h--> 01FFh)
TH2_00:
    mov     A,TH2
    mov     R6,A
    mov     A,TL2
    clr     C                   ; first multiply by 2
    rlc     A
    xch     A,R6
    rlc     A
    xch     A,R6
    add     A,TL2               ; and then add the original value
    xch     A,R6
    addc    A,TH2
;
; a,r6 = (a,r6)/64
;
    mov     R0,#6
div64:
    clr     C
    rrc     A
    xch     A,R6
    rrc     A
    xch     A,R6
    djnz    R0,div64
 
    cpl     A
    mov     RCAP2H,A
    mov     A,R6
    cpl     A
    mov     RCAP2L,A
           
    mov     SCON,#052h          ; serial port in 8 bits UART
    mov     T2CON,#034h         ; Timer2 in Baud rate Generator mode

    setb    TR2                 ; start Timer2
    ret