Merge branch 'master'
[fw/altos] / src / samd21 / ao_tc_samd21.c
1 /*
2  * Copyright © 2019 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, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  */
14
15 #include <ao.h>
16 #include <ao_tc-samd21.h>
17
18 void
19 ao_tc_set(struct samd21_tc *tc, uint8_t channel, uint32_t value)
20 {
21         tc->mode_16.cc[channel] = value;
22 }
23
24 static void
25 ao_tc_init(struct samd21_tc *tc, uint32_t apbcmask)
26 {
27         samd21_pm.apbcmask |= apbcmask;
28
29         /* Reset the device */
30         tc->ctrla = (1 << SAMD21_TC_CTRLA_SWRST);
31
32         while ((tc->ctrla & (1 << SAMD21_TC_CTRLA_SWRST)) != 0 ||
33                (tc->status & (1 << SAMD21_TC_STATUS_SYNCBUSY)) != 0)
34                 ;
35
36         tc->ctrla = ((SAMD21_TC_CTRLA_PRESCSYNC_GCLK << SAMD21_TC_CTRLA_PRESCSYNC) |
37                      (SAMD21_TC_CTRLA_PRESCALER_DIV1 << SAMD21_TC_CTRLA_PRESCALER) |
38                      (SAMD21_TC_CTRLA_WAVEGEN_NPWM << SAMD21_TC_CTRLA_WAVEGEN) |
39                      (SAMD21_TC_CTRLA_MODE_COUNT16) |
40                      (1 << SAMD21_TC_CTRLA_ENABLE));
41         tc->dbgctrl = (1 << SAMD21_TC_DBGCTRL_DBGRUN);
42 }
43
44 void
45 ao_tc_samd21_init(void)
46 {
47         /* SAMD21G18 has only TC3-TC5 */
48         samd21_gclk_clkctrl(0, SAMD21_GCLK_CLKCTRL_ID_TCC2_TC3);
49         samd21_gclk_clkctrl(0, SAMD21_GCLK_CLKCTRL_ID_TC4_TC5);
50
51         ao_tc_init(&samd21_tc3, 1 << SAMD21_PM_APBCMASK_TC3);
52         ao_tc_init(&samd21_tc4, 1 << SAMD21_PM_APBCMASK_TC4);
53         ao_tc_init(&samd21_tc5, 1 << SAMD21_PM_APBCMASK_TC5);
54 }