Subversion Repositories NaviCtrl

Rev

Rev 489 | Rev 500 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 489 Rev 492
1
/*#######################################################################################*/
1
/*#######################################################################################*/
2
/* !!! THIS IS NOT FREE SOFTWARE !!!                                                     */
2
/* !!! THIS IS NOT FREE SOFTWARE !!!                                                     */
3
/*#######################################################################################*/
3
/*#######################################################################################*/
4
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5
// + www.MikroKopter.com
5
// + www.MikroKopter.com
6
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7
// + Software Nutzungsbedingungen (english version: see below)
7
// + Software Nutzungsbedingungen (english version: see below)
8
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
8
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
9
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
9
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
10
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
10
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
11
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
11
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
12
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
12
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
13
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
14
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
15
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
15
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
16
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
16
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
17
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
17
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
18
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
18
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
19
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
19
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
20
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
20
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
21
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
21
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
22
// + des Mitverschuldens offen.
22
// + des Mitverschuldens offen.
23
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
23
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
24
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
24
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
25
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
25
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
26
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
26
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
27
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
27
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
28
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
28
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
29
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
29
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
30
// +  Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
30
// +  Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
31
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
31
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
32
// + Software LICENSING TERMS
32
// + Software LICENSING TERMS
33
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
33
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
34
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
34
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
35
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
35
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
36
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
36
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
37
// + The Software may only be used with the Licensor's products.
37
// + The Software may only be used with the Licensor's products.
38
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
38
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
39
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
39
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
40
// + agreement shall be the property of the Licensor.
40
// + agreement shall be the property of the Licensor.
41
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
41
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
42
// + features that can be used to identify the program may not be altered or defaced by the customer.
42
// + features that can be used to identify the program may not be altered or defaced by the customer.
43
// + The customer shall be responsible for taking reasonable precautions
43
// + The customer shall be responsible for taking reasonable precautions
44
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
44
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
45
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
45
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
46
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
46
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
47
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
47
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
48
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
48
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
49
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
49
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
50
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
50
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
51
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
51
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
52
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
52
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
53
// + #### END OF LICENSING TERMS ####
53
// + #### END OF LICENSING TERMS ####
54
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
54
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
55
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
55
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
56
#include <math.h>
56
#include <math.h>
57
#include <stdio.h>
57
#include <stdio.h>
58
#include <stdlib.h>
58
#include <stdlib.h>
59
#include <string.h>
59
#include <string.h>
60
#include "91x_lib.h"
60
#include "91x_lib.h"
61
#include "ncmag.h"
61
#include "ncmag.h"
62
#include "i2c.h"
62
#include "i2c.h"
63
#include "timer1.h"
63
#include "timer1.h"
64
#include "led.h"
64
#include "led.h"
65
#include "uart1.h"
65
#include "uart1.h"
66
#include "eeprom.h"
66
#include "eeprom.h"
67
#include "mymath.h"
67
#include "mymath.h"
68
#include "main.h"
68
#include "main.h"
69
#include "spi_slave.h"
69
#include "spi_slave.h"
70
 
70
 
71
u8 NCMAG_Present = 0;
71
u8 NCMAG_Present = 0;
72
u8 NCMAG_IsCalibrated = 0;
72
u8 NCMAG_IsCalibrated = 0;
73
 
73
 
74
 
74
 
75
// supported magnetic sensor types
75
// supported magnetic sensor types
76
#define TYPE_NONE                       0
76
#define TYPE_NONE                       0
77
#define TYPE_HMC5843            1
77
#define TYPE_HMC5843            1
78
#define TYPE_LSM303DLH          2
78
#define TYPE_LSM303DLH          2
79
#define TYPE_LSM303DLM          3
79
#define TYPE_LSM303DLM          3
80
 
80
 
81
u8 NCMAG_SensorType = TYPE_NONE;
81
u8 NCMAG_SensorType = TYPE_NONE;
82
u8 NCMAG_Orientation = 0; // 0 means unknown!
82
u8 NCMAG_Orientation = 0; // 0 means unknown!
83
 
83
 
84
// two calibrtion sets for extern and intern sensor
84
// two calibrtion sets for extern and intern sensor
85
#define EEPROM_ADR_MAG_CALIBRATION_INTERN       50
85
#define EEPROM_ADR_MAG_CALIBRATION_INTERN       50
86
#define EEPROM_ADR_MAG_CALIBRATION_EXTERN   70
86
#define EEPROM_ADR_MAG_CALIBRATION_EXTERN   70
87
 
87
 
88
#define CALIBRATION_VERSION                     1
88
#define CALIBRATION_VERSION                     1
89
#define MAG_CALIBRATION_COMPATIBLE              0xA2
89
#define MAG_CALIBRATION_COMPATIBLE              0xA2
90
 
90
 
91
#define NCMAG_MIN_RAWVALUE -2047
91
#define NCMAG_MIN_RAWVALUE -2047
92
#define NCMAG_MAX_RAWVALUE  2047
92
#define NCMAG_MAX_RAWVALUE  2047
93
#define NCMAG_INVALID_DATA -4096
93
#define NCMAG_INVALID_DATA -4096
94
 
94
 
95
typedef struct
95
typedef struct
96
{
96
{
97
        s16 Range;
97
        s16 Range;
98
        s16 Offset;
98
        s16 Offset;
99
} __attribute__((packed)) Scaling_t;
99
} __attribute__((packed)) Scaling_t;
100
 
100
 
101
typedef struct
101
typedef struct
102
{
102
{
103
        Scaling_t MagX;
103
        Scaling_t MagX;
104
        Scaling_t MagY;
104
        Scaling_t MagY;
105
        Scaling_t MagZ;
105
        Scaling_t MagZ;
106
        u8 Version;
106
        u8 Version;
107
        u8 crc;
107
        u8 crc;
108
} __attribute__((packed)) Calibration_t;
108
} __attribute__((packed)) Calibration_t;
109
 
109
 
110
Calibration_t Calibration;              // calibration data in RAM
110
Calibration_t Calibration;              // calibration data in RAM
111
volatile s16vec_t AccRawVector;
111
volatile s16vec_t AccRawVector;
112
volatile s16vec_t MagRawVector;
112
volatile s16vec_t MagRawVector;
113
 
113
 
114
// i2c MAG interface
114
// i2c MAG interface
115
#define MAG_SLAVE_ADDRESS       0x3C    // i2C slave address mag. sensor registers
115
#define MAG_SLAVE_ADDRESS       0x3C    // i2C slave address mag. sensor registers
116
 
116
 
117
// register mapping
117
// register mapping
118
#define REG_MAG_CRA                     0x00
118
#define REG_MAG_CRA                     0x00
119
#define REG_MAG_CRB                     0x01
119
#define REG_MAG_CRB                     0x01
120
#define REG_MAG_MODE            0x02
120
#define REG_MAG_MODE            0x02
121
#define REG_MAG_DATAX_MSB       0x03
121
#define REG_MAG_DATAX_MSB       0x03
122
#define REG_MAG_DATAX_LSB       0x04
122
#define REG_MAG_DATAX_LSB       0x04
123
#define REG_MAG_DATAY_MSB       0x05
123
#define REG_MAG_DATAY_MSB       0x05
124
#define REG_MAG_DATAY_LSB       0x06
124
#define REG_MAG_DATAY_LSB       0x06
125
#define REG_MAG_DATAZ_MSB       0x07
125
#define REG_MAG_DATAZ_MSB       0x07
126
#define REG_MAG_DATAZ_LSB       0x08
126
#define REG_MAG_DATAZ_LSB       0x08
127
#define REG_MAG_STATUS          0x09
127
#define REG_MAG_STATUS          0x09
128
 
128
 
129
#define REG_MAG_IDA                     0x0A
129
#define REG_MAG_IDA                     0x0A
130
#define REG_MAG_IDB                     0x0B
130
#define REG_MAG_IDB                     0x0B
131
#define REG_MAG_IDC                     0x0C
131
#define REG_MAG_IDC                     0x0C
132
#define REG_MAG_IDF                     0x0F  // WHO_AM_I _M = 0x03c when LSM303DLM is connected
132
#define REG_MAG_IDF                     0x0F  // WHO_AM_I _M = 0x03c when LSM303DLM is connected
133
 
133
 
134
// bit mask for configuration mode
134
// bit mask for configuration mode
135
#define CRA_MODE_MASK           0x03
135
#define CRA_MODE_MASK           0x03
136
#define CRA_MODE_NORMAL         0x00    //default
136
#define CRA_MODE_NORMAL         0x00    //default
137
#define CRA_MODE_POSBIAS        0x01
137
#define CRA_MODE_POSBIAS        0x01
138
#define CRA_MODE_NEGBIAS        0x02
138
#define CRA_MODE_NEGBIAS        0x02
139
#define CRA_MODE_SELFTEST       0x03
139
#define CRA_MODE_SELFTEST       0x03
140
 
140
 
141
// bit mask for measurement mode
141
// bit mask for measurement mode
142
#define MODE_MASK                       0xFF
142
#define MODE_MASK                       0xFF
143
#define MODE_CONTINUOUS         0x00
143
#define MODE_CONTINUOUS         0x00
144
#define MODE_SINGLE                     0x01    // default
144
#define MODE_SINGLE                     0x01    // default
145
#define MODE_IDLE                       0x02
145
#define MODE_IDLE                       0x02
146
#define MODE_SLEEP                      0x03
146
#define MODE_SLEEP                      0x03
147
 
147
 
148
// bit mask for rate
148
// bit mask for rate
149
#define CRA_RATE_MASK           0x1C
149
#define CRA_RATE_MASK           0x1C
150
 
150
 
151
// bit mask for gain
151
// bit mask for gain
152
#define CRB_GAIN_MASK           0xE0
152
#define CRB_GAIN_MASK           0xE0
153
 
153
 
154
// ids
154
// ids
155
#define MAG_IDA         0x48
155
#define MAG_IDA         0x48
156
#define MAG_IDB         0x34
156
#define MAG_IDB         0x34
157
#define MAG_IDC         0x33
157
#define MAG_IDC         0x33
158
#define MAG_IDF_LSM303DLM       0x3C
158
#define MAG_IDF_LSM303DLM       0x3C
159
 
159
 
160
// the special HMC5843 interface
160
// the special HMC5843 interface
161
// bit mask for rate
161
// bit mask for rate
162
#define HMC5843_CRA_RATE_0_5HZ          0x00
162
#define HMC5843_CRA_RATE_0_5HZ          0x00
163
#define HMC5843_CRA_RATE_1HZ            0x04
163
#define HMC5843_CRA_RATE_1HZ            0x04
164
#define HMC5843_CRA_RATE_2HZ            0x08
164
#define HMC5843_CRA_RATE_2HZ            0x08
165
#define HMC5843_CRA_RATE_5HZ            0x0C
165
#define HMC5843_CRA_RATE_5HZ            0x0C
166
#define HMC5843_CRA_RATE_10HZ           0x10    //default
166
#define HMC5843_CRA_RATE_10HZ           0x10    //default
167
#define HMC5843_CRA_RATE_20HZ           0x14
167
#define HMC5843_CRA_RATE_20HZ           0x14
168
#define HMC5843_CRA_RATE_50HZ           0x18
168
#define HMC5843_CRA_RATE_50HZ           0x18
169
// bit mask for gain
169
// bit mask for gain
170
#define HMC5843_CRB_GAIN_07GA           0x00
170
#define HMC5843_CRB_GAIN_07GA           0x00
171
#define HMC5843_CRB_GAIN_10GA           0x20    //default
171
#define HMC5843_CRB_GAIN_10GA           0x20    //default
172
#define HMC5843_CRB_GAIN_15GA           0x40    // <--- we use this
172
#define HMC5843_CRB_GAIN_15GA           0x40    // <--- we use this
173
#define HMC5843_CRB_GAIN_20GA           0x60
173
#define HMC5843_CRB_GAIN_20GA           0x60
174
#define HMC5843_CRB_GAIN_32GA           0x80
174
#define HMC5843_CRB_GAIN_32GA           0x80
175
#define HMC5843_CRB_GAIN_38GA           0xA0
175
#define HMC5843_CRB_GAIN_38GA           0xA0
176
#define HMC5843_CRB_GAIN_45GA           0xC0
176
#define HMC5843_CRB_GAIN_45GA           0xC0
177
#define HMC5843_CRB_GAIN_65GA           0xE0
177
#define HMC5843_CRB_GAIN_65GA           0xE0
178
// self test value
178
// self test value
179
#define HMC5843_TEST_XSCALE             555
179
#define HMC5843_TEST_XSCALE             555
180
#define HMC5843_TEST_YSCALE             555
180
#define HMC5843_TEST_YSCALE             555
181
#define HMC5843_TEST_ZSCALE             555
181
#define HMC5843_TEST_ZSCALE             555
182
// calibration range
182
// calibration range
183
#define HMC5843_CALIBRATION_RANGE   600
183
#define HMC5843_CALIBRATION_RANGE   600
184
 
