81640ce8af72a8678c51158678c063e94f9562c8
[fw/altos] / src / kernel / ao_freq.c
1 /*
2  * Copyright © 2012 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  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #include <ao.h>
20
21 /*
22  * The provided 'calibration' value is
23  * that needed to tune the radio to precisely 434550kHz.
24  * Use that to 'walk' to the target frequency by following
25  * a 'bresenham' line from 434550kHz to the target
26  * frequency, and updating the radio setting along the way
27  */
28
29 int32_t ao_freq_to_set(int32_t freq, int32_t cal) 
30 {
31         static int32_t  set;
32         static uint8_t  neg;
33         static int32_t  error;
34
35         set = 0;
36         neg = 0;
37         error = -434550 / 2;
38
39         if ((freq -= 434550) < 0) {
40                 neg = 1;
41                 freq = -freq;
42         }
43         for (;;) {
44                 if (error > 0) {
45                         error -= 434550;
46                         set++;
47                 } else {
48                         error += cal;
49                         if (--freq < 0)
50                                 break;
51                 }
52         }
53         if (neg)
54                 set = -set;
55         return cal + set;
56 }