Subversion Repositories NaviCtrl

Rev

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

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