184
 
185
// the special LSM302DLH interface
185
// the special LSM302DLH interface
186
// bit mask for rate
186
// bit mask for rate
187
#define LSM303DLH_CRA_RATE_0_75HZ       0x00
187
#define LSM303DLH_CRA_RATE_0_75HZ       0x00
188
#define LSM303DLH_CRA_RATE_1_5HZ        0x04
188
#define LSM303DLH_CRA_RATE_1_5HZ        0x04
189
#define LSM303DLH_CRA_RATE_3_0HZ        0x08
189
#define LSM303DLH_CRA_RATE_3_0HZ        0x08
190
#define LSM303DLH_CRA_RATE_7_5HZ        0x0C
190
#define LSM303DLH_CRA_RATE_7_5HZ        0x0C
191
#define LSM303DLH_CRA_RATE_15HZ         0x10    //default
191
#define LSM303DLH_CRA_RATE_15HZ         0x10    //default
192
#define LSM303DLH_CRA_RATE_30HZ         0x14
192
#define LSM303DLH_CRA_RATE_30HZ         0x14
193
#define LSM303DLH_CRA_RATE_75HZ         0x18
193
#define LSM303DLH_CRA_RATE_75HZ         0x18
194
 
194
 
195
// bit mask for gain
195
// bit mask for gain
196
#define LSM303DLH_CRB_GAIN_XXGA         0x00
196
#define LSM303DLH_CRB_GAIN_XXGA         0x00
197
#define LSM303DLH_CRB_GAIN_13GA         0x20    //default
197
#define LSM303DLH_CRB_GAIN_13GA         0x20    //default
198
#define LSM303DLH_CRB_GAIN_19GA         0x40    // <--- we use this
198
#define LSM303DLH_CRB_GAIN_19GA         0x40    // <--- we use this
199
#define LSM303DLH_CRB_GAIN_25GA         0x60
199
#define LSM303DLH_CRB_GAIN_25GA         0x60
200
#define LSM303DLH_CRB_GAIN_40GA         0x80
200
#define LSM303DLH_CRB_GAIN_40GA         0x80
201
#define LSM303DLH_CRB_GAIN_47GA         0xA0
201
#define LSM303DLH_CRB_GAIN_47GA         0xA0
202
#define LSM303DLH_CRB_GAIN_56GA         0xC0
202
#define LSM303DLH_CRB_GAIN_56GA         0xC0
203
#define LSM303DLH_CRB_GAIN_81GA         0xE0
203
#define LSM303DLH_CRB_GAIN_81GA         0xE0
204
 
204
 
205
typedef struct
205
typedef struct
206
{
206
{
207
        u8 A;
207
        u8 A;
208
        u8 B;
208
        u8 B;
209
        u8 C;
209
        u8 C;
210
} __attribute__((packed)) Identification_t;
210
} __attribute__((packed)) Identification_t;
211
volatile Identification_t NCMAG_Identification;
211
volatile Identification_t NCMAG_Identification;
212
 
212
 
213
typedef struct
213
typedef struct
214
{
214
{
215
        u8 Sub;
215
        u8 Sub;
216
} __attribute__((packed)) Identification2_t;
216
} __attribute__((packed)) Identification2_t;
217
volatile Identification2_t NCMAG_Identification2;
217
volatile Identification2_t NCMAG_Identification2;
218
 
218
 
219
typedef struct
219
typedef struct
220
{
220
{
221
        u8 cra;
221
        u8 cra;
222
        u8 crb;
222
        u8 crb;
223
        u8 mode;
223
        u8 mode;
224
} __attribute__((packed)) MagConfig_t;
224
} __attribute__((packed)) MagConfig_t;
225
 
225
 
226
volatile MagConfig_t MagConfig;
226
volatile MagConfig_t MagConfig;
227
 
227
 
228
// self test value
228
// self test value
229
#define LSM303DLH_TEST_XSCALE   495
229
#define LSM303DLH_TEST_XSCALE   495
230
#define LSM303DLH_TEST_YSCALE   495
230
#define LSM303DLH_TEST_YSCALE   495
231
#define LSM303DLH_TEST_ZSCALE   470
231
#define LSM303DLH_TEST_ZSCALE   470
232
// clibration range
232
// clibration range
233
#define LSM303_CALIBRATION_RANGE   550
233
#define LSM303_CALIBRATION_RANGE   550
234
 
234
 
235
// the i2c ACC interface
235
// the i2c ACC interface
236
#define ACC_SLAVE_ADDRESS               0x30    // i2c slave for acc. sensor registers
236
#define ACC_SLAVE_ADDRESS               0x30    // i2c slave for acc. sensor registers
237
 
237
 
238
// multiple byte read/write mask
238
// multiple byte read/write mask
239
#define REG_ACC_MASK_AUTOINCREMENT 0x80
239
#define REG_ACC_MASK_AUTOINCREMENT 0x80
240
 
240
 
241
// register mapping
241
// register mapping
242
#define REG_ACC_CTRL1                   0x20
242
#define REG_ACC_CTRL1                   0x20
243
#define REG_ACC_CTRL2                   0x21
243
#define REG_ACC_CTRL2                   0x21
244
#define REG_ACC_CTRL3                   0x22
244
#define REG_ACC_CTRL3                   0x22
245
#define REG_ACC_CTRL4                   0x23
245
#define REG_ACC_CTRL4                   0x23
246
#define REG_ACC_CTRL5                   0x24
246
#define REG_ACC_CTRL5                   0x24
247
#define REG_ACC_HP_FILTER_RESET 0x25
247
#define REG_ACC_HP_FILTER_RESET 0x25
248
#define REG_ACC_REFERENCE               0x26
248
#define REG_ACC_REFERENCE               0x26
249
#define REG_ACC_STATUS                  0x27
249
#define REG_ACC_STATUS                  0x27
250
#define REG_ACC_X_LSB                   0x28
250
#define REG_ACC_X_LSB                   0x28
251
#define REG_ACC_X_MSB                   0x29
251
#define REG_ACC_X_MSB                   0x29
252
#define REG_ACC_Y_LSB                   0x2A
252
#define REG_ACC_Y_LSB                   0x2A
253
#define REG_ACC_Y_MSB                   0x2B
253
#define REG_ACC_Y_MSB                   0x2B
254
#define REG_ACC_Z_LSB                   0x2C
254
#define REG_ACC_Z_LSB                   0x2C
255
#define REG_ACC_Z_MSB                   0x2D
255
#define REG_ACC_Z_MSB                   0x2D
256
 
256
 
257
#define ACC_CRTL1_PM_DOWN               0x00
257
#define ACC_CRTL1_PM_DOWN               0x00
258
#define ACC_CRTL1_PM_NORMAL             0x20
258
#define ACC_CRTL1_PM_NORMAL             0x20
259
#define ACC_CRTL1_PM_LOW_0_5HZ  0x40
259
#define ACC_CRTL1_PM_LOW_0_5HZ  0x40
260
#define ACC_CRTL1_PM_LOW_1HZ    0x60
260
#define ACC_CRTL1_PM_LOW_1HZ    0x60
261
#define ACC_CRTL1_PM_LOW_2HZ    0x80
261
#define ACC_CRTL1_PM_LOW_2HZ    0x80
262
#define ACC_CRTL1_PM_LOW_5HZ    0xA0
262
#define ACC_CRTL1_PM_LOW_5HZ    0xA0
263
#define ACC_CRTL1_PM_LOW_10HZ   0xC0
263
#define ACC_CRTL1_PM_LOW_10HZ   0xC0
264
// Output data rate in normal power mode
264
// Output data rate in normal power mode
265
#define ACC_CRTL1_DR_50HZ               0x00
265
#define ACC_CRTL1_DR_50HZ               0x00
266
#define ACC_CRTL1_DR_100HZ              0x08
266
#define ACC_CRTL1_DR_100HZ              0x08
267
#define ACC_CRTL1_DR_400HZ              0x10
267
#define ACC_CRTL1_DR_400HZ              0x10
268
#define ACC_CRTL1_DR_1000HZ             0x18
268
#define ACC_CRTL1_DR_1000HZ             0x18
269
// axis anable flags
269
// axis anable flags
270
#define ACC_CRTL1_XEN                   0x01
270
#define ACC_CRTL1_XEN                   0x01
271
#define ACC_CRTL1_YEN                   0x02
271
#define ACC_CRTL1_YEN                   0x02
272
#define ACC_CRTL1_ZEN                   0x04
272
#define ACC_CRTL1_ZEN                   0x04
273
 
273
 
274
#define ACC_CRTL2_FILTER8       0x10
274
#define ACC_CRTL2_FILTER8       0x10
275
#define ACC_CRTL2_FILTER16      0x11
275
#define ACC_CRTL2_FILTER16      0x11
276
#define ACC_CRTL2_FILTER32      0x12
276
#define ACC_CRTL2_FILTER32      0x12
277
#define ACC_CRTL2_FILTER64      0x13
277
#define ACC_CRTL2_FILTER64      0x13
278
 
278
 
279
#define ACC_CTRL4_BDU                   0x80 // Block data update, (0: continuos update; 1: output registers not updated between MSB and LSB reading)
279
#define ACC_CTRL4_BDU                   0x80 // Block data update, (0: continuos update; 1: output registers not updated between MSB and LSB reading)
280
#define ACC_CTRL4_BLE                   0x40 // Big/little endian, (0: data LSB @ lower address; 1: data MSB @ lower address)
280
#define ACC_CTRL4_BLE                   0x40 // Big/little endian, (0: data LSB @ lower address; 1: data MSB @ lower address)
281
#define ACC_CTRL4_FS_2G                 0x00
281
#define ACC_CTRL4_FS_2G                 0x00
282
#define ACC_CTRL4_FS_4G                 0x10
282
#define ACC_CTRL4_FS_4G                 0x10
283
#define ACC_CTRL4_FS_8G                 0x30
283
#define ACC_CTRL4_FS_8G                 0x30
284
#define ACC_CTRL4_STSIGN_PLUS   0x00
284
#define ACC_CTRL4_STSIGN_PLUS   0x00
285
#define ACC_CTRL4_STSIGN_MINUS  0x08
285
#define ACC_CTRL4_STSIGN_MINUS  0x08
286
#define ACC_CTRL4_ST_ENABLE             0x02
286
#define ACC_CTRL4_ST_ENABLE             0x02
287
 
287
 
288
#define ACC_CTRL5_STW_ON                0x03
288
#define ACC_CTRL5_STW_ON                0x03
289
#define ACC_CTRL5_STW_OFF               0x00
289
#define ACC_CTRL5_STW_OFF               0x00
290
 
290
 
291
typedef struct
291
typedef struct
292
{
292
{
293
        u8 ctrl_1;
293
        u8 ctrl_1;
294
        u8 ctrl_2;
294
        u8 ctrl_2;
295
        u8 ctrl_3;
295
        u8 ctrl_3;
296
        u8 ctrl_4;
296
        u8 ctrl_4;
297
        u8 ctrl_5;
297
        u8 ctrl_5;
298
} __attribute__((packed)) AccConfig_t;
298
} __attribute__((packed)) AccConfig_t;
299
 
299
 
300
volatile AccConfig_t AccConfig;
300
volatile AccConfig_t AccConfig;
301
 
301
 
302
// write calibration data for external and internal sensor seperately
302
// write calibration data for external and internal sensor seperately
303
u8 NCMag_CalibrationWrite(I2C_TypeDef* I2Cx)
303
u8 NCMag_CalibrationWrite(I2C_TypeDef* I2Cx)
304
{
304
{
305
        u16 address;
305
        u16 address;
306
        u8 i = 0, crc = MAG_CALIBRATION_COMPATIBLE;
306
        u8 i = 0, crc = MAG_CALIBRATION_COMPATIBLE;
307
        EEPROM_Result_t eres;
307
        EEPROM_Result_t eres;
308
        u8 *pBuff = (u8*)&Calibration;
308
        u8 *pBuff = (u8*)&Calibration;
309
 
309
 
310
        if (I2Cx == NCMAG_PORT_EXTERN)
310
        if (I2Cx == NCMAG_PORT_EXTERN)
311
        {
311
        {
312
                address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
312
                address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
313
                Calibration.Version = CALIBRATION_VERSION + (NCMAG_Orientation<<4);;
313
                Calibration.Version = CALIBRATION_VERSION + (NCMAG_Orientation<<4);;
314
        }
314
        }
315
        else if (I2Cx == NCMAG_PORT_INTERN)
315
        else if (I2Cx == NCMAG_PORT_INTERN)
316
        {
316
        {
317
                address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
317
                address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
318
                Calibration.Version = CALIBRATION_VERSION;
318
                Calibration.Version = CALIBRATION_VERSION;
319
        }
319
        }
320
        else return(i);
320
        else return(i);
321
 
321
 
322
        for(i = 0; i<(sizeof(Calibration)-1); i++)
322
        for(i = 0; i<(sizeof(Calibration)-1); i++)
323
        {
323
        {
324
                crc += pBuff[i];
324
                crc += pBuff[i];
325
        }
325
        }
326
        Calibration.crc = ~crc;
326
        Calibration.crc = ~crc;
327
        eres = EEPROM_WriteBlock(address, pBuff, sizeof(Calibration));
327
        eres = EEPROM_WriteBlock(address, pBuff, sizeof(Calibration));
328
        if(EEPROM_SUCCESS == eres) i = 1;
328
        if(EEPROM_SUCCESS == eres) i = 1;
329
        else i = 0;
329
        else i = 0;
330
        return(i);
330
        return(i);
331
}
331
}
332
 
