; reads analog input on GP4 (AN3) using VDD reference
; displays resulting 10-bit value (0 - 1023) on TM1638 display
; connections for PIC12F675:
; GP0: DIO pin of TM1638 display
; GP1: CLK pin of TM1638 display
; GP2: STB pin of TM1638 display
; GP3: Reset (MCLR)
; GP4: Analog input
; GP5: no function
    
; PIC12F675 Configuration Bit Settings

; Assembly source line config statements

; CONFIG
  CONFIG  FOSC = INTRCIO        ; Oscillator Selection bits (INTOSC oscillator: I/O function on GP4/OSC2/CLKOUT pin, I/O function on GP5/OSC1/CLKIN)
  CONFIG  WDTE = OFF            ; Watchdog Timer Enable bit (WDT disabled)
  CONFIG  PWRTE = ON            ; Power-Up Timer Enable bit (PWRT enabled)
  CONFIG  MCLRE = ON            ; GP3/MCLR pin function select (GP3/MCLR pin function is MCLR)
  CONFIG  BOREN = OFF           ; Brown-out Detect Enable bit (BOD disabled)
  CONFIG  CP = OFF              ; Code Protection bit (Program Memory code protection is disabled)
  CONFIG  CPD = OFF             ; Data Code Protection bit (Data memory code protection is disabled)

// config statements should precede project file includes.
  
#include <xc.inc>

; name GPIO bits used for TM1638 I/O
  STB equ 2
  CLK equ 1
  DIO equ 0

PSECT absdata, abs, ovrld, class=DATA, delta=1
  ORG 20h

sevenSeg: DS 8 ; 8 bytes of seven segment data left to right, common cathode
leds: DS 1 ; 8 bits for the LEDS, left to right, 1 = illuminated
buttons: DS 1 ; 8 bits for the 8 buttons, left to right, 1 = pressed
ledMask: DS 1 ; masks all but one LED bit in refreshDisplay
shiftReg: DS 1 ; byte being clocked in or out by read2Buttons or transmitByte
i: DS 1 ; loop variable for refreshDisplay and read8Buttons loops
j: DS 1 ; loop variable for transmitByte and read2Buttons loops
lo: DS 1 ; low 8 bits for bin2Asc
hi: DS 1 ; high 8 bits for bin2Asc

 ; ***IMPORTANT - code won't work without this linker option ***
 ; in project properties, custom linker options, add -presetVect=0
 ; ***IMPORTANT***
PSECT resetVect, class=CODE, delta=2
resetVect:
    ; PAGESEL(main) ; not needed on PIC12F, because it only has 1K Flash
    goto main
    nop
    nop
    nop
intVect:
    goto intVect


; PSECT code ; no need for a separate code section. follows on from intVect

transmitByte: ; clock out the byte passed in W
    movwf shiftReg
    BANKSEL(TRISIO)
    bcf TRISIO, DIO ; DIO pin is output
    BANKSEL(GPIO)
    bcf GPIO, STB ; enable TM1638 chip
    movlw 8 ; 8 bits to shift out
    movwf j ; loop variable
tbLoop: ; shift out the bits from the least significant end
    bcf GPIO, CLK ; clock low
    btfss shiftReg, 0
    bcf GPIO, DIO ; transmit a 0 if bit 0 of shiftReg is clear
    btfsc shiftReg, 0
    bsf GPIO, DIO ; or transmit a 1 if bit 0 of shiftReg is set
    rrf shiftReg, F; shift next bit in place
    bsf GPIO, CLK ; TM1638 reads in bit on rising edge of clock
    decfsz j, F ; loop till 8 bits transmitted
    goto tbLoop
    return

; write 8 bytes from sevenSeg to TM1638
; interspersed with 8 bytes set or cleared by the 8 bits of leds
refreshDisplay:
    movlw 0x40
    call transmitByte ; write display, auto increment
    bsf GPIO, STB ; end of command
    movlw 0xC0
    call transmitByte ; set starting address zero. Note: no end of command here
    movlw sevenSeg
    movwf FSR ; file select register is pointer to sevenSeg
    movlw 8 ; 8 pairs of bytes to send
    movwf i ; loop variable
    movlw 0x80
    movwf ledMask ; bits from most significant to least control the 8 leds
