APU Sweep
A NES APU sweep unit can be made to periodically adjust a pulse channel's period up or down.
Each sweep unit contains the following: divider, reload flag.
$4001 | EPPP.NSSS | Pulse channel 1 sweep setup (write) |
$4005 | EPPP.NSSS | Pulse channel 2 sweep setup (write) |
bit 7 | E--- ---- | Enabled flag |
bits 6-4 | -PPP ---- | The divider's period is set to P + 1 |
bit 3 | ---- N--- | Negate flag |
bits 2-0 | ---- -SSS | Shift count (number of bits) |
Side effects | Sets the reload flag |
When clocked by the frame counter, the divider is first clocked and then if the reload flag is set, it is cleared and the divider is reloaded.
An internal shifter continuously calculates a result based on the channel's 11-bit raw timer period, but it doesn't change anything. The raw period is first shifted right by shift count. If the negate flag is set, the shifted value's bits are inverted, and additionally on pulse channel 2 only, the inverted value is increased by 1. The intermediate value is added with the channel's raw period, yielding the final shifter result (used below).
When the channel's raw period is less than 8, or the shifter's result is greater than $7FF and the negate flag is clear, the channel is silenced (0 is sent to the mixer) but the channel's raw period is not changed. Otherwise, if the enabled flag is set and the shift count is non-zero, when the divider outputs a clock, the channel's raw period is set to the shifter's result.
Note that the sweep unit can silence a channel even when the enabled flag is clear. To fully disable a sweep unit, write $08 to turn on the negate flag so that the final shifter result is not greater than the channel's period and therefore not greater than $7FF.