-
Notifications
You must be signed in to change notification settings - Fork 5
/
readCalibration.py
149 lines (121 loc) · 5.79 KB
/
readCalibration.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# StepperServoCAN
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from platform import system
import struct
import sys
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from scipy import optimize
import re
basepath = os.path.dirname(__file__)
## Firmware stores sensor calibration in a following structure with fields written one after another
# typedef struct {
# uint16_t FlashCalData[CALIBRATION_TABLE_SIZE];
# uint16_t status;
# } FlashCalData_t;
ANGLE_STEPS = 65536
class CalibrationRead(object):
def __init__(self):
self._update_cal_table_size()
self.address = 0x0800FC00 #FLASH_PAGE63_ADDR
self.struct = self._create_struct_format(self.cal_size)
self.values =np.array([])
self.status= []
self.wrap_idx = 0
@staticmethod
def _create_struct_format(_calsize):
struct = '<' #ARM has little endian
struct += str(_calsize) + 'H' #cal array
struct += "HHH" #status
return struct
def _update_cal_table_size(self):
#find calibration size in c-code
calibration_h_file = os.path.join(basepath, os.pardir, 'src', 'BSP', 'calibration.h')
with open(calibration_h_file, "r") as f:
for line in f:
if "#define" in line and "CALIBRATION_TABLE_SIZE" in line:
self.cal_size = int(re.search(r'\d+', line).group()) #parse cal size from calibration.h
return
print("Didn't find cal table size in c-code. The output might be wrong")
def dump_eeprom_to_file(self):
#dump eeprom memory for calibration address
if system() == 'Windows':
ret = os.system('ST-LINK_CLI -NoPrompt -Dump ' + hex(self.address) + ' ' + str(struct.calcsize(self.struct)) + ' eepromCals.bin')
else: # Linux
# https://github.com/stlink-org/stlink
ret = os.system('st-flash read' + ' eepromCals.bin' + ' ' + hex(self.address) + ' ' + str(struct.calcsize(self.struct)))
return ret
def load_from_bin(self):
with open(os.path.join(basepath, 'eepromCals.bin'), mode='rb') as dump: # r -read, b -> binary
values_raw = struct.unpack(self.struct, dump.read(struct.calcsize(self.struct)))
self.values = np.array(values_raw[0:self.cal_size])
self.status = values_raw[-3]
self.wrap_idx = self.values.argmin()
def print_cals(self):
print(str(self.cal_size) + " measured values:")
print(self.values)
print("Status: {0:1}"
.format(
self.status
)
)
def fit_func(self, X, a, b, c, d=0, e=0, f=0, g=0, h=0, i=0, j=0, o=0):
A = np.matrix([a, c, e, g, i])
B = (np.matrix([b, d, f, h, j]))
K = np.transpose(np.matrix([8, 4, 2, 1, 100]))*3.14/360
Y = A * np.cos(K*X) + B * np.sin(K*X) + o
Y = Y.A1 #flatten
return Y
def plotcals(self):
interp_gran = int(32768/2)
x = np.linspace(0, 360 - 1/self.cal_size*360, self.cal_size)
x_interp = np.linspace(0, 360 - 1/self.cal_size*360, interp_gran)
y = (self.values - self.values[self.wrap_idx]) / ANGLE_STEPS * 360 #normalize the values to start at 0, instead of tiny angle
y_monot = np.r_[y[self.wrap_idx:], y[0:self.wrap_idx]]
error = (y_monot - x)
y_monot_interp = np.interp(x_interp, np.linspace(0, 360 - 1/self.cal_size*360, self.cal_size), y_monot)
error_interp = (y_monot_interp-x_interp)
start_point_monot = int((self.cal_size-self.wrap_idx)/self.cal_size*interp_gran)-1
plt.figure(1)
ax1 = plt.subplot(2,1,1)
ax1.plot(x,x, x_interp[start_point_monot], y_monot_interp[start_point_monot], '.r', markersize=9)
ax1.plot(x,y,'g')
ax1.legend(("expected angle", "rotation start point", "raw angle")); plt.title("Recorded angles")
error_filter2 = signal.wiener(signal.medfilt(error_interp, 201), 201)
params, params_covariance = optimize.curve_fit(self.fit_func, x_interp, error_interp, p0=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
print(params)
ax2 = plt.subplot(2,1,2, sharex=ax1)
ax2.plot(x, error, 'r-o', markersize=3)
ax2.plot(x_interp[start_point_monot], error_interp[start_point_monot], '.c', linewidth=1, markersize=16)
ax2.plot(x_interp, error_filter2,'k')
ax2.plot(x_interp, self.fit_func(x_interp, *params),'b'); #fitted complex function
# ax2.plot(x, error - self.fit_func(x, *params),'g')
ax2.legend(("calibration data", "rotation start point", "filtered data", "5x cos harmonics fitted", "remaining error after fitting"))
plt.title("Angle errors")
ax2.set_xticks(np.linspace(0, 359, 200), minor=True)
ax2.grid(which='minor', alpha=0.2)
plt.show()
if __name__ == "__main__":
cal = CalibrationRead()
if cal.dump_eeprom_to_file() != 0: # currently uses ST-link tool
response = input("Downloading eeprom failed; continue plotting with old dump..? (y/n):")
if response.lower() != 'y':
sys.exit("Exiting program...")
cal.load_from_bin()
cal.print_cals()
print("Plotting Cal...")
cal.plotcals()