🔧 Subroutines Explained

Discover how subroutines work in assembly programming with this interactive demonstration based on a real program that shifts numbers left by 4 positions.

📋 Program Code

Address Label Instruction Comment
100 ORG 100 Main program
101 LDA X Load X
102 BSA SH4 Branch to subroutine
103 STA X Store shifted number
104 LDA Y Load Y
105 BSA SH4 Branch to subroutine again
106 STA Y Store shifted number
107 X, HEX 1234
108 Y, HEX 4321
109 SH4, HEX 0 Store return address here
10A CIL Circulate left once
10B CIL
10C CIL
10D CIL Circulate left fourth time
10E AND MSK Set AC(13-16) to zero
10F BUN SH4 I Return to main program
110 MSK, HEX FFF0 Mask operand

💡 Key Concepts

đŸŽ¯ What is a Subroutine?

A subroutine is a reusable block of code that performs a specific task. Instead of repeating code, we can call the subroutine multiple times.

🔄 BSA Instruction

Branch and Save Address - Saves the return address and jumps to the subroutine. Essential for knowing where to return!

â†Šī¸ Return Mechanism

BUN SH4 I - Uses indirect addressing to return to the saved location in the main program.

âŦ…ī¸ Left Shift Operation

The subroutine shifts bits left by 4 positions using CIL (Circulate Left) instructions, effectively multiplying by 16.

🎮 Interactive Simulator

Watch how the program executes step by step, calling the subroutine twice to shift both X and Y values.

1
2
3
4
5
6
đŸ–Ĩī¸ Execution Console
Ready to execute program...
Click 'Start' to begin simulation
Accumulator (AC)
0000
Program Counter (PC)
100
X Value
1234
Y Value
4321
Return Address (109)
----

🔍 Deep Dive: How It Works

📖 Program Flow

This program demonstrates the power of subroutines by using the same shift-left-4 routine twice:

  1. First, it shifts the value in X (1234₁₆) left by 4 bits
  2. Then, it shifts the value in Y (4321₁₆) left by 4 bits
  3. The subroutine SH4 handles both operations, avoiding code duplication

âš™ī¸ Technical Details

CIL (Circulate Left): Rotates all bits in the accumulator one position left. The leftmost bit moves to the rightmost position.

AND MSK: Uses mask FFF0₁₆ to clear the rightmost 4 bits, ensuring a clean left shift (not rotation).

Mathematical Effect: Left shifting by 4 bits is equivalent to multiplying by 2⁴ = 16.

✨ Benefits of Subroutines

🔄 Code Reusability
Write once, use multiple times
đŸ“Ļ Modularity
Organize code into logical blocks
🐛 Easier Debugging
Fix bugs in one place only
💾 Memory Efficiency
Reduces program size