ao-bringup-avr: Enable crystal clock in blink demo
[fw/altos] / ao-bringup-avr / ao-blink.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 <avr/io.h>
19 #include <avr/interrupt.h>
20 #define F_CPU 16000000UL        // 16 MHz
21 #include <util/delay.h>
22
23 #define LEDOUT          PORTB7
24 #define LEDPORT         PORTB
25 #define LEDDDR          DDRB
26 #define LEDDDRPIN       DD7
27
28 int main(void)
29 {
30         /* disable RC clock */
31         CLKSEL0 &= ~(1 << RCE);
32
33         /* Disable PLL */
34         PLLCSR &= ~(1 << PLLE);
35
36         /* Enable external clock */
37         CLKSEL0 |= (1 << EXTE);
38
39         /* wait for external clock to be ready */
40         while ((CLKSTA & (1 << EXTON)) == 0)
41                 ;
42
43         /* select external clock */
44         CLKSEL0 |= (1 << CLKS);
45
46         /* Disable the clock prescaler */
47         cli();
48         CLKPR = (1 << CLKPCE);
49         CLKPR = 0;
50         sei();
51
52         /* Set up the PLL to use the crystal */
53
54         /* Use primary system clock as PLL source */
55         PLLFRQ = ((0 << PINMUX) |       /* Use primary clock */
56                   (0 << PLLUSB) |       /* No divide by 2 for USB */
57                   (0 << PLLTM0) |       /* Disable high speed timer */
58                   (0x4 << PDIV0));      /* 48MHz PLL clock */
59
60         /* Set the frequency of the crystal */
61         PLLCSR |= (1 << PINDIV);        /* For 16MHz crystal on Teensy board */
62         // PLLCSR &= ~(1 << PINDIV);    /* For 8MHz crystal on TeleScience board */
63
64         /* Enable the PLL */
65         PLLCSR |= (1 << PLLE);
66         while (!(PLLCSR & (1 << PLOCK)))
67                 ;
68
69         LEDDDR |= (1 << LEDDDRPIN);
70
71         while (1) {
72                 LEDPORT |= (1 << LEDOUT);
73                 _delay_ms(1000);
74                 LEDPORT &= ~(1 << LEDOUT);
75                 _delay_ms(1000);
76         }
77 }