332
 
333
// read calibration data for external and internal sensor seperately
333
// read calibration data for external and internal sensor seperately
334
u8 NCMag_CalibrationRead(I2C_TypeDef* I2Cx)
334
u8 NCMag_CalibrationRead(I2C_TypeDef* I2Cx)
335
{
335
{
336
        u8 address;
336
        u8 address;
337
        u8 i = 0, crc = MAG_CALIBRATION_COMPATIBLE;
337
        u8 i = 0, crc = MAG_CALIBRATION_COMPATIBLE;
338
        u8 *pBuff = (u8*)&Calibration;
338
        u8 *pBuff = (u8*)&Calibration;
339
 
339
 
340
        if (I2Cx == NCMAG_PORT_EXTERN)          address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
340
        if (I2Cx == NCMAG_PORT_EXTERN)          address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
341
        else if (I2Cx == NCMAG_PORT_INTERN) address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
341
        else if (I2Cx == NCMAG_PORT_INTERN) address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
342
        else return(0);
342
        else return(0);
343
 
343
 
344
        if(EEPROM_SUCCESS == EEPROM_ReadBlock(address, pBuff, sizeof(Calibration)))
344
        if(EEPROM_SUCCESS == EEPROM_ReadBlock(address, pBuff, sizeof(Calibration)))
345
        {
345
        {
346
                for(i = 0; i<(sizeof(Calibration)-1); i++)
346
                for(i = 0; i<(sizeof(Calibration)-1); i++)
347
                {
347
                {
348
                        crc += pBuff[i];
348
                        crc += pBuff[i];
349
                }
349
                }
350
                crc = ~crc;
350
                crc = ~crc;
351
                if(Calibration.crc != crc) return(0); // crc mismatch
351
                if(Calibration.crc != crc) return(0); // crc mismatch
352
                if((Calibration.Version & 0x0F) == CALIBRATION_VERSION) return(1);
352
                if((Calibration.Version & 0x0F) == CALIBRATION_VERSION) return(1);
353
        }
353
        }
354
        return(0);
354
        return(0);
355
}
355
}
356
 
356
 
357
 
357
 
358
void NCMAG_Calibrate(void)
358
void NCMAG_Calibrate(void)
359
{
359
{
360
        u8 msg[64];
360
        u8 msg[64];
361
        static u8 speak = 0;
361
        static u8 speak = 0;
362
        static s16 Xmin = 0, Xmax = 0, Ymin = 0, Ymax = 0, Zmin = 0, Zmax = 0, Zmin2 = 0, Zmax2 = 0;;
362
        static s16 Xmin = 0, Xmax = 0, Ymin = 0, Ymax = 0, Zmin = 0, Zmax = 0, Zmin2 = 0, Zmax2 = 0;;
363
        static s16 X = 0, Y = 0, Z = 0;
363
        static s16 X = 0, Y = 0, Z = 0;
364
        static u8 OldCalState = 0;
364
        static u8 OldCalState = 0;
365
        s16 MinCalibration = 450;
365
        s16 MinCalibration = 450;
366
 
366
 
367
        X = (X + MagRawVector.X)/2;
367
        X = (X + MagRawVector.X)/2;
368
        Y = (Y + MagRawVector.Y)/2;
368
        Y = (Y + MagRawVector.Y)/2;
369
        Z = (Z + MagRawVector.Z)/2;
369
        Z = (Z + MagRawVector.Z)/2;
370
 
370
 
371
        switch(Compass_CalState)
371
        switch(Compass_CalState)
372
        {
372
        {
373
                case 1:
373
                case 1:
374
                        // 1st step of calibration
374
                        // 1st step of calibration
375
                        // initialize ranges
375
                        // initialize ranges
376
                        // used to change the orientation of the NC in the horizontal plane
376
                        // used to change the orientation of the NC in the horizontal plane
377
                        Xmin =  10000;
377
                        Xmin =  10000;
378
                        Xmax = -10000;
378
                        Xmax = -10000;
379
                        Ymin =  10000;
379
                        Ymin =  10000;
380
                        Ymax = -10000;
380
                        Ymax = -10000;
381
                        Zmin =  10000;
381
                        Zmin =  10000;
382
                        Zmax = -10000;
382
                        Zmax = -10000;
383
                        speak = 1;
383
                        speak = 1;
384
                        CompassValueErrorCount = 0;
384
                        CompassValueErrorCount = 0;
385
                        if(Compass_CalState != OldCalState) // only once per state
385
                        if(Compass_CalState != OldCalState) // only once per state
386
                        {
386
                        {
387
                                UART1_PutString("\r\nStarting compass calibration");
387
                                UART1_PutString("\r\nStarting compass calibration");
388
                                if(Compass_I2CPort == NCMAG_PORT_EXTERN)
388
                                if(Compass_I2CPort == NCMAG_PORT_EXTERN)
389
                                {
389
                                {
390
                                        if(!NCMAG_Orientation) NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
390
                                        if(!NCMAG_Orientation) NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
391
                                        UART1_PutString(" - External sensor ");
391
                                        UART1_PutString(" - External sensor ");
392
                                        sprintf(msg, "with orientation: %d ", NCMAG_Orientation);
392
                                        sprintf(msg, "with orientation: %d ", NCMAG_Orientation);
393
                                        UART1_PutString(msg);
393
                                        UART1_PutString(msg);
394
                                }
394
                                }
395
                                else UART1_PutString(" - Internal sensor ");
395
                                else UART1_PutString(" - Internal sensor ");
396
                        }
396
                        }
397
                        break;
397
                        break;
398
 
398
 
399
                case 2: // 2nd step of calibration
399
                case 2: // 2nd step of calibration
400
                        // find Min and Max of the X- and Y-Sensors during rotation in the horizontal plane
400
                        // find Min and Max of the X- and Y-Sensors during rotation in the horizontal plane
401
                        if(X < Xmin)            { Xmin = X; BeepTime = 20;}
401
                        if(X < Xmin)            { Xmin = X; BeepTime = 20;}
402
                        else if(X > Xmax)       { Xmax = X; BeepTime = 20;}
402
                        else if(X > Xmax)       { Xmax = X; BeepTime = 20;}
403
                        if(Y < Ymin)            { Ymin = Y; BeepTime = 60;}
403
                        if(Y < Ymin)            { Ymin = Y; BeepTime = 60;}
404
                        else if(Y > Ymax)       { Ymax = Y; BeepTime = 60;}
404
                        else if(Y > Ymax)       { Ymax = Y; BeepTime = 60;}
405
                        if(Z < Zmin)        { Zmin = Z; } // silent
405
                        if(Z < Zmin)        { Zmin = Z; } // silent
406
                        else if(Z > Zmax)   { Zmax = Z; }
406
                        else if(Z > Zmax)   { Zmax = Z; }
407
                        if(speak) SpeakHoTT = SPEAK_CALIBRATE; speak = 0;
407
                        if(speak) SpeakHoTT = SPEAK_CALIBRATE; speak = 0;
408
                        break;
408
                        break;
409
 
409
 
410
                case 3: // 3rd step of calibration
410
                case 3: // 3rd step of calibration
411
                        // used to change the orientation of the MK3MAG vertical to the horizontal plane
411
                        // used to change the orientation of the MK3MAG vertical to the horizontal plane
412
                        speak = 1;
412
                        speak = 1;
413
                        break;
413
                        break;
414
 
414
 
415
                case 4:
415
                case 4:
416
                        // find Min and Max of the Z-Sensor
416
                        // find Min and Max of the Z-Sensor
417
                        if(Z < Zmin2)           { Zmin2 = Z; BeepTime = 80;}
417
                        if(Z < Zmin2)           { Zmin2 = Z; BeepTime = 80;}
418
                        else if(Z > Zmax2)      { Zmax2 = Z; BeepTime = 80;}
418
                        else if(Z > Zmax2)      { Zmax2 = Z; BeepTime = 80;}
419
                        if(X < Xmin)            { Xmin = X; BeepTime = 20;}
419
                        if(X < Xmin)            { Xmin = X; BeepTime = 20;}
420
                        else if(X > Xmax)       { Xmax = X; BeepTime = 20;}
420
                        else if(X > Xmax)       { Xmax = X; BeepTime = 20;}
421
                        if(Y < Ymin)            { Ymin = Y; BeepTime = 60;}
421
                        if(Y < Ymin)            { Ymin = Y; BeepTime = 60;}
422
                        else if(Y > Ymax)       { Ymax = Y; BeepTime = 60;}
422
                        else if(Y > Ymax)       { Ymax = Y; BeepTime = 60;}
423
                        if(speak) SpeakHoTT = SPEAK_CALIBRATE; speak = 0;
423
                        if(speak) SpeakHoTT = SPEAK_CALIBRATE; speak = 0;
424
                        break;
424
                        break;
425
 
425
 
426
                case 5:
426
                case 5:
427
                        // Save values
427
                        // Save values
428
                        if(Compass_CalState != OldCalState) // avoid continously writing of eeprom!
428
                        if(Compass_CalState != OldCalState) // avoid continously writing of eeprom!
429
                        {
429
                        {
430
                                switch(NCMAG_SensorType)
430
                                switch(NCMAG_SensorType)
431
                                {
431
                                {
432
                                        case TYPE_HMC5843:
432
                                        case TYPE_HMC5843:
433
                                                UART1_PutString("\r\nFinished: HMC5843 calibration\n\r");
433
                                                UART1_PutString("\r\nFinished: HMC5843 calibration\n\r");
434
                                                MinCalibration = HMC5843_CALIBRATION_RANGE;
434
                                                MinCalibration = HMC5843_CALIBRATION_RANGE;
435
                                                break;
435
                                                break;
436
 
436
 
437
                                        case TYPE_LSM303DLH:
437
                                        case TYPE_LSM303DLH:
438
                                        case TYPE_LSM303DLM:
438
                                        case TYPE_LSM303DLM:
439
                                                UART1_PutString("\r\nFinished: LSM303 calibration\n\r");
439
                                                UART1_PutString("\r\nFinished: LSM303 calibration\n\r");
440
                                                MinCalibration = LSM303_CALIBRATION_RANGE;
440
                                                MinCalibration = LSM303_CALIBRATION_RANGE;
441
                                                break;
441
                                                break;
442
                                }
442
                                }
443
                                if(EarthMagneticStrengthTheoretic)
443
                                if(EarthMagneticStrengthTheoretic)
444
                                {
444
                                {
445
                                        MinCalibration = (MinCalibration * EarthMagneticStrengthTheoretic) / 50;
445
                                        MinCalibration = (MinCalibration * EarthMagneticStrengthTheoretic) / 50;
446
                                        sprintf(msg, "Earth field on your location should be: %iuT\r\n",EarthMagneticStrengthTheoretic);
446
                                        sprintf(msg, "Earth field on your location should be: %iuT\r\n",EarthMagneticStrengthTheoretic);
447
                                        UART1_PutString(msg);
447
                                        UART1_PutString(msg);
448
                                }
448
                                }
449
                            else UART1_PutString("without GPS\n\r");
449
                            else UART1_PutString("without GPS\n\r");
450
 
450
 
451
                                if(Zmin2 < Zmin) Zmin = Zmin2;
451
                                if(Zmin2 < Zmin) Zmin = Zmin2;
452
                                if(Zmax2 > Zmax) Zmax = Zmax2;
452
                                if(Zmax2 > Zmax) Zmax = Zmax2;
453
                                Calibration.MagX.Range = Xmax - Xmin;
453
                                Calibration.MagX.Range = Xmax - Xmin;
454
                                Calibration.MagX.Offset = (Xmin + Xmax) / 2;
454
                                Calibration.MagX.Offset = (Xmin + Xmax) / 2;
455
                                Calibration.MagY.Range = Ymax - Ymin;
455
                                Calibration.MagY.Range = Ymax - Ymin;
456
                                Calibration.MagY.Offset = (Ymin + Ymax) / 2;
456
                                Calibration.MagY.Offset = (Ymin + Ymax) / 2;
457
                                Calibration.MagZ.Range = Zmax - Zmin;
457
                                Calibration.MagZ.Range = Zmax - Zmin;
458
                                Calibration.MagZ.Offset = (Zmin + Zmax) / 2;
458
                                Calibration.MagZ.Offset = (Zmin + Zmax) / 2;
459
                                if(CompassValueErrorCount)
459
                                if(CompassValueErrorCount)
460
                                {
460
                                {
461
                                        SpeakHoTT = SPEAK_ERR_CALIBARTION;
461
                                        SpeakHoTT = SPEAK_ERR_CALIBARTION;
462
                                        UART1_PutString("\r\nCalibration FAILED - Compass sensor error !!!!\r\n ");
462
                                        UART1_PutString("\r\nCalibration FAILED - Compass sensor error !!!!\r\n ");
463
 
463
 
464
                                }
464
                                }
465
                                else
465
                                else
466
                                if((Calibration.MagX.Range > MinCalibration) && (Calibration.MagY.Range > MinCalibration) && (Calibration.MagZ.Range > MinCalibration))
466
                                if((Calibration.MagX.Range > MinCalibration) && (Calibration.MagY.Range > MinCalibration) && (Calibration.MagZ.Range > MinCalibration))
467
                                {
467
                                {
468
                                        NCMAG_IsCalibrated = NCMag_CalibrationWrite(Compass_I2CPort);
468
                                        NCMAG_IsCalibrated = NCMag_CalibrationWrite(Compass_I2CPort);
469
                                        BeepTime = 2500;
469
                                        BeepTime = 2500;
470
                                        UART1_PutString("\r\n-> Calibration okay <-\n\r");
470
                                        UART1_PutString("\r\n-> Calibration okay <-\n\r");
471
                                        SpeakHoTT = SPEAK_MIKROKOPTER;
471
                                        SpeakHoTT = SPEAK_MIKROKOPTER;
472
                                }
472
                                }
473
                                else
473
                                else
474
                                {
474
                                {
475
                                        SpeakHoTT = SPEAK_ERR_CALIBARTION;
475
                                        SpeakHoTT = SPEAK_ERR_CALIBARTION;
476
                                        UART1_PutString("\r\nCalibration FAILED - Values too low: ");
476
                                        UART1_PutString("\r\nCalibration FAILED - Values too low: ");
477
                                    if(Calibration.MagX.Range < MinCalibration) UART1_PutString("X! ");
477
                                    if(Calibration.MagX.Range < MinCalibration) UART1_PutString("X! ");
478
                                    if(Calibration.MagY.Range < MinCalibration) UART1_PutString("Y! ");
478
                                    if(Calibration.MagY.Range < MinCalibration) UART1_PutString("Y! ");
479
                                    if(Calibration.MagZ.Range < MinCalibration) UART1_PutString("Z! ");
479
                                    if(Calibration.MagZ.Range < MinCalibration) UART1_PutString("Z! ");
480
                                        UART1_PutString("\r\n");
480
                                        UART1_PutString("\r\n");
481
 
481
 
482
                                        // restore old calibration data from eeprom
482
                                        // restore old calibration data from eeprom
483
                                        NCMAG_IsCalibrated = NCMag_CalibrationRead(Compass_I2CPort);
483
                                        NCMAG_IsCalibrated = NCMag_CalibrationRead(Compass_I2CPort);
484
                                }
484
                                }
485
                                        sprintf(msg, "X: (%i - %i = %i)\r\n",Xmax,Xmin,Xmax - Xmin);
485
                                        sprintf(msg, "X: (%i - %i = %i)\r\n",Xmax,Xmin,Xmax - Xmin);
486
                                        UART1_PutString(msg);
486
                                        UART1_PutString(msg);
487
                                        sprintf(msg, "Y: (%i - %i = %i)\r\n",Ymax,Ymin,Ymax - Ymin);
487
                                        sprintf(msg, "Y: (%i - %i = %i)\r\n",Ymax,Ymin,Ymax - Ymin);
488
                                        UART1_PutString(msg);
488
                                        UART1_PutString(msg);
489
                                        sprintf(msg, "Z: (%i - %i = %i)\r\n",Zmax,Zmin,Zmax - Zmin);
489
                                        sprintf(msg, "Z: (%i - %i = %i)\r\n",Zmax,Zmin,Zmax - Zmin);
490
                                        UART1_PutString(msg);
490
                                        UART1_PutString(msg);
491
                                        sprintf(msg, "(Minimum ampilitude is: %i)\r\n",MinCalibration);
491
                                        sprintf(msg, "(Minimum ampilitude is: %i)\r\n",MinCalibration);
492
                                        UART1_PutString(msg);
492
                                        UART1_PutString(msg);
493
                        }
493
                        }
494
                        break;
494
                        break;
495
 
495
 
496
                default:
496
                default:
497
                        break;
497
                        break;
498
        }
498
        }
499
        OldCalState = Compass_CalState;
499
        OldCalState = Compass_CalState;
500
}
500
}
501
 
