Class: GBRb::Timer

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

Defined Under Namespace

Classes: Counter, Frequency

Constant Summary collapse

DIV_ADDRESS =
0xff04
TIMA_ADDRESS =
0xff05
TMA_ADDRESS =
0xff06
TAC_ADDRESS =
0xff07
ADDRESSES =
[DIV_ADDRESS, TIMA_ADDRESS, TMA_ADDRESS, TAC_ADDRESS]
FREQUENCIES =
{ freq4096:   Frequency.new('4096 Hz', 256),
  freq16384:  Frequency.new('16384 Hz', 64),
  freq65536:  Frequency.new('65536 Hz', 16),
  freq262144: Frequency.new('262144 Hz', 4)
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTimer

Returns a new instance of Timer.



21
22
23
24
25
26
# File 'lib/gbrb/timer.rb', line 21

def initialize
  @div  = Counter.new 'DIV',  :freq16384
  @tima = Counter.new 'TIMA', :freq4096
  @tac  = 0x00
  @tma  = 0x00
end

Instance Attribute Details

#divObject (readonly)

Returns the value of attribute div.



18
19
20
# File 'lib/gbrb/timer.rb', line 18

def div
  @div
end

#irq_handler=(value) ⇒ Object (writeonly)

Sets the attribute irq_handler

Parameters:

  • value

    the value to set the attribute irq_handler to.



19
20
21
# File 'lib/gbrb/timer.rb', line 19

def irq_handler=(value)
  @irq_handler = value
end

#tacObject (readonly)

Returns the value of attribute tac.



18
19
20
# File 'lib/gbrb/timer.rb', line 18

def tac
  @tac
end

#timaObject (readonly)

Returns the value of attribute tima.



18
19
20
# File 'lib/gbrb/timer.rb', line 18

def tima
  @tima
end

#tmaObject (readonly)

Returns the value of attribute tma.



18
19
20
# File 'lib/gbrb/timer.rb', line 18

def tma
  @tma
end

Instance Method Details

#get_frequency(id) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/gbrb/timer.rb', line 65

def get_frequency id
  case id
  when 0
    :freq4096
  when 1
    :freq262144
  when 2
    :freq65536
  when 3
    :freq16384
  end
end

#read_byte(addr) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/gbrb/timer.rb', line 36

def read_byte addr
  case addr
  when DIV_ADDRESS
    @div.value
  when TIMA_ADDRESS
    @tima.value
  when TMA_ADDRESS
    @tma
  when TAC_ADDRESS
    @tac
  end
end

#step(cycles) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/gbrb/timer.rb', line 28

def step cycles
  if @tac & 0x04 == 0x04 and @tima.step cycles
    @irq_handler.irq TIMER_OVERFLOW_IRQ
    @tima.value = @tma
  end
  @div.step cycles
end

#write_byte(addr, value) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/gbrb/timer.rb', line 49

def write_byte addr, value
  case addr
  when DIV_ADDRESS
    @div.value = 0
  when TIMA_ADDRESS
    @tima.value = value
  when TMA_ADDRESS
    @tma = value
  when TAC_ADDRESS
    old_freq = get_frequency(@tac  & 0x03)
    new_freq = get_frequency(value & 0x03)
    @tima.set_frequency new_freq unless old_freq == new_freq
    @tac = value
  end
end