1 // Copyright 2013 Emilie Gillet.
2 //
3 // Author: Emilie Gillet (emilie.o.gillet@gmail.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // THE SOFTWARE.
22 //
23 // See http://creativecommons.org/licenses/MIT/ for more information.
24 //
25 // -----------------------------------------------------------------------------
26 //
27 // CV scaling functions.
28 
29 #include "tides/cv_scaler.h"
30 
31 #include "stmlib/system/storage.h"
32 
33 namespace tides {
34 
35 using namespace stmlib;
36 
37 /* static */
38 const CvScaler::CalibrationData CvScaler::init_calibration_data_ = {
39   65535,  // 64576
40   20653,  // 20030
41   -9387,  // -9364
42   33100,  // 33221
43   -12673  // -12641
44 };
45 
46 Storage<0x8020000, 1> storage;
47 
Init()48 void CvScaler::Init() {
49   if (!storage.ParsimoniousLoad(&calibration_data_, &version_token_)) {
50     calibration_data_ = init_calibration_data_;
51   }
52 }
53 
SaveCalibrationData()54 void CvScaler::SaveCalibrationData() {
55   storage.ParsimoniousSave(calibration_data_, &version_token_);
56 }
57 
Calibrate()58 void CvScaler::Calibrate() {
59   calibration_data_.v_oct_offset = (v_oct_c2_ + v_oct_) >> 1;
60   int32_t delta = v_oct_ - v_oct_c2_;
61   if (delta != 0) {
62     calibration_data_.v_oct_scale = (1 << 15) * (24 << 7) / delta;
63   }
64   calibration_data_.fm_offset = fm_;
65   calibration_data_.level_offset = level_raw_;
66   calibration_data_.fm_scale = calibration_data_.v_oct_scale * 27 / 20;
67   SaveCalibrationData();
68 }
69 
70 }  // namespace tides
71