501
 
502
// ---------- call back handlers -----------------------------------------
502
// ---------- call back handlers -----------------------------------------
503
 
503
 
504
// rx data handler for id info request
504
// rx data handler for id info request
505
void NCMAG_UpdateIdentification(u8* pRxBuffer, u8 RxBufferSize)
505
void NCMAG_UpdateIdentification(u8* pRxBuffer, u8 RxBufferSize)
506
{       // if number of bytes are matching
506
{       // if number of bytes are matching
507
        if(RxBufferSize == sizeof(NCMAG_Identification) )
507
        if(RxBufferSize == sizeof(NCMAG_Identification) )
508
        {
508
        {
509
                memcpy((u8 *)&NCMAG_Identification, pRxBuffer, sizeof(NCMAG_Identification));
509
                memcpy((u8 *)&NCMAG_Identification, pRxBuffer, sizeof(NCMAG_Identification));
510
        }
510
        }
511
}
511
}
512
 
512
 
513
void NCMAG_UpdateIdentification_Sub(u8* pRxBuffer, u8 RxBufferSize)
513
void NCMAG_UpdateIdentification_Sub(u8* pRxBuffer, u8 RxBufferSize)
514
{       // if number of bytes are matching
514
{       // if number of bytes are matching
515
        if(RxBufferSize == sizeof(NCMAG_Identification2))
515
        if(RxBufferSize == sizeof(NCMAG_Identification2))
516
        {
516
        {
517
                memcpy((u8 *)&NCMAG_Identification2, pRxBuffer, sizeof(NCMAG_Identification2));
517
                memcpy((u8 *)&NCMAG_Identification2, pRxBuffer, sizeof(NCMAG_Identification2));
518
        }
518
        }
519
}
519
}
520
 
520
 
521
// rx data handler for magnetic sensor raw data
521
// rx data handler for magnetic sensor raw data
522
void NCMAG_UpdateMagVector(u8* pRxBuffer, u8 RxBufferSize)
522
void NCMAG_UpdateMagVector(u8* pRxBuffer, u8 RxBufferSize)
523
{       // if number of bytes are matching
523
{       // if number of bytes are matching
524
        if(RxBufferSize == sizeof(MagRawVector) )
524
        if(RxBufferSize == sizeof(MagRawVector) )
525
        {       // byte order from big to little endian
525
        {       // byte order from big to little endian
526
                s16 raw, X = 0, Y = 0, Z = 0;
526
                s16 raw, X = 0, Y = 0, Z = 0;
527
                raw = pRxBuffer[0]<<8;
527
                raw = pRxBuffer[0]<<8;
528
                raw+= pRxBuffer[1];
528
                raw+= pRxBuffer[1];
529
                if(raw >= NCMAG_MIN_RAWVALUE && raw <= NCMAG_MAX_RAWVALUE) X = raw;
529
                if(raw >= NCMAG_MIN_RAWVALUE && raw <= NCMAG_MAX_RAWVALUE) X = raw;
530
                else if(CompassValueErrorCount < 35) CompassValueErrorCount++; // invalid data
530
                else if(CompassValueErrorCount < 35) CompassValueErrorCount++; // invalid data
531
 
531
 
532
                raw = pRxBuffer[2]<<8;
532
                raw = pRxBuffer[2]<<8;
533
                raw+= pRxBuffer[3];
533
                raw+= pRxBuffer[3];
534
            if(raw >= NCMAG_MIN_RAWVALUE && raw <= NCMAG_MAX_RAWVALUE)
534
            if(raw >= NCMAG_MIN_RAWVALUE && raw <= NCMAG_MAX_RAWVALUE)
535
                {
535
                {
536
                        if(NCMAG_SensorType == TYPE_LSM303DLM)  Z = raw; // here Z and Y are exchanged
536
                        if(NCMAG_SensorType == TYPE_LSM303DLM)  Z = raw; // here Z and Y are exchanged
537
                        else                                                                    Y = raw;
537
                        else                                                                    Y = raw;
538
                }
538
                }
539
                else if(CompassValueErrorCount < 35) CompassValueErrorCount++; // invalid data
539
                else if(CompassValueErrorCount < 35) CompassValueErrorCount++; // invalid data
540
 
540
 
541
                raw = pRxBuffer[4]<<8;
541
                raw = pRxBuffer[4]<<8;
542
                raw+= pRxBuffer[5];
542
                raw+= pRxBuffer[5];
543
                if(raw >= NCMAG_MIN_RAWVALUE && raw <= NCMAG_MAX_RAWVALUE)
543
                if(raw >= NCMAG_MIN_RAWVALUE && raw <= NCMAG_MAX_RAWVALUE)
544
                {
544
                {
545
                        if(NCMAG_SensorType == TYPE_LSM303DLM)  Y = raw; // here Z and Y are exchanged
545
                        if(NCMAG_SensorType == TYPE_LSM303DLM)  Y = raw; // here Z and Y are exchanged
546
                        else                                                                    Z = raw;
546
                        else                                                                    Z = raw;
547
                }
547
                }
548
                else if(CompassValueErrorCount < 35) CompassValueErrorCount++; // invalid data
548
                else if(CompassValueErrorCount < 35) CompassValueErrorCount++; // invalid data
549
 
549
 
550
                // correct compass orientation
550
                // correct compass orientation
551
                switch(NCMAG_Orientation)
551
                switch(NCMAG_Orientation)
552
                {
552
                {
553
                        case 0:
553
                        case 0:
554
                        case 1:
554
                        case 1:
555
                        default:
555
                        default:
556
                                // 1:1 Mapping
556
                                // 1:1 Mapping
557
                                MagRawVector.X = X;
557
                                MagRawVector.X = X;
558
                                MagRawVector.Y = Y;
558
                                MagRawVector.Y = Y;
559
                                MagRawVector.Z = Z;
559
                                MagRawVector.Z = Z;
560
                                break;
560
                                break;
561
                        case 2:
561
                        case 2:
562
                                MagRawVector.X = -X;
562
                                MagRawVector.X = -X;
563
                                MagRawVector.Y = Y;
563
                                MagRawVector.Y = Y;
564
                                MagRawVector.Z = -Z;
564
                                MagRawVector.Z = -Z;
565
                                break;
565
                                break;
566
                        case 3:
566
                        case 3:
567
                                MagRawVector.X = -Z;
567
                                MagRawVector.X = -Z;
568
                                MagRawVector.Y = Y;
568
                                MagRawVector.Y = Y;
569
                                MagRawVector.Z = X;
569
                                MagRawVector.Z = X;
570
                                break;
570
                                break;
571
                        case 4:
571
                        case 4:
572
                                MagRawVector.X = Z;
572
                                MagRawVector.X = Z;
573
                                MagRawVector.Y = Y;
573
                                MagRawVector.Y = Y;
574
                                MagRawVector.Z = -X;
574
                                MagRawVector.Z = -X;
575
                                break;
575
                                break;
576
                        case 5:
576
                        case 5:
577
                                MagRawVector.X = X;
577
                                MagRawVector.X = X;
578
                                MagRawVector.Y = -Z;
578
                                MagRawVector.Y = -Z;
579
                                MagRawVector.Z = Y;
579
                                MagRawVector.Z = Y;
580
                                break;
580
                                break;
581
                        case 6:
581
                        case 6:
582
                                MagRawVector.X = -X;
582
                                MagRawVector.X = -X;
583
                                MagRawVector.Y = -Z;
583
                                MagRawVector.Y = -Z;
584
                                MagRawVector.Z = -Y;
584
                                MagRawVector.Z = -Y;
585
                                break;
585
                                break;
586
                }
586
                }
587
        }
587
        }
588
        if(Compass_CalState || !NCMAG_IsCalibrated)
588
        if(Compass_CalState || !NCMAG_IsCalibrated)
589
        {       // mark out data invalid
589
        {       // mark out data invalid
590
                MagVector.X = MagRawVector.X;
590
                MagVector.X = MagRawVector.X;
591
                MagVector.Y = MagRawVector.Y;
591
                MagVector.Y = MagRawVector.Y;
592
                MagVector.Z = MagRawVector.Z;
592
                MagVector.Z = MagRawVector.Z;
593
                Compass_Heading = -1;
593
                Compass_Heading = -1;
594
        }
594
        }
595
        else
595
        else
596
        {
596
        {
597
                // update MagVector from MagRaw Vector by Scaling
597
                // update MagVector from MagRaw Vector by Scaling
598
                MagVector.X = (s16)((1024L*(s32)(MagRawVector.X - Calibration.MagX.Offset))/Calibration.MagX.Range);
598
                MagVector.X = (s16)((1024L*(s32)(MagRawVector.X - Calibration.MagX.Offset))/Calibration.MagX.Range);
599
                MagVector.Y = (s16)((1024L*(s32)(MagRawVector.Y - Calibration.MagY.Offset))/Calibration.MagY.Range);
599
                MagVector.Y = (s16)((1024L*(s32)(MagRawVector.Y - Calibration.MagY.Offset))/Calibration.MagY.Range);
600
                MagVector.Z = (s16)((1024L*(s32)(MagRawVector.Z - Calibration.MagZ.Offset))/Calibration.MagZ.Range);
600
                MagVector.Z = (s16)((1024L*(s32)(MagRawVector.Z - Calibration.MagZ.Offset))/Calibration.MagZ.Range);
601
                Compass_CalcHeading();
601
                Compass_CalcHeading();
602
        }
602
        }
603
}
603
}
604
// rx data handler  for acceleration raw data
604
// rx data handler  for acceleration raw data
605
void NCMAG_UpdateAccVector(u8* pRxBuffer, u8 RxBufferSize)
605
void NCMAG_UpdateAccVector(u8* pRxBuffer, u8 RxBufferSize)
606
{       // if number of bytes are matching
606
{       // if number of bytes are matching
607
        if(RxBufferSize == sizeof(AccRawVector) )
607
        if(RxBufferSize == sizeof(AccRawVector) )
608
        {
608
        {
609
                // copy from I2C buffer
609
                // copy from I2C buffer
610
                memcpy((u8*)&AccRawVector, pRxBuffer,sizeof(AccRawVector));
610
                memcpy((u8*)&AccRawVector, pRxBuffer,sizeof(AccRawVector));
611
                // scale and update Acc Vector, at the moment simply 1:1
611
                // scale and update Acc Vector, at the moment simply 1:1
612
                memcpy((u8*)&AccVector, (u8*)&AccRawVector,sizeof(AccRawVector));
612
                memcpy((u8*)&AccVector, (u8*)&AccRawVector,sizeof(AccRawVector));
613
        }
613
        }
614
}
614
}
615
// rx data handler for reading magnetic sensor configuration
615
// rx data handler for reading magnetic sensor configuration
616
void NCMAG_UpdateMagConfig(u8* pRxBuffer, u8 RxBufferSize)
616
void NCMAG_UpdateMagConfig(u8* pRxBuffer, u8 RxBufferSize)
617
{       // if number of byte are matching
617
{       // if number of byte are matching
618
        if(RxBufferSize == sizeof(MagConfig) )
618
        if(RxBufferSize == sizeof(MagConfig) )
619
        {
619
        {
620
                memcpy((u8*)(&MagConfig), pRxBuffer, sizeof(MagConfig));
620
                memcpy((u8*)(&MagConfig), pRxBuffer, sizeof(MagConfig));
621
        }
621
        }
622
}
622
}
623
// rx data handler for reading acceleration sensor configuration
623
// rx data handler for reading acceleration sensor configuration
624
void NCMAG_UpdateAccConfig(u8* pRxBuffer, u8 RxBufferSize)
624
void NCMAG_UpdateAccConfig(u8* pRxBuffer, u8 RxBufferSize)
625
{       // if number of byte are matching
625
{       // if number of byte are matching
626
        if(RxBufferSize == sizeof(AccConfig) )
626
        if(RxBufferSize == sizeof(AccConfig) )
627
        {
627
        {
628
                memcpy((u8*)&AccConfig, pRxBuffer, sizeof(AccConfig));
628
                memcpy((u8*)&AccConfig, pRxBuffer, sizeof(AccConfig));
629
        }
629
        }
630
}
630
}
631
//----------------------------------------------------------------------
631
//----------------------------------------------------------------------
632
 
