v0.3 - Implementing more Unilink commands and RingIndicator control (to wake the...
authorWerner Johansson <wj@xnk.nu>
Tue, 4 Mar 2003 22:08:11 +0000 (14:08 -0800)
committerWerner Johansson <wj@xnk.nu>
Sun, 17 Oct 2010 00:32:31 +0000 (17:32 -0700)
Signed-off-by: Werner Johansson <wj@xnk.nu>

wj-uni.asm

index 130df18..f2a186d 100644 (file)
@@ -1,7 +1,7 @@
        title   "PIC16F870 Unilink(R) Interface by Werner Johansson (c) 2003"\r
        subtitl "Definitions"\r
        list    c=150,P=16F870,R=DEC,F=inhx8m\r
-        include "p16f870.inc"            ; Standard equates & Macros\r
+        include "p16f870.inc"           ; Standard equates & Macros\r
         ERRORLEVEL 1,-302               ; Get rid of those annoying 302 msgs!\r
 \r
 \r
 ;----------------------------------------------------------------\r
 ;  TODO\r
 ;----------------------------------------------------------------\r
-;  BUSON OUT control isn't implemented\r
+;  Fix the DelayW routine so it actually delays W/10 ms...\r
 ;  No checksum checking is done on incoming packets\r
-;  Investigate whether we actually have to save PCLATH in ISH, maybe save FSR?\r
+;  Investigate whether I actually have to save PCLATH in ISH, maybe save FSR?\r
 ;  Move RS232 code into ISH\r
 ;  Check Overrun errors from the UART\r
-;  Implement Bus re-initialize command\r
-;  Implement lots of other Unilink commands\r
+;  Implement lots of other Unilink commands (Text display, time display etc.)\r
+;  Implement the Watchdog Timer (might be useful even though I haven't seen it hang yet..)\r
 \r
 ;----------------------------------------------------------------\r
 ;  HISTORY\r
 ;----------------------------------------------------------------\r
 ;  Version\r
 ;\r
+;  0.3  Implementing more Unilink commands and RingIndicator control (to wake the computer from sleep)\r
 ;  0.2  First attempt at responding to the Anyone command\r
 ;  0.1  Receives Unilink data OK, relays it to serial\r
-;  0.0  Very first "Fucking No Work!" version\r
+;  0.0  Very first "F**king No Work!" version\r
 \r
 ;----------------------------------------------------------------\r
 ;  I/O LAYOUT\r
@@ -37,7 +38,7 @@
 ;  Unilink BUSON OUT (blue) connected to RC4 (this is for daisy-chaining)\r
 ;  Unilink CLK (yellow) connected to RB0/INT (Interrupt pin)\r
 ;  Unilink RST (lilac) connected to RA4\r
-;  LCD RS connected to pin RB1\r
+;  LCD RS connected to pin RB1 (The LCD is a standard 16x1 char HD44780 compatible unit)\r
 ;  LCD RW connected to pin RB2\r
 ;  LCD E connected to pin RB3\r
 ;  LCD DB4-DB7 connected to RB4-RB7\r
@@ -110,7 +111,7 @@ IRQW                equ     7fh             ;
        subtitl "Startup"\r
        page\r
 ;----------------------------------------------------------------\r
-;  Power up/Reset starting point [den rulerar]\r
+;  Power up/Reset starting point\r
 \r
        org     0                       ; Start at the beginning of memory (the reset vector)\r
        call    Bootstrap               ; Call Flash Load routine\r
@@ -121,12 +122,16 @@ IRQW              equ     7fh             ;
        subtitl "IRQ Handler"\r
 ;----------------------------------------------------------------\r
 ;  Interrupt handler always starts at addr 4\r
-;  In order to save one instruction cycle we put the actual code here directly instead of a goto instruction\r
+;  In order to reduce the INT latency the actual code is put here directly instead of using a goto instruction.\r
+;  Also because of the real-time requirements for clocking data onto the Unilink bus the first check in the ISR\r
+;  is to see whether the Unilink clock rise was the reason for the interrupt. This results in a "clock rise to\r
+;  bit ready" time of less than 30 instruction cycles, should be plenty of spare time waiting for clock to go low\r
+;  again after that.\r
 \r
        org     4                       ; ISR vector is at address 4\r
        movwf   IRQW                    ; Save W\r
        swapf   STATUS,w                ; Get the status register into w\r
-       clrf    STATUS                  ; Zero out the status reg, gives us Bank0 all the time\r
+       clrf    STATUS                  ; Zero out the status reg, gives Reg Bank0\r
        movwf   IRQSTATUS               ; Store the STATUS reg\r
        movf    PCLATH,w                ; Get the PCLATH reg\r
        movwf   IRQPCLATH               ; And store it\r
@@ -136,16 +141,16 @@ IRQW              equ     7fh             ;
        btfss   INTCON,INTF             ; Check if it's the INT edge interrupt (Unilink CLK)\r
        goto    IRQNotINT               ; No it's not, check the other sources\r
 \r
-; If there's activity on the clock line (the clock goes high) we stay in here until we have clocked eight bits\r
-; - this saves us a lot of context switching (and it's just a few hundred cpu cycles after all (20us*8 bits=\r
-; 160us=800 instruction cycles (5 MIPS @ 20MHz), not even a problem for serial input if we're not getting more than\r
-; 6250 bytes per second from the UART, and the 2-byte FIFO somehow fills up (this should be impossible even @ 115200\r
-; as we're only calling this blocking INT handler a maximum of 1000 times per second, halting INT's for 1/6250 of a second,\r
-; this gives the CPU ample of time to deal with all bytes from the USART. I'm checking the OERR (Serial Overrun) bit\r
-; to catch this though.. Note that this piece of code does both TX and RX at the same time (in order to receive packets\r
-; one has to make sure that the packet buffer is zeroed out before entering here, otherwise collisions will occur..\r
-; According to my logic analyzer this implementation is pretty decent when it comes to timing, even though it's a\r
-; interrupt driven software based USART - by trigging the interrupt on the rising edge we buy us some extra time here\r
+; If there's activity on the clock line (the clock goes high) the CPU will stay in here until eight bits have been clocked in\r
+; - this reduces context switching (and it's just a few hundred cpu cycles after all (20us*8 bits=160us=800 instruction\r
+; cycles (5 MIPS @ 20MHz), not even a problem for serial input if it's not receiving more than 6250 bytes per second, and the\r
+; 2-byte FIFO somehow fills up (this should be impossible even @ 115200 as this blocking INT handler only runs a maximum of\r
+; 1000 times per second, halting INT's for 1/6250 of a second - this gives the CPU ample of time to deal with all bytes from\r
+; the USART. I should check the OERR (Serial Overrun) bit to catch this though.. Note that this piece of code does both TX\r
+; and RX at the same time (in order to receive packets one has to make sure that the packet buffer is zeroed out before entering\r
+; here, otherwise collisions will occur..\r
+; According to my logic analyzer this implementation is pretty decent when it comes to timing, even though it's an\r
+; interrupt driven "USART" implemented in software - by trigging the interrupt on the rising edge there's some extra margin here\r
 ; (the clock goes high 10us before the master clocks the bit in (on the falling edge), that should be plenty of time..)\r
 \r
        movlw   8                       ; Loop through the 8 bits\r
@@ -173,14 +178,14 @@ IRQINTCLKWaitLow
        btfsc   PORTB,0                 ; Wait for clock to go low\r
        goto    IRQINTCLKWaitLow\r
 \r
-       clrc                            ; Clear carry (this way the DataStore byte doesn't have to be cleared before)\r
+       clrc                            ; Clear carry\r
        btfss   PORTC,3                 ; Test DATA\r
        setc                            ; Set carry if data is LOW (data is inverted!)\r
-       rlf     INDF,f                  ; Shift it into our accumulator\r
+       rlf     INDF,f                  ; Shift it into the "accumulator"\r
 \r
        decfsz  DataCount,f             ; Loop once more perhaps?\r
        goto    IRQINTCLKWaitHigh       ; Yes, again!\r
-       goto    IRQINTRecvDone          ; No we're done, don't check for clock to go high again\r
+       goto    IRQINTRecvDone          ; No it's done, don't check for clock to go high again\r
 \r
 IRQINTCLKWaitHigh\r
        btfss   PORTC,2                 ; Check for BUSON\r
@@ -190,7 +195,7 @@ IRQINTCLKWaitHigh
        goto    IRQINTBitSet            ; Loop again\r
 \r
 ; Successfully received a byte here, run it through a state machine to figure out what to do\r
-; (several possibilites exists here:\r
+; (several possibilites exists here):\r
 ;;;;;; If more than 1.1ms has passed since last receive, reset receive counter to zero\r
 ; If receive counter is zero and the received byte is a zero byte, discard it\r
 ; Otherwise store the byte in our receive buffer and increment receive counter\r
@@ -203,7 +208,7 @@ IRQINTCLKWaitHigh
 ; the packet and take appropriate action.\r
 \r
 IRQINTRecvDone\r
-       movf    UnilinkTXRX,w           ; Find out which byte we got\r
+       movf    UnilinkTXRX,w           ; Find out which byte # that was received\r
        andlw   0fh                     ; Mask\r
        bnz     IRQINTRecvNotFirst      ; Not the first byte\r
        movf    UnilinkRAD,w            ; Get the first byte received\r
@@ -230,10 +235,10 @@ IRQINTRecvNotCMD1
        andlw   0fh                     ; and mask - this results in a zero result when finished receiving\r
        bnz     IRQINTRecvIncomplete    ; Packet not ready yet\r
 \r
-; Here we actually have received a packet, should check the checksum(s) as well, but I don't care right now\r
+; Here a packet is actually received a packet, should check the checksum(s) as well, but I don't care right now\r
 ; (I need music in my car! :))\r
-; This is inefficient, I know, I'll improve it later... (Not that it matters, we have plenty of time here\r
-; (there can't be any more communication for another 4.8ms))\r
+; This is inefficient, I know, I'll improve it later... (Not that it matters, there's plenty of time here\r
+; (there won't be any more communication for at least another 4.8ms))\r
 \r
 ; Unilink command parser:\r
 \r
@@ -242,6 +247,18 @@ IRQINTRecvNotCMD1
        xorlw   01h\r
        bnz     IRQINTParseNot01\r
 \r
+; Check for 01 00 (Bus Re-Initialization)\r
+       movf    UnilinkCMD2,w\r
+;      xorlw   00h\r
+       bnz     IRQINTParseNot0100\r
+\r
+       clrf    UnilinkID               ; Clear the existing Unilink ID, if any\r
+       bcf     BUSON_OUT_BIT           ; Clear the cascade BUSON pin, not activated again until we have a new ID\r
+\r
+       goto    IRQINTParseComplete     ; Don't send any reply to this\r
+\r
+IRQINTParseNot0100\r
+\r
 ; Check for 01 02 (Anyone)\r
        movf    UnilinkCMD2,w\r
        xorlw   02h\r
@@ -271,7 +288,7 @@ IRQINTRecvNotCMD1
        movlw   0deh                    ; Hard coded parity 2 (!)\r
        movwf   UnilinkData5\r
         clrf   UnilinkData6\r
-       goto    IRQINTParseBypassClear  ; We don't want to clear the data, we want to send what's in the buffer next time\r
+       goto    IRQINTParseBypassClear  ; Don't clear the data, the buffer will be sent as the next packet\r
 \r
 IRQINTParseNot0102\r
 \r
@@ -281,8 +298,8 @@ IRQINTParseNot0102
        bnz     IRQINTParseNot0112\r
 \r
        movf    UnilinkRAD,w\r
-       xorwf   UnilinkID,w             ; Is it for us?\r
-       bnz     IRQINTParseNot0112      ; nope\r
+       xorwf   UnilinkID,w             ; Is it for me?\r
+       bnz     IRQINTParseNot0112      ; Nope\r
 \r
        clrf    UnilinkParity1\r
        movlw   10h                     ; Sending to Master\r
@@ -295,14 +312,14 @@ IRQINTParseNot0102
        addwf   UnilinkParity1,f\r
        movwf   UnilinkCMD1\r
 \r
-       movlw   80h                     ; We're idle unless selected\r
+       movlw   80h                     ; Idle unless selected\r
        btfsc   UnilinkSelected,7       \r
        clrw\r
        \r
        addwf   UnilinkParity1,f\r
        movwf   UnilinkCMD2\r
         clrf   UnilinkData6\r
-       goto    IRQINTParseBypassClear  ; We don't want to clear the data, we want to send!\r
+       goto    IRQINTParseBypassClear  ; Don't clear the data, the buffer will be sent as the next packet\r
 \r
 IRQINTParseNot0112\r
 \r
@@ -313,7 +330,9 @@ IRQINTParseNot01
        xorlw   02h\r
        bnz     IRQINTParseNot02\r
 \r
-       movf    UnilinkRAD,w            ; Get the ID the master has given us\r
+       bsf     BUSON_OUT_BIT           ; Now activate the cascade BUSON pin, to allow others to be discovered\r
+\r
+       movf    UnilinkRAD,w            ; Get the ID the master has given me\r
        movwf   UnilinkID               ; Store my id\r
        movf    UnilinkCMD2,w           ; Get the bitmask\r
        movwf   UnilinkBit              ; And store it (this is needed when doing slave breaks and actually responding)\r
@@ -338,7 +357,7 @@ IRQINTParseNot01
        movlw   24h\r
        addwf   UnilinkParity2M,f\r
        movwf   UnilinkData1\r
-       movlw   2ch                     ; My internal MD sends 1c here... (external/internal or 1/10 disc difference?)\r
+       movlw   2ch                     ; My internal MD sends 1c here... (external/internal difference)\r
        addwf   UnilinkParity2M,f\r
        movwf   UnilinkData2\r
        movlw   22h\r
@@ -349,30 +368,50 @@ IRQINTParseNot01
        movwf   UnilinkData4\r
 \r
         clrf   UnilinkData6\r
-       goto    IRQINTParseBypassClear  ; We don't want to clear the data, we want to send!\r
+       goto    IRQINTParseBypassClear  ; Don't clear the data, the buffer will be sent as the next packet\r
 \r
 IRQINTParseNot02\r
 \r
+; Check for CMD1 = 87h (Power control)\r
+       movf    UnilinkCMD1,w\r
+       xorlw   087h\r
+       bnz     IRQINTParseNot87\r
+\r
+; Test for power-on bit (it seems like bit 3 (0x08h) of CMD2 is set when the power is on)\r
+       btfsc   UnilinkCMD2,3\r
+       goto    IRQINTParse87PowerOn\r
+\r
+       bsf     RS232_RI_BIT            ; Set this to make RI pin go low (after RS-232 levels)\r
+       goto    IRQINTParseComplete\r
+\r
+IRQINTParse87PowerOn\r
+       bcf     RS232_RI_BIT            ; Clear this to make RI pin go high (waking the computer)\r
+       goto    IRQINTParseComplete\r
+\r
+IRQINTParseNot87\r
+\r
 ; Check for CMD1 = f0h (Source Select)\r
        movf    UnilinkCMD1,w\r
        xorlw   0f0h\r
        bnz     IRQINTParseNotF0\r
 \r
        movf    UnilinkCMD2,w\r
-       xorwf   UnilinkID,w             ; Check if it's selecting us\r
+       xorwf   UnilinkID,w             ; Check if it's selecting me\r
        bnz     IRQINTParseF0Deselect\r
 \r
        bsf     UnilinkSelected,7       ; Now we're selected\r
-       goto    IRQINTParseNotF0\r
+       goto    IRQINTParseComplete\r
 \r
 IRQINTParseF0Deselect\r
 \r
        bcf     UnilinkSelected,7       ; Now we're de-selected\r
-       goto    IRQINTParseNotF0\r
+       goto    IRQINTParseComplete\r
 \r
 IRQINTParseNotF0\r
 \r
-; We end up here when parsing is complete and we're not interested in sending any reply back to the master\r
+IRQINTParseComplete\r
+\r
+; The CPU ends up here when parsing is complete and it's not interested in sending any reply back to the master\r
 ; (that's why we clear out all the packet buffer bytes)\r
 ; TODO: Replace this with an FSR access to save space and make the code neater\r
 \r
@@ -398,28 +437,31 @@ IRQINTParseBypassClear
        movlw   UnilinkRAD              ; Get the pointer to the first byte in the receive buffer\r
        movwf   UnilinkTXRX             ; Store it - this way the next byte that gets received goes into RAD\r
 \r
-       clrf    UnilinkCmdLen           ; No command length as we're waiting for a new packet\r
+       clrf    UnilinkCmdLen           ; No command length while waiting for a new packet\r
 \r
        \r
 IRQINTRecvIncomplete\r
 \r
 IRQINTRecvNullByte\r
        movf    INDF,w\r
-       movwf   DataStore               ; Store it so our non-irq code can snoop\r
+       movwf   DataStore               ; Store it so the non-irq code can snoop\r
 \r
 IRQAfterINT\r
-       bcf     INTCON,INTF             ; Clear our IRQ source bit so we can receive new bits again\r
+       bcf     INTCON,INTF             ; Clear the IRQ source bit to re-enable INT interrupts again\r
 \r
 IRQNotINT\r
 \r
 ; Finally restore CPU state and return from the ISR\r
+\r
+; If I have to save the FSR in the beginning I also need to restore it here...\r
+\r
        movf    IRQPCLATH,w\r
-       movwf   PCLATH          ; Restore PCLATH\r
+       movwf   PCLATH                  ; Restore PCLATH\r
        swapf   IRQSTATUS,w\r
-       movwf   STATUS          ; Restore STATUS\r
+       movwf   STATUS                  ; Restore STATUS\r
        swapf   IRQW,f\r
-       swapf   IRQW,w          ; Restore W\r
-       retfie                  ; Interrupt return\r
+       swapf   IRQW,w                  ; Restore W\r
+       retfie                          ; Interrupt return\r
 \r
 \r
        subtitl "Main loop"\r
@@ -431,247 +473,188 @@ IRQNotINT
 StartUpText1\r
        DT      "----- WJ UniLink"\r
                \r
-LookUp  movwf   PCL             ; Go to it\r
+LookUp  movwf   PCL                    ; Go to it (this assumes PCLATH == 00h)\r
 \r
 ;----------------------------------------------------------------\r
 ;  Main program begins here. [Called after bootloader, lcdinit and irqinit...]\r
 \r
-       org     100h\r
+       org     100h                    ; Maybe not force this to a specific address later\r
 Main\r
 \r
-       bsf     RS232_RI_BIT    ; We want RI to be high (inverted logic, not set)\r
-       bcf     BUSON_OUT_BIT   ; But we don't want BUSON_OUT on just yet, we need to be appointed first\r
-\r
-       bsf     STATUS,RP0      ; Select bank 1\r
-\r
-       bcf     RS232_RI_BIT    ; Both bits should be outputs at least\r
-       bcf     BUSON_OUT_BIT   ;\r
-\r
-;      bcf     STATUS,RP0\r
-;      bsf     STATUS,RP0\r
-\r
-       bsf     TXSTA,TXEN              ; Enable UART TX\r
-       bcf     STATUS,RP0              ; Back to bank 0\r
-\r
-       bsf     RCSTA,SPEN              ; Enable serial port\r
-       bsf     RCSTA,CREN              ; Enable UART RX\r
-\r
-; Replace this with an FSR access\r
-       clrf    UnilinkSelected\r
-       clrf    UnilinkID\r
-       clrf    UnilinkBit\r
-       clrf    UnilinkCmdLen\r
-       clrf    UnilinkRAD\r
-       clrf    UnilinkTAD\r
-       clrf    UnilinkCMD1\r
-       clrf    UnilinkCMD2\r
-       clrf    UnilinkParity1\r
-       clrf    UnilinkData1\r
-       clrf    UnilinkData2\r
-       clrf    UnilinkData3\r
-       clrf    UnilinkData4\r
-       clrf    UnilinkData5\r
-       clrf    UnilinkData6\r
-       clrf    UnilinkData7\r
-       clrf    UnilinkData8\r
-       clrf    UnilinkData9\r
-       clrf    UnilinkParity2\r
-       clrf    UnilinkZero\r
+       movlw   StartUpText1            ; Show something on the LCD\r
+       call    TxLCD16B\r
 \r
-       clrf    DataStore\r
-       movlw   UnilinkRAD      ; Get the pointer to the first byte in the receive buffer\r
-       movwf   UnilinkTXRX     ; Store it\r
+MainLoop\r
 \r
-       movlw   StartUpText1\r
-       call    TxLCD16B\r
-retry\r
-       \r
-        bcf     LCD_RS_BIT     ;Command mode\r
-       movlw   80h             ;DisplayRam 0\r
+       bcf     LCD_RS_BIT              ; LCD Command mode\r
+       movlw   80h                     ; DisplayRam 0\r
        call    TxLCDB\r
-        bsf     LCD_RS_BIT\r
+       bsf     LCD_RS_BIT\r
 \r
        movlw   '0'\r
-       btfsc   PORTA,4         ; Test RST\r
+       btfsc   PORTA,4                 ; Test RST\r
        movlw   'R'\r
        call    TxLCDB\r
 \r
        movlw   '0'\r
-       btfsc   PORTB,0         ; Test CLK\r
+       btfsc   PORTB,0                 ; Test CLK\r
        movlw   'C'\r
        call    TxLCDB\r
 \r
        movlw   '0'\r
-       btfsc   PORTC,2         ; Test BUSON-IN\r
+       btfsc   PORTC,2                 ; Test BUSON-IN\r
        movlw   'B'\r
        call    TxLCDB\r
 \r
        movlw   '0'\r
-       btfsc   PORTC,3         ; Test DATA\r
+       btfsc   PORTC,3                 ; Test DATA\r
        movlw   'D'\r
        call    TxLCDB\r
 \r
        movf    UnilinkCmdLen,w\r
-       bz      DontPrintCmd\r
+       bz      MainDontPrintCmd\r
        addlw   '0'\r
        call    TxLCDB\r
-DontPrintCmd\r
+\r
+MainDontPrintCmd\r
 \r
        movf    DataCount,w             ; Load bit counter (if 0 then byte is available)\r
        skpz\r
-       goto    retry\r
+       goto    MainLoop\r
 \r
        decf    DataCount,f             ; Set it non-zero\r
 \r
        movf    DataStore,w\r
        call    BootTXB                 ; Send to terminal\r
-       goto    retry\r
+       goto    MainLoop\r
 \r
 \r
+;----------------------------------------------------------------\r
+; IRQInit - Sets up the IRQ Handler\r
 \r
-;      movlw   StartUpText1\r
-;      call    TxLCD16B\r
-;      call    LongDelay\r
-\r
-;      bsf     PORTA,4         ; turn off LED\r
+IRQInit\r
 \r
-;      movlw   StartUpText2\r
-;      call    TxLCD16B\r
-;      call    LongDelay\r
+; Start with clearing the Unilink packet buffer before enabling any interrupts, otherwise the first packet might become corrupt\r
+; TODO: Replace this with FSR access\r
+       clrf    UnilinkSelected\r
+       clrf    UnilinkID\r
+       clrf    UnilinkBit\r
+       clrf    UnilinkCmdLen\r
+       clrf    UnilinkRAD\r
+       clrf    UnilinkTAD\r
+       clrf    UnilinkCMD1\r
+       clrf    UnilinkCMD2\r
+       clrf    UnilinkParity1\r
+       clrf    UnilinkData1\r
+       clrf    UnilinkData2\r
+       clrf    UnilinkData3\r
+       clrf    UnilinkData4\r
+       clrf    UnilinkData5\r
+       clrf    UnilinkData6\r
+       clrf    UnilinkData7\r
+       clrf    UnilinkData8\r
+       clrf    UnilinkData9\r
+       clrf    UnilinkParity2\r
+       clrf    UnilinkZero\r
 \r
-;      bcf     PORTA,4         ; turn on LED\r
+       clrf    DataStore\r
+       movlw   UnilinkRAD              ; Get the pointer to the first byte in the receive buffer\r
+       movwf   UnilinkTXRX             ; Store it\r
 \r
-;      movlw   StartUpText3\r
-;      call    TxLCD16B\r
-;      call    LongDelay\r
+; Fix the output state of RI and BUSON_OUT to a safe default\r
 \r
-;      goto    retry\r
+       bsf     RS232_RI_BIT            ; RS232 RI should be inactive (inverted logic, a set bit here gives a negative output)\r
+       bcf     BUSON_OUT_BIT           ; BUSON_OUT should be disabled for now, must be appointed first\r
 \r
+       bsf     STATUS,RP0              ; Reg bank 1\r
 \r
-;----------------------------------------------------------------\r
-; IRQInit - Sets up the IRQ Handler\r
+       bcf     RS232_RI_BIT            ; Both bits should be outputs\r
+       bcf     BUSON_OUT_BIT           ;\r
 \r
-IRQInit\r
-       bsf     STATUS,RP0              ; Reg bank 1\r
+; The default behavior of RB0/INT is to interrupt on the rising edge, that's what we use...\r
 ;      bcf     OPTION_REG,INTEDG       ; We want RB0 to give us an IRQ on the falling edge\r
+\r
        bsf     INTCON,INTE             ; Enable the RB0/INT\r
        bsf     INTCON,GIE              ; Enable global interrupts\r
+\r
+       bsf     TXSTA,TXEN              ; Enable UART TX\r
+\r
        bcf     STATUS,RP0              ; Back to bank 0\r
+\r
+       bsf     RCSTA,SPEN              ; Enable serial port\r
+       bsf     RCSTA,CREN              ; Enable UART RX\r
+\r
        return\r
 \r
 ;----------------------------------------------------------------\r
 ;  Initialize LCD Controller...\r
 \r
 LCDInit\r
-        clrf   PORTB\r
-        bsf     STATUS,RP0      ; Hi Bank\r
-        movlw   001h            ; All but RB0 are outputs.\r
-        movwf   TRISB           ; Yep\r
-        bcf     OPTION_REG,NOT_RBPU     ; Turn on port B pull-up\r
-        bcf     STATUS,RP0      ; Restore Lo Bank\r
+       clrf    PORTB                   ; First clear PortB data register\r
+       bsf     STATUS,RP0              ; Reg bank 1\r
+       movlw   001h                    ; All but RB0 are outputs.\r
+       movwf   TRISB                   ;\r
 \r
-;      bcf     PORTA,4         ; turn on LED\r
+       bcf     OPTION_REG,NOT_RBPU     ; Turn on port B pull-up\r
+       bcf     STATUS,RP0              ; Restore Reg bank 0\r
 \r
-;      movlw   44              ; Should be 16ms delay\r
-       movlw   255             ; Should be 16ms delay\r
+; This is a standard reset sequence for the LCD controller\r
+\r
+       movlw   160                     ; Need to delay for at least 15ms, let's go for 16ms delay\r
        call    DelayW\r
 \r
-       movlw   3               ; Write 3 to the LCD\r
-       call    TxLCD           ; Send to LCD\r
-;      movlw   12              ; Should be 5ms delay\r
-       movlw   255             ; Should be 16ms delay\r
+       movlw   3                       ; Write 3 to the LCD\r
+       call    TxLCD                   ; Send to LCD\r
+       movlw   50                      ; Need to delay for at least 4.1ms, let's go for 5ms delay\r
        call    DelayW\r
 \r
-       movlw   3               ; Write 3 to the LCD\r
+       movlw   3                       ; Write 3 to the LCD\r
        call    TxLCD\r
-;      movlw   12              ; Should be 16ms delay\r
-       movlw   255             ; Should be 16ms delay\r
+       movlw   10                      ; Need to delay for at least 100us, let's go for 1ms delay\r
        call    DelayW\r
 \r
-       movlw   3               ; Write 3 to the LCD\r
+       movlw   3                       ; Write 3 to the LCD\r
        call    TxLCD\r
-;      movlw   44\r
-       movlw   255             ; Should be 16ms delay\r
+       movlw   10                      ; Need to delay for at least 40us, let's go for 1ms delay\r
        call    DelayW\r
 \r
-       movlw   2               ;\\r
-       call    TxLCD           ; | 4-bit interface\r
-;      movlw   55              ; | After this we are ready to ROCK!\r
-       movlw   255             ; Should be 16ms delay\r
-       call    DelayW          ;/\r
+       movlw   2                       ; 4-bit interface requested\r
+       call    TxLCD                   ;\r
+       movlw   10                      ; Need to delay for at least 40us, let's go for 1ms delay\r
+       call    DelayW                  ;\r
 \r
-;      bsf     PORTA,4         ; turn off LED\r
+; Reset sequence ends here\r
+; From this point no delays are needed, now the BUSY bit is valid and the bus I/F is 4 bits\r
 \r
-       movlw 28h               ; Some random commands :)))\r
-       call TxLCDB\r
+       movlw   28h                     ; Function Select + 4-bit bus + 2-line display\r
+       call    TxLCDB\r
 \r
-       movlw 0ch               ; hmmm\r
-       call TxLCDB\r
+       movlw   0ch                     ; Display Control + LCD On (No cursor)\r
+       call    TxLCDB\r
 \r
-       movlw 01h               ; hmmm\r
-       call TxLCDB\r
+       movlw   01h                     ; Clear Display\r
+       call    TxLCDB\r
 \r
-       movlw 06h               ; hmmm\r
-       call TxLCDB\r
+       movlw   06h                     ; Auto Increment cursor position\r
+       call    TxLCDB\r
        \r
        return\r
    \r
 ;----------------------------------------------------------------\r
-; LongDelay - Well, guess that for yourself...\r
-\r
-LongDelay\r
-;   btfss PORTB,6        ; Talk to da PC?\r
-;   goto PCTalk          ; Oh yeah...\r
-\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   movlw 255\r
-   call DelayW\r
-   return\r
-\r
-;----------------------------------------------------------------\r
 ;  TxLCD16B\r
 ;  Send a string to the LCD.\r
 \r
 TxLCD16B\r
        movwf   Icount\r
-        bcf     LCD_RS_BIT\r
-       movlw   80h             ;DisplayRam 0\r
+       bcf     LCD_RS_BIT\r
+       movlw   80h                     ; DisplayRam 0\r
        call    TxLCDB\r
-        bsf     LCD_RS_BIT\r
+       bsf     LCD_RS_BIT\r
        call    TxLCD8B\r
-        bcf     LCD_RS_BIT\r
-       movlw   80h+40          ;DisplayRam 40 (row 2)\r
+       bcf     LCD_RS_BIT\r
+       movlw   80h+40                  ; DisplayRam 40 (row 2)\r
        call    TxLCDB\r
-        bsf     LCD_RS_BIT\r
+       bsf     LCD_RS_BIT\r
        call    TxLCD8B\r
        return\r
 \r
@@ -680,14 +663,14 @@ TxLCD16B
 ;  Send a string to the LCD.\r
 \r
 TxLCD8B\r
-;      movwf   Icount          ; Icount = W\r
+;      movwf   Icount                  ; Icount = W\r
        movlw   8\r
-       movwf   e_LEN           ; Move to e_LEN\r
+       movwf   e_LEN                   ; Move to e_LEN\r
 \r
-Txm_lp movf    Icount,w        ; get the byte\r
+Txm_lp movf    Icount,w                ; get the byte\r
        call    LookUp\r
-       incf    Icount,f        ; ...else ++Icount (table index)\r
-       call    TxLCDB          ; Send out the byte\r
+       incf    Icount,f                ; ...else ++Icount (table index)\r
+       call    TxLCDB                  ; Send out the byte\r
        decfsz  e_LEN,f\r
        goto    Txm_lp\r
        return\r
@@ -696,39 +679,39 @@ Txm_lp    movf    Icount,w        ; get the byte
 ; TxLCDB - send a byte to the LCD\r
 \r
 TxLCDB\r
-       movwf   TxTemp          ; Store byte to send for a while...\r
+       movwf   TxTemp                  ; Store byte to send for a while...\r
 \r
-       bcf     temp,0          ; Clear my temp bit\r
-       btfss   LCD_RS_BIT      ; Check if we try the correct reg\r
+       bcf     temp,0                  ; Clear my temp bit\r
+       btfss   LCD_RS_BIT              ; Check if we try the correct reg\r
        goto    RxNoProb\r
        bcf     LCD_RS_BIT\r
-       bsf     temp,0          ; Indicate RS change\r
+       bsf     temp,0                  ; Indicate RS change\r
 RxNoProb\r
 \r
 NotReady\r
-       call    RxLCDB          ; Receive byte from LCD, status reg\r
+       call    RxLCDB                  ; Receive byte from LCD, status reg\r
        andlw   80h\r
-       btfss   STATUS,Z        ; If the bit was set, the zero flag is not\r
+       skpz                            ; If the bit was set, the zero flag is not\r
        goto    NotReady\r
 \r
-       btfsc   temp,0          ; If we had to clear RS reset it now\r
+       btfsc   temp,0                  ; If we had to clear RS reset it now\r
        bsf     LCD_RS_BIT\r
 \r
-       swapf   TxTemp,w        ; Hi nibble of data to send in lo w bits\r
-       call    TxLCD           ; Send them first...\r
-       movf    TxTemp,w        ; Then we have the low nibble in low w bits\r
-       call    TxLCD           ; And send that one as well\r
+       swapf   TxTemp,w                ; Hi nibble of data to send in lo w bits\r
+       call    TxLCD                   ; Send them first...\r
+       movf    TxTemp,w                ; Then we have the low nibble in low w bits\r
+       call    TxLCD                   ; And send that one as well\r
 \r
        return\r
 ;----------------------------------------------------------------\r
 ; RxLCDB - recv a byte from the LCD\r
 \r
 RxLCDB\r
-       call    RxLCD           ; Receive the high nibble\r
+       call    RxLCD                   ; Receive the high nibble\r
        movwf   LCDWTmp\r
-       swapf   LCDWTmp,f       ; Swap it back to file\r
-       call    RxLCD           ; Receive the low nibble\r
-       addwf   LCDWTmp,w       ; Put the nibbles together and return in W\r
+       swapf   LCDWTmp,f               ; Swap it back to file\r
+       call    RxLCD                   ; Receive the low nibble\r
+       addwf   LCDWTmp,w               ; Put the nibbles together and return in W\r
 \r
        return\r
 \r
@@ -736,90 +719,100 @@ RxLCDB
 ; TxLCD - send a nibble to the LCD\r
 \r
 TxLCD\r
-       movwf   LCDWTmp         ; Write nibble to tmp\r
-       bcf     LCD_DB4_BIT     ; Clear previous data\r
-       bcf     LCD_DB5_BIT     ; \r
-       bcf     LCD_DB6_BIT     ;\r
-       bcf     LCD_DB7_BIT     ;\r
+       movwf   LCDWTmp                 ; Write nibble to tmp\r
+       bcf     LCD_DB4_BIT             ; Clear previous data\r
+       bcf     LCD_DB5_BIT             ; \r
+       bcf     LCD_DB6_BIT             ;\r
+       bcf     LCD_DB7_BIT             ;\r
 \r
-       btfsc   LCDWTmp,0       ; Test bit 0, transfer a set bit to LCD PORT\r
+       btfsc   LCDWTmp,0               ; Test bit 0, transfer a set bit to LCD PORT\r
        bsf     LCD_DB4_BIT\r
-       btfsc   LCDWTmp,1       ; Test bit 1, transfer a set bit to LCD PORT\r
+       btfsc   LCDWTmp,1               ; Test bit 1, transfer a set bit to LCD PORT\r
        bsf     LCD_DB5_BIT\r
-       btfsc   LCDWTmp,2       ; Test bit 2, transfer a set bit to LCD PORT\r
+       btfsc   LCDWTmp,2               ; Test bit 2, transfer a set bit to LCD PORT\r
        bsf     LCD_DB6_BIT\r
-       btfsc   LCDWTmp,3       ; Test bit 3, transfer a set bit to LCD PORT\r
+       btfsc   LCDWTmp,3               ; Test bit 3, transfer a set bit to LCD PORT\r
        bsf     LCD_DB7_BIT\r
 \r
-       bsf     LCD_E_BIT       ; And set E to clock the data into the LCD module\r
-       nop                     ; Let it settle\r
-        bcf     LCD_E_BIT       ; And clear the Enable again.\r
-       return                  ; Returns without modifying W\r
+       bsf     LCD_E_BIT               ; And set E to clock the data into the LCD module\r
+       nop                             ; Let it settle\r
+        bcf    LCD_E_BIT               ; And clear the Enable again.\r
+       return                          ; Returns without modifying W\r
 \r
 ;----------------------------------------------------------------\r
 ; RxLCD - recv a nibble from the LCD\r
 \r
 RxLCD\r
-       clrw                    ; Clear W register, return data in lower 4 bits\r
+       clrw                            ; Clear W register, return data in lower 4 bits\r
 \r
-        bsf     STATUS,RP0     ; Select 2nd reg bank, now TRIS regs can be accessed\r
+       bsf     STATUS,RP0              ; Select 2nd reg bank, now TRIS regs can be accessed\r
        \r
-       bsf     LCD_DB4_BIT     ; This sets the port bit as an input\r
+       bsf     LCD_DB4_BIT             ; This sets the port bit as an input\r
        bsf     LCD_DB5_BIT     \r
        bsf     LCD_DB6_BIT     \r
        bsf     LCD_DB7_BIT\r
-       bcf     STATUS,RP0      ; Back at reg bank 0    \r
 \r
-       bsf     LCD_RW_BIT      ; Set Read mode for the LCD\r
-       bsf     LCD_E_BIT       ; And set E to clock the data out of the LCD module\r
-       nop                     ; Let the bus settle\r
-       btfsc   LCD_DB4_BIT     ; Transfer a set port bit into W\r
+       bcf     STATUS,RP0              ; Back at reg bank 0    \r
+\r
+       bsf     LCD_RW_BIT              ; Set Read mode for the LCD\r
+       bsf     LCD_E_BIT               ; And set E to clock the data out of the LCD module\r
+       nop                             ; Let the bus settle\r
+       btfsc   LCD_DB4_BIT             ; Transfer a set port bit into W\r
        addlw   1\r
-       btfsc   LCD_DB5_BIT     ; Transfer a set port bit into W\r
+       btfsc   LCD_DB5_BIT             ; Transfer a set port bit into W\r
        addlw   2\r
-       btfsc   LCD_DB6_BIT     ; Transfer a set port bit into W\r
+       btfsc   LCD_DB6_BIT             ; Transfer a set port bit into W\r
        addlw   4\r
-       btfsc   LCD_DB7_BIT     ; Transfer a set port bit into W\r
+       btfsc   LCD_DB7_BIT             ; Transfer a set port bit into W\r
        addlw   8\r
-        bcf     LCD_E_BIT       ; And clear the Enable again.\r
-       bcf     LCD_RW_BIT      ; Set Write mode for the LCD\r
+        bcf    LCD_E_BIT               ; And clear the Enable again.\r
+       bcf     LCD_RW_BIT              ; Set Write mode for the LCD\r
+\r
+       bsf     STATUS,RP0              ; Select 2nd reg bank, now TRIS regs can be accessed\r
+\r
+       bcf     LCD_DB4_BIT             ; Set the port as an output again\r
+       bcf     LCD_DB5_BIT             ; \r
+       bcf     LCD_DB6_BIT             ;\r
+       bcf     LCD_DB7_BIT             ;\r
 \r
-        bsf     STATUS,RP0     ; Select 2nd reg bank, now TRIS regs can be accessed\r
-       bcf     LCD_DB4_BIT     ; Set the port as an output again\r
-       bcf     LCD_DB5_BIT     ; \r
-       bcf     LCD_DB6_BIT     ;\r
-       bcf     LCD_DB7_BIT     ;\r
-       bcf     STATUS,RP0      ; Back at reg bank 0    \r
+       bcf     STATUS,RP0              ; Back at reg bank 0    \r
 \r
-       return                  ; Returns with data in W\r
+       return                          ; Returns with data in W\r
 \r
 ;----------------------------------------------------------------------\r
-; Delay routines       (one iteration=3 cycles. That is 0.366211ms @32kHz)\r
-; 2.73* # of ms is good...\r
-\r
-DelayW movwf   Dcount          ; Set delay counter\r
-       clrf    Dcount2\r
-       decf    Dcount2,f\r
-DelayLp        decfsz  Dcount,f\r
-       goto    DelayIn\r
-       retlw   0\r
-DelayIn        decfsz  Dcount2,f\r
-       goto    DelayIn2\r
-       decf    Dcount2,f\r
-       goto    DelayLp\r
-DelayIn2       goto    $+1\r
-       goto    $+1\r
-       goto    $+1\r
-       goto    DelayIn\r
+; Delay routines (non-interrupt based, therefore not even close to reliable)\r
+; W=10 gives ~ 1ms of delay\r
+; 1ms=5000 instructions wasted, 100us=500 cycles\r
+; Maximum time waited will be 256*100us=25.6ms\r
+\r
+DelayW\r
+       movwf   Dcount                  ; Set delay counter, number of 100us periods to wait\r
+\r
+DelayOuter\r
+       movlw   0a5h                    ; This gives 165 iterations of the inner loop, wastes 495 cycles + these two + one more\r
+       movwf   Dcount2                 ; exiting the loop + 3 more for the outer loop = 501 cycles for every Dcount\r
+DelayInner\r
+       decfsz  Dcount2,f               ; 1 cycle (or two when exiting the loop)\r
+       goto    DelayInner              ; 2 cycles\r
+       decfsz  Dcount,f                ; Now decrement number of 100us periods and loop again\r
+       goto    DelayOuter\r
+       return\r
+\r
 \r
        subtitl "Bootstrap/Bootloader code"\r
        page\r
 \r
 ;----------------------------------------------------------------------\r
-; Bootstrap code - Allows PIC to flash itself with data from async port\r
+; Bootstrap code - Allows PIC to flash itself with data from the async port.\r
+; Accepts a standard INHX8 encoded file as input, the only caveat is that the code is slow when writing to memory\r
+; (we have to wait for the flash to complete), and therefore care has to be taken not to overflow the RS232 receiver\r
+; (one good way of solving that is to wait for the echo from the PIC before sending anything else)\r
+; Both program memory and Data EEPROM memory can be programmed, but due to hardware contraints the configuration\r
+; register can't be programmed. That means that any references to the config register in the hex file will be ignored.\r
+;\r
 ; Startup @9600bps\r
 \r
-       org     700h                    ; Place the boot code at the top of memory\r
+; RAM usage for the bootstrap code\r
 \r
 BootRXState    equ     7fh             ; What are we waiting for @RX\r
 BootBits       equ     7eh             ; bit0 1=write 0=read, bit1 1=PGM 0=EE, bit2 0=normal 1=no-op when prog\r
@@ -836,9 +829,11 @@ BootDataVH equ     74h
 BootHEXTemp    equ     73h\r
 BootStrTemp    equ     72h\r
 \r
+       org     700h                    ; Place the boot code at the top of memory\r
+\r
 Bootstrap\r
        movlw   7\r
-       movwf   PCLATH\r
+       movwf   PCLATH                  ; Make sure the lookup code runs with the high PC bits set!\r
 \r
        bsf     STATUS,RP0              ; Access bank 1\r
        bsf     TXSTA,TXEN              ; Enable UART TX\r
@@ -851,10 +846,10 @@ Bootstrap
 \r
 ;      clrf    BootRXState             ; Waiting for command\r
 \r
-       movlw   BootStartText\r
+       movlw   low BootStartText       ; Send boot banner to the serial port\r
        call    BootTXStr\r
 \r
-       movlw   0e8h\r
+       movlw   0e8h                    ; Initialize timeout timer\r
        movwf   BootTimerL\r
        movwf   BootTimerM\r
        movwf   BootTimerH\r
@@ -871,11 +866,11 @@ BootTimeout
        goto    BootTimeout\r
        call    BootRXB\r
        xorlw   27                      ; ESC\r
-       btfss   STATUS,Z\r
-       goto    BootTimeout             ; If it wasn't space, wait for another key\r
+       skpz\r
+       goto    BootTimeout             ; If it wasn't ESC, wait for another key\r
 \r
 BootFlash\r
-       movlw   BootFlashText\r
+       movlw   low BootFlashText       ; OK, flashing it is, send "start" text to serial port\r
        call    BootTXStr\r
 \r
        bsf     BootBits,1\r
@@ -884,11 +879,12 @@ BootFlash
 \r
 BootLoop\r
        call    BootRXB                 ; First find the ':'\r
+       call    BootTXB                 ; Echo to terminal\r
        xorlw   ':'\r
        skpz\r
        goto    BootLoop                ; Loop until we find it!\r
 \r
-       call    BootRXHEX               ; Get one ASCII encoded byte (two chars)\r
+       call    BootRXHEX               ; Get one ASCII encoded byte (two chars) (this echoes automatically)\r
        movwf   BootNumBytes            ; This is the number of bytes to be programmed on the line\r
 ; Maybe clear cary here?\r
        rrf     BootNumBytes,f          ; Right shift because we're double addressing this 8-bit format\r
@@ -952,13 +948,13 @@ BootWrite
 \r
 ; Here a verify can take place, the read-back results are now in DataL/H\r
 \r
-       movlw   '+'\r
-       goto    BootWriteDone\r
+;      movlw   '+'\r
+;      goto    BootWriteDone\r
 \r
 BootWriteSkip\r
-       movlw   '-'\r
+;      movlw   '-'\r
 BootWriteDone\r
-       call    BootTXB\r
+;      call    BootTXB\r
 \r
        incf    BootAddrL,f             ; Advance counter to next addr\r
        skpnz\r
@@ -967,30 +963,30 @@ BootWriteDone
        decfsz  BootNumBytes,f\r
        goto    BootLineLoop\r
 \r
-       movlw   13                      ; Progress\r
-       call    BootTXB\r
-       movlw   10                      ; Progress\r
-       call    BootTXB\r
+;      movlw   13                      ; Progress\r
+;      call    BootTXB\r
+;      movlw   10                      ; Progress\r
+;      call    BootTXB\r
 \r
        goto    BootLoop\r
 \r
 BootFlashComplete\r
        \r
 BootReturn\r
-       movlw   BootRunText\r
+       movlw   low BootRunText\r
        call    BootTXStr\r
 \r
-       bsf     STATUS,RP0\r
+       bsf     STATUS,RP0              ; Reg bank 1\r
 BootReturnWait\r
        btfss   TXSTA,TRMT              ; Wait for last things to flush\r
        goto    BootReturnWait\r
        bcf     TXSTA,TXEN              ; Disable UART TX\r
        bcf     STATUS,RP0              ; Back to bank 0\r
 \r
-       bcf     RCSTA,SPEN              ; Enable serial port\r
-       bcf     RCSTA,CREN              ; Enable UART RX\r
+       bcf     RCSTA,SPEN              ; Disable serial port\r
+       bcf     RCSTA,CREN              ; Disable UART RX\r
 \r
-       clrf    PCLATH\r
+       clrf    PCLATH                  ; Go back to memory bank 0\r
        return                          ; Return to code        \r
 \r
 ;----------------------------------------------------------------------\r
@@ -1032,7 +1028,7 @@ BootRXW1
 \r
 BootRXHEXNibble\r
        call    BootRXB                 ; Receive nibble\r
-\r
+       call    BootTXB                 ; Echo to terminal\r
        addlw   -'A'                    ; Convert from BCD to binary nibble\r
        skpc                            ; Test if if was 0-9 or A-F, skip if A-F\r
        addlw  'A' - 10 - '0'           ; It was numeric '0'\r
@@ -1121,6 +1117,6 @@ BootLookup
 ; EE Data (64 bytes), located at 2100h\r
 \r
         org 2100h\r
-;        data 0f2h, 099h, 000h, 000h, 018h, 0a5h, 090h, 084h\r
+;        data 0ffh, 0ffh, 0ffh, 0ffh, 0ffh, 0ffh, 0ffh, 0ffh\r
 \r
        END\r