/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation. See the file COPYING
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * Copyright (C) 2010 Frank van Maarseveen <frankvm@frankvm.com>
 */

#ifndef _TIMER0_H_
#define _TIMER0_H_

/*
 * 4MHz / 64 / 62.5 yields 1kHz so we can choose either 62 or 63 depending on
 * measurement (RC oscillator is not that precise).
 */
#define T0_MS 62

void		t0_init(void);
void		t0_cleanup(void);
uint32_t	t0_ms(uint32_t start);
void		t0_mswait(uint32_t ms);

/*
 * Return the elapsed time in ticks of 16 us. Usage:
 *
 *	uint8_t start = t0_ticks(0);
 *	...
 *	elapsed = t0_ticks(start);
 */
__attribute__((always_inline))
static inline uint8_t t0_ticks(uint8_t start)
{
	return TCNT0 - start;
}

/*
 * Wait `count' ticks of 16 us. The argument must not exceed 128.
 */
__attribute__((always_inline))
static inline void t0_tickwait(uint8_t count)
{
	uint8_t t = TCNT0 + count;

	while ((int8_t)(TCNT0 - t) < 0)
		;
}

/*
 * Wait until a specific time measured in ticks.
 */
__attribute__((always_inline))
static inline void t0_tickwait_until(uint8_t t)
{
	while ((int8_t)(TCNT0 - t) < 0)
		;
}

#endif