632
 
633
u8 NCMAG_GetOrientationFromAcc(void)
633
u8 NCMAG_GetOrientationFromAcc(void)
634
{
634
{
635
        // only if external compass connected
635
        // only if external compass connected
636
        if(Compass_I2CPort != NCMAG_PORT_EXTERN) return(0);
636
        if(Compass_I2CPort != NCMAG_PORT_EXTERN) return(0);
637
         // MK must not be tilted
637
         // MK must not be tilted
638
        if((abs(FromFlightCtrl.AngleNick) > 300) || (abs(FromFlightCtrl.AngleRoll) > 300))
638
        if((abs(FromFlightCtrl.AngleNick) > 300) || (abs(FromFlightCtrl.AngleRoll) > 300))
639
        {
639
        {
640
//              UART1_PutString("\r\nTilted");
640
//              UART1_PutString("\r\nTilted");
641
                return(0);
641
                return(0);
642
        }
642
        }
643
        // select orientation
643
        // select orientation
644
        if(AccRawVector.Z >  3300) return(1); // Flach - Bestückung oben - Pfeil nach vorn
644
        if(AccRawVector.Z >  3300) return(1); // Flach - Bestückung oben - Pfeil nach vorn
645
        else
645
        else
646
        if(AccRawVector.Z < -3300) return(2); // Flach - Bestückung unten - Pfeil nach vorn
646
        if(AccRawVector.Z < -3300) return(2); // Flach - Bestückung unten - Pfeil nach vorn
647
        else
647
        else
648
        if(AccRawVector.X >  3300) return(3); // Flach - Bestückung Links - Pfeil nach vorn
648
        if(AccRawVector.X >  3300) return(3); // Flach - Bestückung Links - Pfeil nach vorn
649
        else
649
        else
650
        if(AccRawVector.X < -3300) return(4); // Flach - Bestückung rechts - Pfeil nach vorn
650
        if(AccRawVector.X < -3300) return(4); // Flach - Bestückung rechts - Pfeil nach vorn
651
        else
651
        else
652
        if(AccRawVector.Y >  3300) return(5); // Stehend - Pfeil nach oben - 'front' nach vorn
652
        if(AccRawVector.Y >  3300) return(5); // Stehend - Pfeil nach oben - 'front' nach vorn
653
        else
653
        else
654
        if(AccRawVector.Y < -3300) return(6); // Stehend - Pfeil nach unten  - 'front' nach vorn
654
        if(AccRawVector.Y < -3300) return(6); // Stehend - Pfeil nach unten  - 'front' nach vorn
655
        return(0);
655
        return(0);
656
}
656
}
657
 
657
 
658
// ---------------------------------------------------------------------
658
// ---------------------------------------------------------------------
659
u8 NCMAG_SetMagConfig(void)
659
u8 NCMAG_SetMagConfig(void)
660
{
660
{
661
        u8 retval = 0;
661
        u8 retval = 0;
662
 
662
 
663
        // try to catch the i2c buffer within 100 ms timeout
663
        // try to catch the i2c buffer within 100 ms timeout
664
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
664
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
665
        {
665
        {
666
                u8 TxBytes = 0;
666
                u8 TxBytes = 0;
667
                u8 TxData[sizeof(MagConfig) + 3];
667
                u8 TxData[sizeof(MagConfig) + 3];
668
 
668
 
669
                TxData[TxBytes++] = REG_MAG_CRA;
669
                TxData[TxBytes++] = REG_MAG_CRA;
670
                memcpy(&TxData[TxBytes], (u8*)&MagConfig, sizeof(MagConfig));
670
                memcpy(&TxData[TxBytes], (u8*)&MagConfig, sizeof(MagConfig));
671
                TxBytes += sizeof(MagConfig);
671
                TxBytes += sizeof(MagConfig);
672
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, 0, 0))
672
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, 0, 0))
673
                {
673
                {
674
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
674
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
675
                        {
675
                        {
676
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
676
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
677
                        }
677
                        }
678
                }
678
                }
679
        }
679
        }
680
        return(retval);
680
        return(retval);
681
}
681
}
682
 
682
 
683
// ----------------------------------------------------------------------------------------
683
// ----------------------------------------------------------------------------------------
684
u8 NCMAG_GetMagConfig(void)
684
u8 NCMAG_GetMagConfig(void)
685
{
685
{
686
        u8 retval = 0;
686
        u8 retval = 0;
687
        // try to catch the i2c buffer within 100 ms timeout
687
        // try to catch the i2c buffer within 100 ms timeout
688
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
688
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
689
        {
689
        {
690
                u8 TxBytes = 0;
690
                u8 TxBytes = 0;
691
                u8 TxData[3];
691
                u8 TxData[3];
692
                TxData[TxBytes++] = REG_MAG_CRA;
692
                TxData[TxBytes++] = REG_MAG_CRA;
693
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateMagConfig, sizeof(MagConfig)))
693
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateMagConfig, sizeof(MagConfig)))
694
                {
694
                {
695
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
695
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
696
                        {
696
                        {
697
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
697
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
698
                        }
698
                        }
699
                }
699
                }
700
        }
700
        }
701
        return(retval);
701
        return(retval);
702
}
702
}
703
 
703
 
704
// ----------------------------------------------------------------------------------------
704
// ----------------------------------------------------------------------------------------
705
u8 NCMAG_SetAccConfig(void)
705
u8 NCMAG_SetAccConfig(void)
706
{
706
{
707
        u8 retval = 0;
707
        u8 retval = 0;
708
        // try to catch the i2c buffer within 50 ms timeout
708
        // try to catch the i2c buffer within 50 ms timeout
709
        if(I2CBus_LockBuffer(Compass_I2CPort, 50))
709
        if(I2CBus_LockBuffer(Compass_I2CPort, 50))
710
        {
710
        {
711
                u8 TxBytes = 0;
711
                u8 TxBytes = 0;
712
                u8 TxData[sizeof(AccConfig) + 3];
712
                u8 TxData[sizeof(AccConfig) + 3];
713
                TxData[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
713
                TxData[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
714
                memcpy(&TxData[TxBytes], (u8*)&AccConfig, sizeof(AccConfig));
714
                memcpy(&TxData[TxBytes], (u8*)&AccConfig, sizeof(AccConfig));
715
                TxBytes += sizeof(AccConfig);
715
                TxBytes += sizeof(AccConfig);
716
                if(I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, 0, 0))
716
                if(I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, 0, 0))
717
                {
717
                {
718
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 50))
718
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 50))
719
                        {
719
                        {
720
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
720
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
721
                        }
721
                        }
722
                }
722
                }
723
        }
723
        }
724
        return(retval);
724
        return(retval);
725
}
725
}
726
 
726
 
727
// ----------------------------------------------------------------------------------------
727
// ----------------------------------------------------------------------------------------
728
u8 NCMAG_GetAccConfig(void)
728
u8 NCMAG_GetAccConfig(void)
729
{
729
{
730
        u8 retval = 0;
730
        u8 retval = 0;
731
        // try to catch the i2c buffer within 100 ms timeout
731
        // try to catch the i2c buffer within 100 ms timeout
732
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
732
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
733
        {
733
        {
734
                u8 TxBytes = 0;
734
                u8 TxBytes = 0;
735
                u8 TxData[3];
735
                u8 TxData[3];
736
                TxData[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
736
                TxData[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
737
                if(I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateAccConfig, sizeof(AccConfig)))
737
                if(I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateAccConfig, sizeof(AccConfig)))
738
                {
738
                {
739
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
739
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
740
                        {
740
                        {
741
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
741
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
742
                        }
742
                        }
743
                }
743
                }
744
        }
744
        }
745
        return(retval);
745
        return(retval);
746
}
746
}
747
 
747
 
748
// ----------------------------------------------------------------------------------------
748
// ----------------------------------------------------------------------------------------
749
u8 NCMAG_GetIdentification(void)
749
u8 NCMAG_GetIdentification(void)
750
{
750
{
751
        u8 retval = 0;
751
        u8 retval = 0;
752
        // try to catch the i2c buffer within 100 ms timeout
752
        // try to catch the i2c buffer within 100 ms timeout
753
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
753
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
754
        {
754
        {
755
                u8 TxBytes = 0;
755
                u8 TxBytes = 0;
756
                u8 TxData[3];
756
                u8 TxData[3];
757
                NCMAG_Identification.A = 0xFF;
757
                NCMAG_Identification.A = 0xFF;
758
                NCMAG_Identification.B = 0xFF;
758
                NCMAG_Identification.B = 0xFF;
759
                NCMAG_Identification.C = 0xFF;
759
                NCMAG_Identification.C = 0xFF;
760
                TxData[TxBytes++] = REG_MAG_IDA;
760
                TxData[TxBytes++] = REG_MAG_IDA;
761
                // initiate transmission
761
                // initiate transmission
762
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateIdentification, sizeof(NCMAG_Identification)))
762
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateIdentification, sizeof(NCMAG_Identification)))
763
                {
763
                {
764
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
764
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
765
                        {
765
                        {
766
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
766
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
767
                        }
767
                        }
768
                }
768
                }
