; RAM and I/O bus demo program 
; written by cb750mark 2025-12.
; for fCPU 0.4.39 and should work with later versions.

; clear all external RAM.  
; this consists of a [virtual-signal=signal-exclamation-mark] write command to each address, with no data.
clr out
mov r1 10[virtual-signal=signal-exclamation-mark] ; clear all external mem.
:clr-next
mov out1 r1
inc r1
ble r1 15 :clr-next
clr out

; time the execution of certain instructions.
clr

mov out1 0[virtual-signal=signal-T] ; init T count to 0
mov out2 201[virtual-signal=signal-exclamation-mark] ; timer device's address is 201.
clr out
mov out1 1[virtual-signal=signal-T] ; set T increment to 1 to start timer.
mov out2 202[virtual-signal=signal-exclamation-mark]
clr out

; test instruction speed.  
; WARNING: modifying program text in any way, including whitespace, can affect the 1 next run thereafter e.g. reading 6 ticks shorter than all other runs.  100% repeatable for any given program.  something to do with fCPU internal init i guess.
; the following list all take 1 tick:
; emit (to mem)
; mov (to reg) 
; clr out

emit mem1 5[item=pistol]
emit mem1 6[item=pistol]
emit mem1 7[item=pistol]
emit mem1 8[item=pistol]

clr out
mov out1 0[virtual-signal=signal-T] ; set T increment to 0 to stop timer.
mov out2 202[virtual-signal=signal-exclamation-mark]

; read elapsed time from T count.
mov out2 201[virtual-signal=signal-question-mark]
nop ; wait for read data to arrive.
fid r1 red [virtual-signal=signal-T]

; save result to external RAM cell 10
mov out1 r1
mov out2 10[virtual-signal=signal-exclamation-mark]
clr out

; read "qty of items to produce" from external ROM cell 401 to mem1.
clr out
mov out2 401[virtual-signal=signal-question-mark]
nop ; wait for read data to arrive.
xmov mem1 red 

; write product quantities from mem1 to external RAM cell 12.
xmov out mem1
mov out2 12[virtual-signal=signal-exclamation-mark] ; scalar "out2" is output along with dictionary "out" by fCPU.
clr out

; get ingredients for electric furnace.
clr out
mov out1 1[item=electric-furnace] ; send goal product to asr.
mov out2 101[virtual-signal=signal-exclamation-mark] ; recipe device's address is 101.
; concurrent "write" and read is something we wouldn't normally do with a RAM cell etc but it's required for the recipe lookup device.
mov out3 101[virtual-signal=signal-question-mark]
slp 3 ; wait for ingts to arrive at input.  1 tick for write addressing, 1 for asr, 1 for read addressing.  some may have already passed.
xmov mem1 red ; capture ingts to mem vector.
clr out
emit mem1 0[virtual-signal=signal-exclamation-mark] ; strip bus commands out of data.
emit mem1 0[virtual-signal=signal-question-mark]

; write ingts from mem1 to external RAM cell 11.
xmov out mem1 
mov out2 11[virtual-signal=signal-exclamation-mark]
clr out

; read back the product quantities from external RAM cell 12 to mem1.
clr out
mov out2 12[virtual-signal=signal-question-mark]
nop ; wait for read data to arrive.
xmov mem1 red 
clr out

hlt
