/* Original one-shot integrating converter, RV32I + read-only cycle CSR.
 * GPIO0 INPUT/REFERENCE, GPIO1 finite reset, GPIO2 integrate-enable,
 * GPIO3 pulled-up physical comparator. x23 run-up ticks, x20 raw return
 * ticks, x21 done, x22 1=returned / 2=timeout. One virtual tick is10 us.
 * Positive x8=998 gives exactly2000 run-up ticks including loop overhead.
 */
.option norvc
.option norelax
.section .text.start,"ax",@progbits
.globl _start
.type _start,@function
_start:
    lui x5, 0x40000
    addi x6, zero, 7
    sw x6, 8(x5)
    addi x6, zero, 3
    sw x6, 4(x5)
    addi x7, zero, 64
reset_wait:
    addi x7, x7, -1
    bne x7, zero, reset_wait
    addi x8, zero, 998
    addi x6, zero, 5
    sw x6, 4(x5)
    csrrs x24, cycle, zero
    addi x7, x8, 0
integrate_wait:
    addi x7, x7, -1
    bne x7, zero, integrate_wait
    addi x6, zero, 4
    sw x6, 4(x5)
    csrrs x25, cycle, zero
    sub x23, x25, x24
    addi x9, zero, 2047
poll:
    lw x28, 0(x5)
    andi x28, x28, 8
    bne x28, zero, returned
    addi x9, x9, -1
    bne x9, zero, poll
    addi x22, zero, 2
    jal zero, finish
returned:
    csrrs x26, cycle, zero
    sub x20, x26, x25
    addi x22, zero, 1
finish:
    sw zero, 4(x5)
    addi x21, zero, 1
idle:
    jal zero, idle
.size _start, .-_start
.section .note.GNU-stack,"",@progbits