rdLoop:
    movf INDF, W ; get one sevenSeg byte from table into w
    call transmitByte
    incf FSR, F ; advance pointer ready for next character (if any)
    movf leds, W
    andwf ledMask, W ; test if bit set
    btfss ZERO ; skip if W now contains 0
    movlw 1 ; if ledMask bit was set in leds, W now contains 1
    call transmitByte ; send 1 to switch LED on or 0 to switch off
    bcf CARRY ; clear carry, so next instruction can't set bit 7
    rrf ledMask, F ; shift mask bit ready for next LED (if any)
    decfsz i, F ; loop to transmit 8 pairs of bytes
    goto rdLoop
    bsf GPIO, STB ; end of command
    return

; read 2 buttons from the TM1638 board into bits 0 and 4 of W.
; the way the board is laid out, first keyscan read returns the leftmost
; button (7) in bit 0 and the 5th button from right (3) in bit 4.
; subsequent auto-increment reads return buttons 6&2, 5&1, 4&0 the same bits
read2Buttons:
    BANKSEL(TRISIO)
    bsf TRISIO, DIO ; DIO pin is input
    bsf WPU, DIO ; weak pull up enabled for DIO
    BANKSEL(GPIO)
    clrf shiftReg
    movlw 8 ; 8 bits to shift in
    movwf j ; loop variable
r2bLoop: ; shift in the bits to the most significant end
    bcf GPIO, CLK ; clock low - TMS1638 outputs data on falling edge
    bcf CARRY
    rrf shiftReg, F
    btfsc GPIO, DIO
    bsf shiftReg, 7 ; move received bit into shiftReg
    bsf GPIO, CLK ; clock high
    decfsz j, F ; loop till 8 bits received
    goto r2bLoop
    movf shiftReg, W ; return 2 bits read in W
    return

read8Buttons: ; read all 8 board pushbuttons into buttons byte
    movlw 0x42 ; read keyscan data, auto increment
    call transmitByte ; 2 microseconds needed after this, before 1st read
    clrf buttons
    movlw 4 ; four bytes to read
    movwf i ; loop variable
r8bLoop:
    bcf CARRY
    rlf buttons, F ; shift any buttons already read (8-bit rotate, not 9)
    btfsc CARRY ; check what was bit 7 of buttons, now in carry
    bsf buttons, 0 ; rotate the bit back into buttons
    call read2Buttons ; read 2 buttons into bits 0 and 4 of W
    iorwf buttons, F ; merge those button bits with the ones already read
    decfsz i, F ; loop four times to read the 8 buttons
    goto r8bLoop
    swapf buttons, F ; after four shifts, nibbles are reversed
    bsf GPIO, STB ; end of communication
    return

