LoginSignup
1
0

More than 5 years have passed since last update.

Simple CPU Simulator with Excel VBA

Posted at

新人研修最初の解説で、コンピュータの基礎を解説する。
「メモリの感覚を身につけられるように」=>「それならExcelでいいんじゃ?」
ということで即席で作った。

Worksheet(1)を以下のように用意する。

Memory Address Command Part Address Part Program Counter Command Register Address Register Accumulator A Accumulator B
100 読み込む 104 100
101 加算する 105
102 書き込み 106
103 終了
104 7
105 5
106

`ExecuteStep'を実行するごとに、Program Counterで指定されたメモリの
命令を実行していく。

MicroComputer
Option Explicit
Private cPC As Range ' ProgramCounter
Private cCR As Range ' CommandRegister
Private cAR As Range ' AddressRegister
Private cAA As Range ' AccumulatorA
Private cAB As Range ' AccumulatorB

Sub Init()
    Set cPC = Worksheets(1).Cells(2, 4)
    Set cCR = Worksheets(1).Cells(2, 5)
    Set cAR = Worksheets(1).Cells(2, 6)
    Set cAA = Worksheets(1).Cells(2, 7)
    Set cAB = Worksheets(1).Cells(2, 8)
End Sub

Sub ExecuteStep()
    Call Init
    Call ReadOneCommand
    Call IncrementProgramCounter
    Call ExecuteOneCommand
End Sub

Sub ReadOneCommand()
    cCR.Value2 = GetCP
    cAR.Value2 = GetAP
End Sub

Function GetCP()
    GetCP = Worksheets(1).Cells(cPC.Value2 - 98, 2)
End Function

Function GetAP()
    GetAP = Worksheets(1).Cells(cPC.Value2 - 98, 3)
End Function

Sub IncrementProgramCounter()
    cPC.Value2 = cPC.Value2 + 1
End Sub

Sub ExecuteOneCommand()
    Select Case cCR.Value2
        Case "読み込む"
            Call CmdLoad
        Case "加算する"
            Call CmdAdd
        Case "書き込み"
            Call CmdStore
        Case "終了"
            Call CmdExit
    End Select
End Sub

Sub CmdLoad()
    cAA.Value2 = Worksheets(1).Cells(cAR.Value2 - 98, 2)
End Sub

Sub CmdAdd()
    cAB.Value2 = Worksheets(1).Cells(cAR.Value2 - 98, 2)
    cAA.Value2 = cAA.Value2 + cAB.Value2
End Sub

Sub CmdStore()
    Worksheets(1).Cells(cAR.Value2 - 98, 2).Value2 = cAA.Value2
End Sub

Sub CmdExit()
    MsgBox ("Exit")
End Sub

マルチコアのシミュレータにならんかな。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0