769
        }
769
        }
770
        return(retval);
770
        return(retval);
771
}
771
}
772
 
772
 
773
u8 NCMAG_GetIdentification_Sub(void)
773
u8 NCMAG_GetIdentification_Sub(void)
774
{
774
{
775
        u8 retval = 0;
775
        u8 retval = 0;
776
        // try to catch the i2c buffer within 100 ms timeout
776
        // try to catch the i2c buffer within 100 ms timeout
777
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
777
        if(I2CBus_LockBuffer(Compass_I2CPort, 100))
778
        {
778
        {
779
                u8 TxBytes = 0;
779
                u8 TxBytes = 0;
780
                u8 TxData[3];
780
                u8 TxData[3];
781
                NCMAG_Identification2.Sub = 0xFF;
781
                NCMAG_Identification2.Sub = 0xFF;
782
                TxData[TxBytes++] = REG_MAG_IDF;
782
                TxData[TxBytes++] = REG_MAG_IDF;
783
                // initiate transmission
783
                // initiate transmission
784
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateIdentification_Sub, sizeof(NCMAG_Identification2)))
784
                if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateIdentification_Sub, sizeof(NCMAG_Identification2)))
785
                {
785
                {
786
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
786
                        if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
787
                        {
787
                        {
788
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
788
                                if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
789
                        }
789
                        }
790
                }
790
                }
791
        }
791
        }
792
        return(retval);
792
        return(retval);
793
}
793
}
794
 
794
 
795
 
795
 
796
// ----------------------------------------------------------------------------------------
796
// ----------------------------------------------------------------------------------------
797
void NCMAG_GetMagVector(u8 timeout)
797
void NCMAG_GetMagVector(u8 timeout)
798
{
798
{
799
        // try to catch the I2C buffer within timeout ms
799
        // try to catch the I2C buffer within timeout ms
800
        if(I2CBus_LockBuffer(Compass_I2CPort, timeout))
800
        if(I2CBus_LockBuffer(Compass_I2CPort, timeout))
801
        {
801
        {
802
                u8 TxBytes = 0;
802
                u8 TxBytes = 0;
803
                u8 TxData[3];
803
                u8 TxData[3];
804
                // set register pointer
804
                // set register pointer
805
                TxData[TxBytes++] = REG_MAG_DATAX_MSB;
805
                TxData[TxBytes++] = REG_MAG_DATAX_MSB;
806
                // initiate transmission
806
                // initiate transmission
807
                I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateMagVector, sizeof(MagVector));
807
                I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateMagVector, sizeof(MagVector));
808
        }
808
        }
809
}
809
}
810
 
810
 
811
//----------------------------------------------------------------
811
//----------------------------------------------------------------
812
void NCMAG_GetAccVector(u8 timeout)
812
void NCMAG_GetAccVector(u8 timeout)
813
{
813
{
814
        // try to catch the I2C buffer within timeout ms
814
        // try to catch the I2C buffer within timeout ms
815
        if(I2CBus_LockBuffer(Compass_I2CPort, timeout))
815
        if(I2CBus_LockBuffer(Compass_I2CPort, timeout))
816
        {
816
        {
817
                u8 TxBytes = 0;
817
                u8 TxBytes = 0;
818
                u8 TxData[3];
818
                u8 TxData[3];
819
                // set register pointer
819
                // set register pointer
820
                TxData[TxBytes++] = REG_ACC_X_LSB|REG_ACC_MASK_AUTOINCREMENT;
820
                TxData[TxBytes++] = REG_ACC_X_LSB|REG_ACC_MASK_AUTOINCREMENT;
821
                // initiate transmission
821
                // initiate transmission
822
                I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateAccVector, sizeof(AccRawVector));
822
                I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateAccVector, sizeof(AccRawVector));
823
        }
823
        }
824
}
824
}
825
 
825
 
826
//----------------------------------------------------------------
826
//----------------------------------------------------------------
827
u8 NCMAG_ConfigureSensor(void)
827
u8 NCMAG_ConfigureSensor(void)
828
{
828
{
829
        u8 crb_gain, cra_rate;
829
        u8 crb_gain, cra_rate;
830
 
830
 
831
        switch(NCMAG_SensorType)
831
        switch(NCMAG_SensorType)
832
        {
832
        {
833
                case TYPE_HMC5843:
833
                case TYPE_HMC5843:
834
                        crb_gain = HMC5843_CRB_GAIN_15GA;
834
                        crb_gain = HMC5843_CRB_GAIN_15GA;
835
                        cra_rate = HMC5843_CRA_RATE_50HZ;
835
                        cra_rate = HMC5843_CRA_RATE_50HZ;
836
                        break;
836
                        break;
837
 
837
 
838
                case TYPE_LSM303DLH:
838
                case TYPE_LSM303DLH:
839
                case TYPE_LSM303DLM:
839
                case TYPE_LSM303DLM:
840
                        crb_gain = LSM303DLH_CRB_GAIN_19GA;
840
                        crb_gain = LSM303DLH_CRB_GAIN_19GA;
841
                        cra_rate = LSM303DLH_CRA_RATE_75HZ;
841
                        cra_rate = LSM303DLH_CRA_RATE_75HZ;
842
                        break;
842
                        break;
843
 
843
 
844
                default:
844
                default:
845
                return(0);
845
                return(0);
846
        }
846
        }
847
 
847
 
848
        MagConfig.cra = cra_rate|CRA_MODE_NORMAL;
848
        MagConfig.cra = cra_rate|CRA_MODE_NORMAL;
849
        MagConfig.crb = crb_gain;
849
        MagConfig.crb = crb_gain;
850
        MagConfig.mode = MODE_CONTINUOUS;
850
        MagConfig.mode = MODE_CONTINUOUS;
851
        return(NCMAG_SetMagConfig());
851
        return(NCMAG_SetMagConfig());
852
}
852
}
853
 
853
 
854
 
854
 
855
//----------------------------------------------------------------
855
//----------------------------------------------------------------
856
u8 NCMAG_Init_ACCSensor(void)
856
u8 NCMAG_Init_ACCSensor(void)
857
{
857
{
858
        AccConfig.ctrl_1 = ACC_CRTL1_PM_NORMAL|ACC_CRTL1_DR_50HZ|ACC_CRTL1_XEN|ACC_CRTL1_YEN|ACC_CRTL1_ZEN;
858
        AccConfig.ctrl_1 = ACC_CRTL1_PM_NORMAL|ACC_CRTL1_DR_50HZ|ACC_CRTL1_XEN|ACC_CRTL1_YEN|ACC_CRTL1_ZEN;
859
        AccConfig.ctrl_2 = 0;
859
        AccConfig.ctrl_2 = 0;
860
        AccConfig.ctrl_3 = 0x00;
860
        AccConfig.ctrl_3 = 0x00;
861
        AccConfig.ctrl_4 = ACC_CTRL4_BDU | ACC_CTRL4_FS_8G;
861
        AccConfig.ctrl_4 = ACC_CTRL4_BDU | ACC_CTRL4_FS_8G;
862
        AccConfig.ctrl_5 = ACC_CTRL5_STW_OFF;
862
        AccConfig.ctrl_5 = ACC_CTRL5_STW_OFF;
863
        return(NCMAG_SetAccConfig());
863
        return(NCMAG_SetAccConfig());
864
}
864
}
865
// --------------------------------------------------------
865
// --------------------------------------------------------
866
void NCMAG_Update(u8 init)
866
void NCMAG_Update(u8 init)
867
{
867
{
868
        static u32 TimerUpdate = 0;
868
        static u32 TimerUpdate = 0;
869
        static s8 send_config = 0;
869
        static s8 send_config = 0;
870
        u32 delay = 20;
870
        u32 delay = 20;
871
 
871
 
872
        if(init) TimerUpdate = SetDelay(10);
872
        if(init) TimerUpdate = SetDelay(10);
873
 
873
 
874
        if( (I2CBus(Compass_I2CPort)->State == I2C_STATE_UNDEF) /*|| !NCMAG_Present*/ )
874
        if( (I2CBus(Compass_I2CPort)->State == I2C_STATE_UNDEF) /*|| !NCMAG_Present*/ )
875
        {
875
        {
876
                Compass_Heading = -1;
876
                Compass_Heading = -1;
877
                DebugOut.Analog[14]++; // count I2C error
877
                DebugOut.Analog[14]++; // count I2C error
878
                TimerUpdate = SetDelay(10);
878
                TimerUpdate = SetDelay(10);
879
                return;
879
                return;
880
        }
880
        }
881
        if(CheckDelay(TimerUpdate))
881
        if(CheckDelay(TimerUpdate))
882
        {
882
        {
883
                if(Compass_Heading != -1) send_config = 0; // no re-configuration if value is valid
883
                if(Compass_Heading != -1) send_config = 0; // no re-configuration if value is valid
884
        if(++send_config == 25)   // 500ms
884
        if(++send_config == 25)   // 500ms
885
                {
885
                {
886
                        send_config = -25;    // next try after 1 second
886
                        send_config = -25;    // next try after 1 second
887
                NCMAG_ConfigureSensor();
887
                NCMAG_ConfigureSensor();
888
                        TimerUpdate = SetDelay(20);    // back into the old time-slot
888
                        TimerUpdate = SetDelay(20);    // back into the old time-slot
889
                }
889
                }
890
                else
890
                else
891
                {
891
                {
892
                        static u8 s = 0;
892
                        static u8 s = 0;
893
                        // check for new calibration state
893
                        // check for new calibration state
894
                        Compass_UpdateCalState();
894
                        Compass_UpdateCalState();
895
                        if(Compass_CalState) NCMAG_Calibrate();
895
                        if(Compass_CalState) NCMAG_Calibrate();
896
 
896
 
897
                        // in case of LSM303 type
897
                        // in case of LSM303 type
898
                        switch(NCMAG_SensorType)
898
                        switch(NCMAG_SensorType)
899
                        {
899
                        {
900
                                case TYPE_HMC5843:
900
                                case TYPE_HMC5843:
901
                                        delay = 20;      // next cycle after 20 ms
901
                                        delay = 20;      // next cycle after 20 ms
902
                                        NCMAG_GetMagVector(5);
902
                                        NCMAG_GetMagVector(5);
903
                                        break;
903
                                        break;
904
                                case TYPE_LSM303DLH:
904
                                case TYPE_LSM303DLH:
905
                                case TYPE_LSM303DLM:
905
                                case TYPE_LSM303DLM:
906
 
-
 
-
 
906
                                        delay = 20;      // next cycle after 20 ms
907
                                        if(s-- || (Compass_I2CPort == NCMAG_PORT_INTERN))
907
                                        if(s-- || (Compass_I2CPort == NCMAG_PORT_INTERN))
908
                                        {
908
                                        {
909
                                                delay = 20;      // next cycle after 20 ms
-
 
910
                                                NCMAG_GetMagVector(5);
909
                                                NCMAG_GetMagVector(5);
911
                                        }
910
                                        }
912
                                        else // having an external compass, read every 50th cycle the ACC vec
911
                                        else // having an external compass, read every 50th cycle the ACC vec
913
                                        {       // try to initialize if no data are there
912
                                        {       // try to initialize if no data are there
914
                                                if((AccRawVector.X + AccRawVector.Y + AccRawVector.Z) == 0) NCMAG_Init_ACCSensor();
913
                                                if((AccRawVector.X + AccRawVector.Y + AccRawVector.Z) == 0) NCMAG_Init_ACCSensor();
915
                                                // get new data
914
                                                // get new data
916
                                                NCMAG_GetAccVector(5);
915
                                                NCMAG_GetAccVector(5);
917
                                                delay = 10; // next cycle after 10 ms
916
                                                delay = 10; // next cycle after 10 ms
918
                                                s = 40; //reset downconter about 0,8 sec
917
                                                s = 40; //reset downconter about 0,8 sec
919
                                        }
918
                                        }
920
                                        break;
919
                                        break;
921
                        }
920
                        }
922
                        if(send_config == 24) TimerUpdate = SetDelay(15);    // next event is the re-configuration
921
                        if(send_config == 24) TimerUpdate = SetDelay(15);    // next event is the re-configuration
923
                        else TimerUpdate = SetDelay(delay);    // every 20 ms are 50 Hz
922
                        else TimerUpdate = SetDelay(delay);    // every 20 ms are 50 Hz
924
                }
923
                }
925
        }
924
        }
926
}
925
}
927
 
