usbfanctrl/timer.c

126 lines
3.8 KiB
C

/***************************************************************************
* Copyright (C) 01/2019 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; version 2 of the License, *
* *
* 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. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <avr/interrupt.h>
#include <avr/io.h>
#include "event.h"
#include "timer.h"
/* *********************************************************************** */
#define TIMER_TIM_INIT() { \
TCCR0A = 0x00; \
TCCR0B = 0x00; \
TIMSK0 = (1<<TOIE0); \
}
#define TIMER_TIM_ENABLE() { TCCR0B |= ((1<<CS00) | (1<<CS01)); }
#define TIMER_TIM_DISABLE() { TCCR0B &= ~((1<<CS00) | (1<<CS01)); }
#define TIMER_TIM_RUNNING() (TCCR0B & ((1<<CS00) | (1<<CS01) | (1<<CS02)))
#define TIMER_TIM_RELOAD(x) { TCNT0 = (0xFF - (x)); }
#define TIMER_TIM_VECT TIMER0_OVF_vect
#define TIMER_DIVISOR 64
#define TIMER_IRQFREQ_MS 1
#define TIMER_MSEC2TICKS(x) ((x * F_CPU) / (TIMER_DIVISOR * 1000ULL))
#define TIMER_MSEC2IRQCNT(x) (x / TIMER_IRQFREQ_MS)
static uint16_t m_timers[TIMER_COUNT];
volatile static uint8_t m_timer_ticked;
/* *********************************************************************** */
ISR(TIMER_TIM_VECT)
{
/* 1ms interrupt */
TIMER_TIM_RELOAD(TIMER_MSEC2TICKS(TIMER_IRQFREQ_MS));
m_timer_ticked = 1;
} /* TIM1_OVF_vect */
uint8_t timer_check(uint8_t timer_needed)
{
if (m_timer_ticked)
{
uint8_t i;
m_timer_ticked = 0;
for (i = 0; i < TIMER_COUNT; i++)
{
if (m_timers[i] > 0)
{
m_timers[i]--;
if (m_timers[i] == 0)
{
event_queue(EVENT_TYPE_TIMER_ELAPSED, i, 0);
}
else
{
timer_needed = 1;
}
}
}
/* stop timer */
if (timer_needed == 0)
{
TIMER_TIM_DISABLE();
}
return 1;
}
return 0;
} /* timer_check */
void timer_event_handler(event_entry_t * p_event)
{
if ((p_event->type == EVENT_TYPE_TIMER_SET) &&
(p_event->num < TIMER_COUNT)
)
{
m_timers[p_event->num] = p_event->value;
/* start timer if needed */
if (!TIMER_TIM_RUNNING())
{
TIMER_TIM_RELOAD(TIMER_MSEC2TICKS(TIMER_IRQFREQ_MS));
TIMER_TIM_ENABLE();
}
}
} /* timer_event_handler */
uint8_t timer_need_hw_clock(void)
{
return !!TIMER_TIM_RUNNING();
} /* timer_need_hw_clock */
void timer_init(void)
{
TIMER_TIM_INIT();
TIMER_TIM_RELOAD(TIMER_MSEC2TICKS(TIMER_IRQFREQ_MS));
TIMER_TIM_ENABLE();
} /* timer_init */