CPU模拟器延时代码

时间:2015-10-11 19:07:48

标签: assembly cpu

我无法在网上找到这方面的任何信息,所以任何帮助将不胜感激。 我试图将一些涉及时间延迟的示例代码纳入我们已经被告知由我的大学制作的蛇程序中,我们正在运行"微控制器模拟器"。 有人可以解释这段代码是如何工作的吗?我将在下面发布:

; ---------------------------------------------------------------

;  A general purpose time delay procedure.

;  The delay is controlled by the value in AL.

;  When the procedure terminates, the CPU registers are
;  restored to the same values that were present before 
;  the procedure was called. Push, Pop, Pushf and Popf
;  are used to achieve this.  In this example one procedure 
;  is re-used three times.  This re-use is one of the main 
;  advantages of using procedures.

;------ The Main Program ----------------------------------------
Start:
    MOV AL,8    ; A short delay.
    CALL    30  ; Call the procedure at address [30]

    MOV AL,10   ; A middle sized delay.
    CALL    30  ; Call the procedure at address [30]

    MOV AL,20   ; A Longer delay.
    CALL    30  ; Call the procedure at address [30]

JMP Start   ; Jump back to the start.

; ----- Time Delay Procedure Stored At Address [30] -------------
    ORG 30  ; Generate machine code from address [30]

    PUSH    AL  ; Save AL on the stack.
    PUSHF       ; Save the CPU flags on the stack.
Rep:
    DEC AL  ; Subtract one from AL.
    JNZ REP ; Jump back to Rep if AL was not Zero.

    POPF        ; Restore the CPU flags from the stack.
    POP AL  ; Restore AL from the stack.

    RET     ; Return from the procedure.
; ---------------------------------------------------------------
    END
; ---------------------------------------------------------------

如果您需要更多信息,请告诉我们。

1 个答案:

答案 0 :(得分:1)

让我们看一下负责延迟的代码

; ----- Time Delay Procedure Stored At Address [30] -------------
    ORG 30  ; Generate machine code from address [30]

    PUSH    AL  ; Save AL on the stack.
    PUSHF       ; Save the CPU flags on the stack.
Rep:
    DEC AL  ; Subtract one from AL.
    JNZ REP ; Jump back to Rep if AL was not Zero.

    POPF        ; Restore the CPU flags from the stack.
    POP AL  ; Restore AL from the stack.

    RET     ; Return from the procedure.

ORG 30语句确保代码从内存地址30开始。这是您在调用子例程时指定的地址。

然后代码将AL寄存器压入堆栈,因为它即将使用它。 PUSHF保存CPU标志的状态,以便您以后可以检索它们。

DEC AL / JNZ REP部分是一个循环。它迭代的次数与AL中存储的次数相同。

POPF和POP AL在代码启动延迟循环之前恢复事物的状态。具体来说,它会在调用此代码之前将AL和CPU标志保持在调用者放置的相同状态。

RET将控制权返回给调用者。

现在让我们看一下如何调用此代码

MOV AL,8    ; A short delay.
CALL    30  ; Call the procedure at address [30]

为AL指定值8并调用延迟例程,该例程使用ORG 30语句放在内存地址30处。

延迟过程将循环8次,因为您在AL中传入了值8。