926
 
928
 
927
 
929
// --------------------------------------------------------
928
// --------------------------------------------------------
930
u8 NCMAG_SelfTest(void)
929
u8 NCMAG_SelfTest(void)
931
{
930
{
932
        u8 msg[64];
931
        u8 msg[64];
933
        static u8 done = 0;
932
        static u8 done = 0;
934
 
933
 
935
        if(done) return(1);        // just make it once
934
        if(done) return(1);        // just make it once
936
 
935
 
937
        #define LIMITS(value, min, max) {min = (80 * value)/100; max = (120 * value)/100;}
936
        #define LIMITS(value, min, max) {min = (80 * value)/100; max = (120 * value)/100;}
938
        u32 time;
937
        u32 time;
939
        s32 XMin = 0, XMax = 0, YMin = 0, YMax = 0, ZMin = 0, ZMax = 0;
938
        s32 XMin = 0, XMax = 0, YMin = 0, YMax = 0, ZMin = 0, ZMax = 0;
940
        s16 xscale, yscale, zscale, scale_min, scale_max;
939
        s16 xscale, yscale, zscale, scale_min, scale_max;
941
        u8 crb_gain, cra_rate;
940
        u8 crb_gain, cra_rate;
942
        u8 i = 0, retval = 1;
941
        u8 i = 0, retval = 1;
943
 
942
 
944
        switch(NCMAG_SensorType)
943
        switch(NCMAG_SensorType)
945
        {
944
        {
946
                case TYPE_HMC5843:
945
                case TYPE_HMC5843:
947
                        crb_gain = HMC5843_CRB_GAIN_15GA;
946
                        crb_gain = HMC5843_CRB_GAIN_15GA;
948
                        cra_rate = HMC5843_CRA_RATE_50HZ;
947
                        cra_rate = HMC5843_CRA_RATE_50HZ;
949
                        xscale = HMC5843_TEST_XSCALE;
948
                        xscale = HMC5843_TEST_XSCALE;
950
                        yscale = HMC5843_TEST_YSCALE;
949
                        yscale = HMC5843_TEST_YSCALE;
951
                        zscale = HMC5843_TEST_ZSCALE;
950
                        zscale = HMC5843_TEST_ZSCALE;
952
                        break;
951
                        break;
953
 
952
 
954
                case TYPE_LSM303DLH:
953
                case TYPE_LSM303DLH:
955
                        crb_gain = LSM303DLH_CRB_GAIN_19GA;
954
                        crb_gain = LSM303DLH_CRB_GAIN_19GA;
956
                        cra_rate = LSM303DLH_CRA_RATE_75HZ;
955
                        cra_rate = LSM303DLH_CRA_RATE_75HZ;
957
                        xscale = LSM303DLH_TEST_XSCALE;
956
                        xscale = LSM303DLH_TEST_XSCALE;
958
                        yscale = LSM303DLH_TEST_YSCALE;
957
                        yscale = LSM303DLH_TEST_YSCALE;
959
                        zscale = LSM303DLH_TEST_ZSCALE;
958
                        zscale = LSM303DLH_TEST_ZSCALE;
960
                        break;
959
                        break;
961
 
960
 
962
                case TYPE_LSM303DLM:
961
                case TYPE_LSM303DLM:
963
                        // does not support self test feature
962
                        // does not support self test feature
964
                        done = 1;
963
                        done = 1;
965
                        return(1); // always return success
964
                        return(1); // always return success
966
                        break;
965
                        break;
967
 
966
 
968
                default:
967
                default:
969
                        return(0);
968
                        return(0);
970
        }
969
        }
971
 
970
 
972
        MagConfig.cra = cra_rate|CRA_MODE_POSBIAS;
971
        MagConfig.cra = cra_rate|CRA_MODE_POSBIAS;
973
        MagConfig.crb = crb_gain;
972
        MagConfig.crb = crb_gain;
974
        MagConfig.mode = MODE_CONTINUOUS;
973
        MagConfig.mode = MODE_CONTINUOUS;
975
        // activate positive bias field
974
        // activate positive bias field
976
        NCMAG_SetMagConfig();
975
        NCMAG_SetMagConfig();
977
        // wait for stable readings
976
        // wait for stable readings
978
        time = SetDelay(50);
977
        time = SetDelay(50);
979
        while(!CheckDelay(time));
978
        while(!CheckDelay(time));
980
        // averaging
979
        // averaging
981
        #define AVERAGE 20
980
        #define AVERAGE 20
982
        for(i = 0; i<AVERAGE; i++)
981
        for(i = 0; i<AVERAGE; i++)
983
        {
982
        {
984
                NCMAG_GetMagVector(5);
983
                NCMAG_GetMagVector(5);
985
                time = SetDelay(20);
984
                time = SetDelay(20);
986
        while(!CheckDelay(time));
985
        while(!CheckDelay(time));
987
                XMax += MagRawVector.X;
986
                XMax += MagRawVector.X;
988
                YMax += MagRawVector.Y;
987
                YMax += MagRawVector.Y;
989
                ZMax += MagRawVector.Z;
988
                ZMax += MagRawVector.Z;
990
        }
989
        }
991
        MagConfig.cra = cra_rate|CRA_MODE_NEGBIAS;
990
        MagConfig.cra = cra_rate|CRA_MODE_NEGBIAS;
992
        // activate positive bias field
991
        // activate positive bias field
993
        NCMAG_SetMagConfig();
992
        NCMAG_SetMagConfig();
994
    // wait for stable readings
993
    // wait for stable readings
995
        time = SetDelay(50);
994
        time = SetDelay(50);
996
        while(!CheckDelay(time));
995
        while(!CheckDelay(time));
997
        // averaging
996
        // averaging
998
        for(i = 0; i < AVERAGE; i++)
997
        for(i = 0; i < AVERAGE; i++)
999
        {
998
        {
1000
                NCMAG_GetMagVector(5);
999
                NCMAG_GetMagVector(5);
1001
                time = SetDelay(20);
1000
                time = SetDelay(20);
1002
        while(!CheckDelay(time));
1001
        while(!CheckDelay(time));
1003
                XMin += MagRawVector.X;
1002
                XMin += MagRawVector.X;
1004
                YMin += MagRawVector.Y;
1003
                YMin += MagRawVector.Y;
1005
                ZMin += MagRawVector.Z;
1004
                ZMin += MagRawVector.Z;
1006
        }
1005
        }
1007
        // setup final configuration
1006
        // setup final configuration
1008
        MagConfig.cra = cra_rate|CRA_MODE_NORMAL;
1007
        MagConfig.cra = cra_rate|CRA_MODE_NORMAL;
1009
        // activate positive bias field
1008
        // activate positive bias field
1010
        NCMAG_SetMagConfig();
1009
        NCMAG_SetMagConfig();
1011
        // check scale for all axes
1010
        // check scale for all axes
1012
        // prepare scale limits
1011
        // prepare scale limits
1013
        LIMITS(xscale, scale_min, scale_max);
1012
        LIMITS(xscale, scale_min, scale_max);
1014
        xscale = (XMax - XMin)/(2*AVERAGE);
1013
        xscale = (XMax - XMin)/(2*AVERAGE);
1015
        if((xscale > scale_max) || (xscale < scale_min))
1014
        if((xscale > scale_max) || (xscale < scale_min))
1016
    {
1015
    {
1017
                retval = 0;
1016
                retval = 0;
1018
        sprintf(msg, "\r\n Value X: %d not %d-%d !", xscale, scale_min,scale_max);
1017
        sprintf(msg, "\r\n Value X: %d not %d-%d !", xscale, scale_min,scale_max);
1019
                UART1_PutString(msg);
1018
                UART1_PutString(msg);
1020
    }
1019
    }
1021
        LIMITS(yscale, scale_min, scale_max);
1020
        LIMITS(yscale, scale_min, scale_max);
1022
        yscale = (YMax - YMin)/(2*AVERAGE);
1021
        yscale = (YMax - YMin)/(2*AVERAGE);
1023
        if((yscale > scale_max) || (yscale < scale_min))
1022
        if((yscale > scale_max) || (yscale < scale_min))
1024
    {
1023
    {
1025
                retval = 0;
1024
                retval = 0;
1026
        sprintf(msg, "\r\n Value Y: %d not %d-%d !", yscale, scale_min,scale_max);
1025
        sprintf(msg, "\r\n Value Y: %d not %d-%d !", yscale, scale_min,scale_max);
1027
                UART1_PutString(msg);
1026
                UART1_PutString(msg);
1028
    }
1027
    }
1029
        LIMITS(zscale, scale_min, scale_max);
1028
        LIMITS(zscale, scale_min, scale_max);
1030
        zscale = (ZMax - ZMin)/(2*AVERAGE);
1029
        zscale = (ZMax - ZMin)/(2*AVERAGE);
1031
        if((zscale > scale_max) || (zscale < scale_min))
1030
        if((zscale > scale_max) || (zscale < scale_min))
1032
        {
1031
        {
1033
                retval = 0;
1032
                retval = 0;
1034
        sprintf(msg, "\r\n Value Z: %d not %d-%d !", zscale, scale_min,scale_max);
1033
        sprintf(msg, "\r\n Value Z: %d not %d-%d !", zscale, scale_min,scale_max);
1035
                UART1_PutString(msg);
1034
                UART1_PutString(msg);
1036
    }
1035
    }
1037
        done = retval;
1036
        done = retval;
1038
        return(retval);
1037
        return(retval);
1039
}
1038
}
1040
 
1039
 
1041
 
1040
 