asciiTo7Seg: ; cut-down version for numbers and hex digits only
    addlw -71
    btfsc CARRY
    retlw 0 ; W was >= 71 : return blank
    addlw 71 - 45 ; W now original value - 45
    btfss CARRY
    retlw 0 ; W was < 45 : return blank
    addwf PCL, F ; computed goto for 45 <= W <= 70
    retlw 0x40 ; 45 -
    retlw 0x80 ; 46 .
    retlw 0x12 ; 47 /
    retlw 0x3F ; 48 0
    retlw 0x06 ; 49 1
    retlw 0x5B ; 50 2
    retlw 0x4F ; 51 3
    retlw 0x66 ; 52 4
    retlw 0x6D ; 53 5
    retlw 0x7D ; 54 6
    retlw 0x07 ; 55 7
    retlw 0x7F ; 56 8
    retlw 0x6F ; 57 9
    retlw 0x22 ; 58 : (")
    retlw 0x20 ; 59 ; (left apostrophe)
    retlw 0x39 ; 60 < ([)
    retlw 0x48 ; 61 =
    retlw 0x0F ; 62 > (])
    retlw 0x53 ; 63 ?
    retlw 0x63 ; 64 @ (degree sign - high o)
    retlw 0x77 ; 65 A
    retlw 0x7C ; 66 B
    retlw 0x58 ; 67 C
    retlw 0x5E ; 68 D
    retlw 0x79 ; 69 E
    retlw 0x71 ; 70 F

loTenPower:
    addwf PCL, F
    retlw 1 ; units
    retlw 10 ; tens
    retlw 100 ; hundreds
    retlw 0xE8 ; thousands (0x03E8)
    retlw 0x10 ; ten thousands (0x 2710)

hiTenPower:
    addwf PCL, F
    retlw 0 ; units
    retlw 0 ; tens
    retlw 0 ; hundreds
    retlw 0x03 ; thousands (0x03E8)
    retlw 0x27 ; ten thousands (0x 2710)
    
; convert 16-bit unsigned binary in HI LO to 5 chars of ASCII with leading zero
; suppression starting at FSR.  contents of HI LO are destroyed
; resulting digits then converted to seven-segment code
; uses i as power-of-ten index, j as flag for suppress leading zeros
bin2Seven:
    movlw 4
    movwf i ; start by subtracting ten thousands (10^4)
    movwf j ; set leading zero suppression flag
b2sNextDigit:
    clrf INDF
b2sSubHi:
    movf i, W
    call hiTenPower
    subwf hi, F
    btfss CARRY
    goto b2sAddHi
    movf i, W
    call loTenPower
    subwf lo, F
    btfss CARRY
    goto b2sDecHi
b2sSubtracted:
    incf INDF, F ; subtracted a power of ten without going negative
    clrf j ; switch off leading zero suppression
    goto b2sSubHi ; loop till one too many power of ten subtracted
b2sAddLo:
    movf i, W
    call loTenPower
    addwf lo, F
b2sAddHi:
    movf i, W
    call hiTenPower
    addwf hi, F
    movlw 32 ; or binary digit with 32 to convert zero to space    
    movf j, F ; suppressing zeros? ZERO flag set when NOT suppressing
    btfsc ZERO ; skip if suppressing zeros
    movlw 48 ; or binary digit with 48 to convert to ASCII
    movf INDF, F ; is digit a zero? ZERO flag set if it is
    btfss ZERO ; skip if digit is zero
    movlw 48 ; otherwise, or binary digit with 48 to convert to ASCII
    iorwf INDF, W
    call asciiTo7Seg
    movwf INDF
    incf FSR, F ; move to next digit
    decfsz i, F ;
    goto b2sNextDigit ; continue with next decade down to tens
    movf lo, W ; get last digit (ones)
    iorlw 48	     ; convert to ASCII
    call asciiTo7Seg
    movwf INDF
    return
b2sDecHi:
    movf hi, F ; test if hi can be decremented without going negative
    btfsc ZERO
    goto b2sAddLo
    decf hi, F
    goto b2sSubtracted
   
main:
    BANKSEL(CMCON) ; bank 0
    clrf GPIO ; init GPIO (taken from datasheet example)
    movlw 7
    movwf CMCON ; turn off comparitor
    BANKSEL(ANSEL) ; bank 1
    movlw 0xF8
    movwf TRISIO ; three pins that communicate with TM1638 are initially outputs
    movwf ANSEL ; use internal A/D oscillator and make AN3 (GP4) analog input
    bcf nGPPU ; enable pull-ups (required on DIO pin by read2Buttons)
    BANKSEL(GPIO) ; bank 0
    movlw 7
    movwf GPIO ; all 3 outputs high, initially
    movlw 0x8D ; select right-justified 10-bit ADC result, VDD as the reference
    movwf ADCON0 ; ... and select AN3 (GP4) as the input for the A/D converter

    movlw 0x81
    call transmitByte ; display off
    bsf GPIO, STB ; end of command

    movlw 0x88
    call transmitByte ; set brightness 1_16
    bsf GPIO, STB ; end of command
    
    movlw 'A'
    call asciiTo7Seg ; could save some FLASH here by hard coding 7seg patterns
    movwf sevenSeg + 0
    movlw 'D'
    call asciiTo7Seg
    movwf sevenSeg + 1
    movlw 'C'
    call asciiTo7Seg
    movwf sevenSeg + 2 ; put Adc label on first three chars of display

mLoop:
    call read8Buttons
    movf buttons, W
    movwf leds
    bsf ADCON0, 1 ; start A/D conversion
waitADC:
    btfsc ADCON0, 1 ; wait for conversion to complete
    goto waitADC
    BANKSEL(ADRESL) ; bank 1
    movf ADRESL, W ; get low 8 bits of ADC conversion
    movwf lo
    BANKSEL(ADRESH) ; bank 0
    movf ADRESH, W ; get highest two bits of ADC conversion (other bits read 0)
    movwf hi
    movlw sevenSeg + 3
    movwf FSR
    call bin2Seven
    call refreshDisplay
    clrf i
    clrf j
delay:
    decfsz j, F
    goto delay
    decfsz i, F
    goto delay
    goto mLoop
END resetVect ; gives assembler clue to program start point. (Not needed PIC12)
