/* Original virtual-timer AC phase controller. GPIO1 is measured polarity;
 * GPIO4/5 select delay 0/128/256/384 ticks, GPIO2 is the bounded command.
 * Each observed polarity change clears GPIO2 and starts a 480-tick window.
 * Expiry clears GPIO2 even if no further polarity change is seen.
 * RAM +0 edge count, +4 selected delay, +8 edge timer, +12 fire timer read.
 * Teaching RV32I platform, not vendor timing or a triac gate algorithm. */
    .option norvc
    .option norelax
    .section .text.start,"ax",@progbits
    .globl _start
    .type _start,@function
_start:
    lui x5, 0x40000
    lui x7, 0x20000
    addi x6, zero, 4
    sw x6, 8(x5)
    addi x8, zero, -1
    addi x16, zero, 0
    addi x15, zero, 1
poll:
    lw x10, 0(x5)
    andi x11, x10, 2
    beq x11, x8, check
    sw zero, 4(x5)
    addi x8, x11, 0
    lw x12, 256(x5)
    srli x13, x10, 4
    andi x13, x13, 3
    slli x13, x13, 7
    add x14, x12, x13
    addi x19, x12, 480
    addi x15, zero, 0
    addi x16, x16, 1
    sw x16, 0(x7)
    sw x13, 4(x7)
    sw x12, 8(x7)
check:
    lw x17, 256(x5)
    sub x20, x17, x19
    bge x20, zero, expired
    bne x15, zero, poll
    sub x20, x17, x14
    blt x20, zero, poll
    addi x18, zero, 4
    sw x18, 4(x5)
    addi x15, zero, 1
    sw x17, 12(x7)
    jal zero, poll
expired:
    sw zero, 4(x5)
    addi x15, zero, 1
    jal zero, poll
    .size _start, .-_start
    .section .note.GNU-stack,"",@progbits
