Sega Mega Drive/Interrupts

From Sega Retro

CRT televisions and monitors work by firing an electron beam through magnetic coils onto a phosphorescent screen. The magnetic coils direct the beam across the screen from left to right, and top to bottom. When the beam reaches the end of a scanline, it is deactivated and the coils reposition to the beginning of the next line. This period of inactivity is known as HBlank. Likewise, when the beam reaches the end of the final scanline (and thus the end of the frame), it is deactivated and the coils return to the top left of the screen for the next frame. This is a longer period known as VBlank.

VBlank and HBlank.svg
  • red = active scan
  • green = HBlank
  • blue = VBlank

HBlank and horizontal interrupt

During HBlank the Sega Mega Drive can run a small amount of code in a horizontal interrupt. Horizontal interrupts are enabled by the mode register 1 (VDP register 00) and their frequency is controlled by the horizontal interrupt counter (register $0A).

The counter decrements after every scanline, and when it hits 0, a horizontal interrupt occurs and the counter is reset to the initial value. To run a horizontal interrupt every 16 scanlines, set the counter to $10.

Entering a new value into register $0A will only take effect after the current countdown has finished. In other words, a horizontal interrupt occurs after 16 scanlines even if the counter has been set to $20 since the last one. Subsequent interrupts will occur 32 scanlines apart because the new value is only loaded when the counter reaches 0.

Data Changeable during HBlank Effect Example
CRAM Yes Palette changes mid-frame. Unwanted "CRAM dots" appear. Water in Sonic the Hedgehog games.
VSRAM Yes Foreground/background plane is stretched or compressed vertically. Gunstar Heroes title screen.

VBlank and vertical interrupt

VBlank is a longer period than HBlank, and so the vertical interrupt can contain more code. The vertical interrupt is typically when a game will load new data to VRAM, CRAM and VSRAM via DMA. VBlank reliably occurs 60 times a second (50 times a second on PAL consoles), so game logic and music is often tied to it to keep things running at a constant pace. This is done by running a certain amount of code during a frame, then waiting for a vertical interrupt before running it again.