import time
try:
from machine import Pin
led_fetch = Pin(16, Pin.OUT)
led_decode = Pin(17, Pin.OUT)
led_execute = Pin(18, Pin.OUT)
HARDWARE_DISPONIVEL = True
except ImportError:
HARDWARE_DISPONIVEL = False
def apagar_leds():
if HARDWARE_DISPONIVEL:
led_fetch.value(0)
led_decode.value(0)
led_execute.value(0)
def acender_led(etapa):
apagar_leds()
if HARDWARE_DISPONIVEL:
if etapa == "FETCH":
led_fetch.value(1)
elif etapa == "DECODE":
led_decode.value(1)
elif etapa == "EXECUTE":
led_execute.value(1)
else:
print("[LED simulado] Aceso ->", etapa)
programa = [
"LOAD R0 10",
"LOAD R1 2",
"SUB R0 R1",
"STORE R0 R2",
"LOAD R0 4",
"LOAD R1 3",
"MUL R0 R1",
]
registradores = {
"R0": 0,
"R1": 0,
"R2": 0
}
pc = 0
while pc < len(programa):
print()
print("==============================")
acender_led("FETCH")
instrucao = programa[pc]
print("FETCH")
print("PC =", pc)
print("Instrucao:", instrucao)
time.sleep(1)
acender_led("DECODE")
partes = instrucao.split()
comando = partes[0]
print()
print("DECODE")
print("Comando:", comando)
time.sleep(1)
acender_led("EXECUTE")
print()
print("EXECUTE")
if comando == "LOAD":
registrador = partes[1]
valor = int(partes[2])
registradores[registrador] = valor
print("Carregando", valor, "em", registrador)
elif comando == "ADD":
r1 = partes[1]
r2 = partes[2]
registradores[r1] = registradores[r1] + registradores[r2]
print(r1, "+", r2)
elif comando == "SUB":
r1 = partes[1]
r2 = partes[2]
registradores[r1] = registradores[r1] - registradores[r2]
print(r1, "-", r2)
elif comando == "MUL":
r1 = partes[1]
r2 = partes[2]
registradores[r1] = registradores[r1] * registradores[r2]
print(r1, "*", r2)
elif comando == "STORE":
origem = partes[1]
destino = partes[2]
registradores[destino] = registradores[origem]
print("Copiando", origem, "para", destino)
print()
print("REGISTRADORES")
print("R0 =", registradores["R0"])
print("R1 =", registradores["R1"])
print("R2 =", registradores["R2"])
print("==============================")
time.sleep(1)
# Próxima instrução
pc += 1
apagar_leds()
print()
print("Programa finalizado.")