1042
void NCMAG_CheckOrientation(void)
1041
void NCMAG_CheckOrientation(void)
1043
{       // only for external sensor
1042
{       // only for external sensor
1044
        if(Compass_I2CPort == NCMAG_PORT_EXTERN)
1043
        if(Compass_I2CPort == NCMAG_PORT_EXTERN)
1045
        {
1044
        {
1046
                NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
1045
                NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
1047
                if(NCMAG_Orientation != (Calibration.Version>>4)) NCMAG_IsCalibrated = 0;
1046
                if(NCMAG_Orientation != (Calibration.Version>>4)) NCMAG_IsCalibrated = 0;
1048
                else NCMAG_IsCalibrated = 1;
1047
                else NCMAG_IsCalibrated = 1;
1049
        }
1048
        }
1050
}
1049
}
1051
//----------------------------------------------------------------
1050
//----------------------------------------------------------------
1052
u8 NCMAG_Init(void)
1051
u8 NCMAG_Init(void)
1053
{
1052
{
1054
        MagRawVector.X = 0;
1053
        MagRawVector.X = 0;
1055
    MagRawVector.Y = 0;
1054
    MagRawVector.Y = 0;
1056
    MagRawVector.Z = 0;
1055
    MagRawVector.Z = 0;
1057
        AccRawVector.X = 0;
1056
        AccRawVector.X = 0;
1058
        AccRawVector.Y = 0;
1057
        AccRawVector.Y = 0;
1059
        AccRawVector.Z = 0;
1058
        AccRawVector.Z = 0;
1060
 
1059
 
1061
        if(NCMAG_Present) // do only short init ! , full init was called before
1060
        if(NCMAG_Present) // do only short init ! , full init was called before
1062
        {
1061
        {
1063
                // reset I2C Bus
1062
                // reset I2C Bus
1064
                I2CBus_Deinit(Compass_I2CPort);
1063
                //I2CBus_Deinit(Compass_I2CPort);
1065
                I2CBus_Init(Compass_I2CPort);
1064
                //I2CBus_Init(Compass_I2CPort);
1066
                // try to reconfigure senor
1065
                // try to reconfigure senor
1067
                NCMAG_ConfigureSensor();
1066
                NCMAG_ConfigureSensor();
1068
                NCMAG_Update(1);
1067
                //NCMAG_Update(1);
1069
        }
1068
        }
1070
        else  // full init
1069
        else  // full init
1071
        {
1070
        {
1072
                u8 msg[64];
1071
                u8 msg[64];
1073
                u8 retval = 0;
1072
                u8 retval = 0;
1074
                u8 repeat = 0;
1073
                u8 repeat = 0;
1075
 
1074
 
1076
                //--------------------------------------------
1075
                //--------------------------------------------
1077
                // search external sensor first
1076
                // search external sensor first
1078
                //--------------------------------------------
1077
                //--------------------------------------------
1079
                Compass_I2CPort = NCMAG_PORT_EXTERN;
1078
                Compass_I2CPort = NCMAG_PORT_EXTERN;
1080
                // get id bytes
1079
                // get id bytes
1081
                retval = 0;
1080
                retval = 0;
1082
                for(repeat = 0; repeat < 5; repeat++)
1081
                for(repeat = 0; repeat < 5; repeat++)
1083
                {
1082
                {
1084
                        //retval = NCMAG_GetIdentification();
1083
                        //retval = NCMAG_GetIdentification();
1085
                        retval = NCMAG_GetAccConfig();            // only the external sensor with ACC is supported
1084
                        retval = NCMAG_GetAccConfig();            // only the external sensor with ACC is supported
1086
                        if(retval) break; // break loop on success
1085
                        if(retval) break; // break loop on success
1087
                        UART1_PutString("_");
1086
                        UART1_PutString("_");
1088
                }
1087
                }
1089
                // Extenal sensor not found?
1088
                // Extenal sensor not found?
1090
                if(!retval)
1089
                if(!retval)
1091
                {
1090
                {
1092
                        // search internal sensor afterwards
1091
                        // search internal sensor afterwards
1093
                        UART1_PutString(" internal sensor");
1092
                        UART1_PutString(" internal sensor");
1094
                        Compass_I2CPort = NCMAG_PORT_INTERN;
1093
                        Compass_I2CPort = NCMAG_PORT_INTERN;
1095
                }
1094
                }
1096
                else
1095
                else
1097
                {
1096
                {
1098
                        UART1_PutString(" external sensor");
1097
                        UART1_PutString(" external sensor");
1099
                        Compass_I2CPort = NCMAG_PORT_EXTERN;
1098
                        Compass_I2CPort = NCMAG_PORT_EXTERN;
1100
                }
1099
                }
1101
                //-------------------------------------------
1100
                //-------------------------------------------
1102
 
1101
 
1103
                NCMAG_Present = 0;
1102
                NCMAG_Present = 0;
1104
                NCMAG_SensorType = TYPE_HMC5843;        // assuming having an HMC5843
1103
                NCMAG_SensorType = TYPE_HMC5843;        // assuming having an HMC5843
1105
                // polling for LSM302DLH/DLM option by ACC address ack
1104
                // polling for LSM302DLH/DLM option by ACC address ack
1106
                repeat = 0;
1105
                repeat = 0;
1107
                for(repeat = 0; repeat < 3; repeat++)
1106
                for(repeat = 0; repeat < 3; repeat++)
1108
                {
1107
                {
1109
                        retval = NCMAG_GetAccConfig();
1108
                        retval = NCMAG_GetAccConfig();
1110
                        if(retval) break; // break loop on success
1109
                        if(retval) break; // break loop on success
1111
                }
1110
                }
1112
                if(retval)
1111
                if(retval)
1113
                {
1112
                {
1114
                        // initialize ACC sensor
1113
                        // initialize ACC sensor
1115
                        NCMAG_Init_ACCSensor();
1114
                        NCMAG_Init_ACCSensor();
1116
 
1115
 
1117
                        NCMAG_SensorType = TYPE_LSM303DLH;
1116
                        NCMAG_SensorType = TYPE_LSM303DLH;
1118
                        // polling of sub identification
1117
                        // polling of sub identification
1119
                        repeat = 0;
1118
                        repeat = 0;
1120
                        for(repeat = 0; repeat < 12; repeat++)
1119
                        for(repeat = 0; repeat < 12; repeat++)
1121
                        {
1120
                        {
1122
                                retval = NCMAG_GetIdentification_Sub();
1121
                                retval = NCMAG_GetIdentification_Sub();
1123
                                if(retval) break; // break loop on success
1122
                                if(retval) break; // break loop on success
1124
                        }
1123
                        }
1125
                        if(retval)
1124
                        if(retval)
1126
                        {
1125
                        {
1127
                                if(NCMAG_Identification2.Sub == MAG_IDF_LSM303DLM)      NCMAG_SensorType = TYPE_LSM303DLM;
1126
                                if(NCMAG_Identification2.Sub == MAG_IDF_LSM303DLM)      NCMAG_SensorType = TYPE_LSM303DLM;
1128
                        }
1127
                        }
1129
                }
1128
                }
1130
                // get id bytes
1129
                // get id bytes
1131
                retval = 0;
1130
                retval = 0;
1132
                for(repeat = 0; repeat < 3; repeat++)
1131
                for(repeat = 0; repeat < 3; repeat++)
1133
                {
1132
                {
1134
                        retval = NCMAG_GetIdentification();
1133
                        retval = NCMAG_GetIdentification();
1135
                        if(retval) break; // break loop on success
1134
                        if(retval) break; // break loop on success
1136
                }
1135
                }
1137
 
1136
 
1138
                // if we got an answer to id request
1137
                // if we got an answer to id request
1139
                if(retval)
1138
                if(retval)
1140
                {
1139
                {
1141
                        u8 n1[] = "\n\r HMC5843";
1140
                        u8 n1[] = "\n\r HMC5843";
1142
                        u8 n2[] = "\n\r LSM303DLH";
1141
                        u8 n2[] = "\n\r LSM303DLH";
1143
                        u8 n3[] = "\n\r LSM303DLM";
1142
                        u8 n3[] = "\n\r LSM303DLM";
1144
                        u8* pn = n1;
1143
                        u8* pn = n1;
1145
 
1144
 
1146
                        switch(NCMAG_SensorType)
1145
                        switch(NCMAG_SensorType)
1147
                        {
1146
                        {
1148
                                case TYPE_HMC5843:
1147
                                case TYPE_HMC5843:
1149
                                        pn = n1;
1148
                                        pn = n1;
1150
                                        break;
1149
                                        break;
1151
                                case TYPE_LSM303DLH:
1150
                                case TYPE_LSM303DLH:
1152
                                        pn = n2;
1151
                                        pn = n2;
1153
                                        break;
1152
                                        break;
1154
                                case TYPE_LSM303DLM:
1153
                                case TYPE_LSM303DLM:
1155
                                        pn = n3;
1154
                                        pn = n3;
1156
                                        break;
1155
                                        break;
1157
                        }
1156
                        }
1158
 
1157
 
1159
                        sprintf(msg, " %s ID 0x%02x/%02x/%02x-%02x", pn, NCMAG_Identification.A, NCMAG_Identification.B, NCMAG_Identification.C,NCMAG_Identification2.Sub);
1158
                        sprintf(msg, " %s ID 0x%02x/%02x/%02x-%02x", pn, NCMAG_Identification.A, NCMAG_Identification.B, NCMAG_Identification.C,NCMAG_Identification2.Sub);
1160
                        UART1_PutString(msg);
1159
                        UART1_PutString(msg);
1161
                        if (    (NCMAG_Identification.A == MAG_IDA)
1160
                        if (    (NCMAG_Identification.A == MAG_IDA)
1162
                             && (NCMAG_Identification.B == MAG_IDB)
1161
                             && (NCMAG_Identification.B == MAG_IDB)
1163
                                 && (NCMAG_Identification.C == MAG_IDC))
1162
                                 && (NCMAG_Identification.C == MAG_IDC))
1164
                        {
1163
                        {
1165
                                NCMAG_Present = 1;
1164
                                NCMAG_Present = 1;
1166
 
1165
 
1167
                                if(EEPROM_Init())
1166
                                if(EEPROM_Init())
1168
                                {
1167
                                {
1169
                                        NCMAG_IsCalibrated = NCMag_CalibrationRead(Compass_I2CPort);
1168
                                        NCMAG_IsCalibrated = NCMag_CalibrationRead(Compass_I2CPort);
1170
                                        if(!NCMAG_IsCalibrated) UART1_PutString("\r\n Not calibrated!");
1169
                                        if(!NCMAG_IsCalibrated) UART1_PutString("\r\n Not calibrated!");
1171
                                }
1170
                                }
1172
                                else UART1_PutString("\r\n EEPROM data not available!!!!!!!!!!!!!!!");
1171
                                else UART1_PutString("\r\n EEPROM data not available!!!!!!!!!!!!!!!");
1173
 
1172
 
1174
                                // in case of an external sensor, try to get the orientation by acc readings
1173
                                // in case of an external sensor, try to get the orientation by acc readings
1175
                                if(Compass_I2CPort == NCMAG_PORT_EXTERN)
1174
                                if(Compass_I2CPort == NCMAG_PORT_EXTERN)
1176
                                {
1175
                                {
1177
                                        // try to get orientation by acc sensor values
1176
                                        // try to get orientation by acc sensor values
1178
                                        for(repeat = 0; repeat < 100; repeat++)
1177
                                        for(repeat = 0; repeat < 100; repeat++)
1179
                                        {
1178
                                        {
1180
                                                NCMAG_GetAccVector(10); // only the sensor with ACC is supported
1179
                                                NCMAG_GetAccVector(10); // only the sensor with ACC is supported
1181
                                                NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
1180
                                                NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
1182
                                                if(NCMAG_Orientation && (NCMAG_Orientation == Calibration.Version >> 4)) break;
1181
                                                if(NCMAG_Orientation && (NCMAG_Orientation == Calibration.Version >> 4)) break;
1183
                                        }
1182
                                        }
1184
                                        // check orientation result if available
1183
                                        // check orientation result if available
1185
                                        sprintf(msg, "\r\n Orientation: ");
1184
                                        sprintf(msg, "\r\n Orientation: ");
1186
                                        UART1_PutString(msg);
1185
                                        UART1_PutString(msg);
1187
                                        if(NCMAG_Orientation)
1186
                                        if(NCMAG_Orientation)
1188
                                        {
1187
                                        {
1189
                                                sprintf(msg, "%d ", NCMAG_Orientation);
1188
                                                sprintf(msg, "%d ", NCMAG_Orientation);
1190
                                                UART1_PutString(msg);
1189
                                                UART1_PutString(msg);
1191
                                                if(NCMAG_IsCalibrated) // check against calibration data orientation
1190
                                                if(NCMAG_IsCalibrated) // check against calibration data orientation
1192
                                                {
1191
                                                {
1193
                                                        if(NCMAG_Orientation != Calibration.Version >> 4)
1192
                                                        if(NCMAG_Orientation != Calibration.Version >> 4)
1194
                                                        {
1193
                                                        {
1195
                                                                sprintf(msg, "\n\r Warning: calibrated orientation was %d !",Calibration.Version >> 4);
1194
                                                                sprintf(msg, "\n\r Warning: calibrated orientation was %d !",Calibration.Version >> 4);
1196
                                                                UART1_PutString(msg);
1195
                                                                UART1_PutString(msg);
1197
                                                        }
1196
                                                        }
1198
                                                }
1197
                                                }
1199
                                        }
1198
                                        }
1200
                                        else
1199
                                        else
1201
                                        {
1200
                                        {
1202
                                                UART1_PutString("unknown!");
1201
                                                UART1_PutString("unknown!");
1203
                                        }
1202
                                        }
1204
                                }
1203
                                }
1205
 
1204
 
1206
 
1205
 
1207
                                // perform self test
1206
                                // perform self test
1208
                                if(!NCMAG_SelfTest())
1207
                                if(!NCMAG_SelfTest())
1209
                                {
1208
                                {
1210
                                        UART1_PutString("\r\n Selftest failed!!!!!!!!!!!!!!!!!!!!\r\n");
1209
                                        UART1_PutString("\r\n Selftest failed!!!!!!!!!!!!!!!!!!!!\r\n");
1211
                                        LED_RED_ON;
1210
                                        LED_RED_ON;
1212
                                        //NCMAG_IsCalibrated = 0;
1211
                                        //NCMAG_IsCalibrated = 0;
1213
                                }
1212
                                }
1214
                                else UART1_PutString("\r\n Selftest ok");
1213
                                else UART1_PutString("\r\n Selftest ok");
1215
 
1214
 
1216
                                // initialize magnetic sensor configuration
1215
                                // initialize magnetic sensor configuration
1217
                                NCMAG_ConfigureSensor();
1216
                                NCMAG_ConfigureSensor();
1218
                        }
1217
                        }
1219
                        else
1218
                        else
1220
                        {
1219
                        {
1221
                                UART1_PutString("\n\r Not compatible!");
1220
                                UART1_PutString("\n\r Not compatible!");
1222
                                UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_INCOMPATIBLE;
1221
                                UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_INCOMPATIBLE;
1223
                                LED_RED_ON;
1222
                                LED_RED_ON;
1224
                        }
1223
                        }
1225
                }
1224
                }
1226
                else // nothing found
1225
                else // nothing found
1227
                {
1226
                {
1228
                        NCMAG_SensorType = TYPE_NONE;
1227
                        NCMAG_SensorType = TYPE_NONE;
1229
                        UART1_PutString("not found!");
1228
                        UART1_PutString("not found!");
1230
                }
1229
                }
1231
        }
1230
        }
1232
        return(NCMAG_Present);
1231
        return(NCMAG_Present);
1233
}
1232
}
1234
 
1233
 
1235
 
1234