Class: Rubyboy::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyboy/timer.rb

Instance Method Summary collapse

Constructor Details

#initialize(interrupt) ⇒ Timer

Returns a new instance of Timer.



5
6
7
8
9
10
11
12
# File 'lib/rubyboy/timer.rb', line 5

def initialize(interrupt)
  @div = 0
  @tima = 0
  @tma = 0
  @tac = 0
  @cycles = 0
  @interrupt = interrupt
end

Instance Method Details

#read_byte(byte) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubyboy/timer.rb', line 40

def read_byte(byte)
  case byte
  when 0xff04
    @div >> 8
  when 0xff05
    @tima
  when 0xff06
    @tma
  when 0xff07
    @tac | 0b1111_1000
  end
end

#step(cycles) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rubyboy/timer.rb', line 14

def step(cycles)
  before_cycles = @cycles
  after_cycles = @cycles + cycles
  @cycles = after_cycles & 0xffff

  @div += after_cycles / 256 - before_cycles / 256
  @div &= 0xffff

  return if @tac[2] == 0

  divider = case @tac & 0b11
            when 0b00 then 1024
            when 0b01 then 16
            when 0b10 then 64
            when 0b11 then 256
            end

  tima_diff = (after_cycles / divider - before_cycles / divider)
  @tima += tima_diff

  return if @tima < 256

  @tima = @tma
  @interrupt.request(:timer)
end

#write_byte(byte, value) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rubyboy/timer.rb', line 53

def write_byte(byte, value)
  case byte
  when 0xff04
    @div = 0
    @cycles = 0
  when 0xff05
    @tima = value
  when 0xff06
    @tma = value
  when 0xff07
    @tac = value & 0b111
  end
end