From 034645154d41ec4586ad6cdb1906aae3f66d6fb0 Mon Sep 17 00:00:00 2001 From: Lauchmelder Date: Sun, 24 Oct 2021 16:52:15 +0200 Subject: [PATCH] added interrupts --- NES Emulator/cpu.c | 49 +++++++++++++++++++++++++++++++++++++++++++++- NES Emulator/cpu.h | 6 ++++++ NES Emulator/ppu.c | 6 ++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/NES Emulator/cpu.c b/NES Emulator/cpu.c index 0ad0cd4..8ffe8bd 100644 --- a/NES Emulator/cpu.c +++ b/NES Emulator/cpu.c @@ -37,6 +37,9 @@ struct CPU* createCPU(struct Bus* parent) cpu->remainingCycles = 7; cpu->totalCycles = 0; + cpu->irq = 0; + cpu->nmi = 0; + cpu->bus = parent; return cpu; } @@ -54,6 +57,40 @@ int tickCPU(struct CPU* cpu) cpu->remainingCycles--; cpu->totalCycles += 1; + if (cpu->remainingCycles == 1) + { + // Handle interrupts + if (cpu->nmi) + { + Push(cpu->bus, cpu->pc.hi); + Push(cpu->bus, cpu->pc.lo); + Push(cpu->bus, cpu->status.raw & 0b11101111); + + cpu->nmi = 0; + + cpu->pc.lo = readBus(cpu->bus, 0xFFFA); + cpu->pc.hi = readBus(cpu->bus, 0xFFFB); + + return 0; + } + + if (!cpu->status.id) + { + if (cpu->irq) + { + Push(cpu->bus, cpu->pc.hi); + Push(cpu->bus, cpu->pc.lo); + Push(cpu->bus, cpu->status.raw & 0b11101111); + + cpu->status.id = 1; + cpu->pc.lo = readBus(cpu->bus, 0xFFFE); + cpu->pc.hi = readBus(cpu->bus, 0xFFFF); + + cpu->irq = 0; + } + } + } + if (cpu->remainingCycles == 0) { fetch(cpu); @@ -189,7 +226,7 @@ void fetch(struct CPU* cpu) void execute(struct CPU* cpu) { - LOG_BUS(cpu->bus); + // LOG_BUS(cpu->bus); switch (cpu->currentOpcode->op) { @@ -795,3 +832,13 @@ void execute(struct CPU* cpu) break; } } + +void IRQ(struct CPU* cpu) +{ + cpu->irq = 1; +} + +void NMI(struct CPU* cpu) +{ + cpu->nmi = 1; +} diff --git a/NES Emulator/cpu.h b/NES Emulator/cpu.h index b4d73e4..dec38e9 100644 --- a/NES Emulator/cpu.h +++ b/NES Emulator/cpu.h @@ -80,6 +80,9 @@ struct CPU Word fetchedAddress; char fetchedRelAddress; + Byte irq; + Byte nmi; + const struct Opcode* currentOpcode; struct Bus* bus; @@ -94,4 +97,7 @@ void tickInstr(struct CPU* cpu); void fetch(struct CPU* cpu); void execute(struct CPU* cpu); +void IRQ(struct CPU* cpu); +void NMI(struct CPU* cpu); + #endif // _CPU_H_ \ No newline at end of file diff --git a/NES Emulator/ppu.c b/NES Emulator/ppu.c index 02c9ac8..0bb8c1a 100644 --- a/NES Emulator/ppu.c +++ b/NES Emulator/ppu.c @@ -4,6 +4,7 @@ #include #include #include "bus.h" +#include "cpu.h" #include "cartridge.h" struct PPU* createPPU(struct Bus* parent) @@ -222,6 +223,11 @@ void ppuWrite(struct PPU* ppu, Word addr, Byte val) int tickPPU(struct PPU* ppu) { + // Do stuff + if (ppu->x == 0 && ppu->y == 241) + NMI(ppu->bus->cpu); + + // Increment counters ppu->x++; if (ppu->x == 341)