Timer 3 working with slower clock and all 16 bits.
[fw/altos] / src / avr / ao_clock.c
1 /*
2  * Copyright © 2011 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao.h"
19
20 /*
21  * AltOS always cranks the clock to the max frequency
22  */
23
24 void
25 ao_clock_init(void)
26 {
27         /* disable RC clock */
28         CLKSEL0 &= ~(1 << RCE);
29
30         /* Disable PLL */
31         PLLCSR &= ~(1 << PLLE);
32
33         /* Enable external clock */
34         CLKSEL0 |= (1 << EXTE);
35
36         /* wait for external clock to be ready */
37         while ((CLKSTA & (1 << EXTON)) == 0)
38                 ;
39
40         /* select external clock */
41         CLKSEL0 |= (1 << CLKS);
42
43         /* Disable the clock prescaler */
44         cli();
45         CLKPR = (1 << CLKPCE);
46
47         /* Always run the system clock at 8MHz */
48 #if AVR_CLOCK > 12000000UL
49         CLKPR = 1;
50 #else
51         CLKPR = 0;
52 #endif
53         sei();
54
55         /* Set up the PLL to use the crystal */
56
57         /* Use primary system clock as PLL source */
58         PLLFRQ = ((0 << PINMUX) |       /* Use primary clock */
59                   (0 << PLLUSB) |       /* No divide by 2 for USB */
60                   (0 << PLLTM0) |       /* Disable high speed timer */
61                   (0x4 << PDIV0));      /* 48MHz PLL clock */
62
63         /* Set the frequency of the crystal */
64 #if AVR_CLOCK > 12000000UL
65         PLLCSR |= (1 << PINDIV);        /* For 16MHz crystal on Teensy board */
66 #else
67         PLLCSR &= ~(1 << PINDIV);       /* For 8MHz crystal on TeleScience board */
68 #endif
69
70         /* Enable the PLL */
71         PLLCSR |= (1 << PLLE);
72         while (!(PLLCSR & (1 << PLOCK)))
73                 ;
74
75         set_sleep_mode(SLEEP_MODE_IDLE);
76         sleep_enable();
77 }