/* Original three-bit automatic SAR. GPIO bits2..0 select the DAC;
 * GPIO3 reads the comparator; GPIO4 closes the physical acquisition switch.
 * x23 is a positive acquisition wait; x8 is the positive DAC wait count.
 * x20 final code, x21 done, x22 trials. Each conversion acquires once.
 */
    .option norvc
    .option norelax
    .section .text.start,"ax",@progbits
    .globl _start
    .type _start,@function
_start:
    lui x5, 0x40000
    addi x6, zero, 23
    sw x6, 8(x5)
    addi x24, zero, 16
    sw x24, 4(x5)
    addi x23, zero, 64
acquire:
    addi x7, x23, 0
acquire_wait:
    addi x7, x7, -1
    bne x7, zero, acquire_wait
    sw zero, 4(x5)
    addi x8, zero, 64
    addi x9, zero, 0
    addi x18, zero, 4
trial:
    or x19, x9, x18
    sw x19, 4(x5)
    addi x7, x8, 0
wait:
    addi x7, x7, -1
    bne x7, zero, wait
    lw x28, 0(x5)
    andi x28, x28, 8
    beq x28, zero, reject
    addi x9, x19, 0
reject:
    addi x22, x22, 1
    srli x18, x18, 1
    bne x18, zero, trial
    sw x9, 4(x5)
    addi x7, x8, 0
final_wait:
    addi x7, x7, -1
    bne x7, zero, final_wait
    addi x20, x9, 0
    addi x21, zero, 1
finished:
    jal zero, finished
    .size _start, .-_start
    .section .note.GNU-stack,"",@progbits
