summaryrefslogtreecommitdiffstatshomepage
path: root/src/devices/machine/clock.cpp
blob: 15b8320e23df82ca082c2928599638b8d416d3ce (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// license:BSD-3-Clause
// copyright-holders:smf
#include "clock.h"

const device_type CLOCK = &device_creator<clock_device>;

clock_device::clock_device(const machine_config &mconfig, std::string tag, device_t *owner, UINT32 clock)
	: device_t(mconfig, CLOCK, "Clock", tag, owner, clock, "clock", __FILE__),
	m_signal(0),
	m_timer(nullptr),
	m_signal_handler(*this)
{
}

void clock_device::device_start()
{
	m_signal_handler.resolve();

	save_item(NAME(m_signal));
}

void clock_device::device_clock_changed()
{
	update_timer();
}

attotime clock_device::period()
{
	if (m_clock > 0)
		return attotime::from_hz(m_clock * 2);

	return attotime::never;
}

void clock_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
	m_signal = !m_signal;
	m_signal_handler(m_signal);

	m_timer->adjust(period());
}

void clock_device::update_timer()
{
	if (!m_signal_handler.isnull() && m_clock > 0)
	{
		if (m_timer == nullptr)
		{
			m_timer = timer_alloc(0);
			m_timer->adjust(period());
		}
		else
		{
			attotime next = period() - m_timer->elapsed();

			if (next < attotime::zero)
			{
				next = attotime::zero;
			}

			m_timer->adjust(next);
		}
	}
	else if (m_timer != nullptr)
	{
		m_timer->adjust(attotime::never);
	}
}