Subversion Repositories NaviCtrl

Compare Revisions

Ignore whitespace Rev 481 → Rev 482

/trunk/i2c0.c
File deleted
/trunk/i2c1.c
File deleted
/trunk/i2c1.h
File deleted
/trunk/i2c0.h
File deleted
/trunk/GPS.c
74,7 → 74,7
#include "timer1.h"
#include "spi_slave.h"
#include "waypoints.h"
#include "i2c1.h"
#include "i2c.h"
 
 
#define M_PI_180 (M_PI / 180.0f)
/trunk/Navi-Ctrl.Uv2
12,10 → 12,10
File 1,1,<.\main.c><main.c>
File 1,1,<.\ramfunc.c><ramfunc.c>
File 1,1,<.\menu.c><menu.c>
File 1,1,<.\mymath.c><mymath.c>
File 1,1,<.\i2c.c><i2c.c>
File 1,1,<.\spi_slave.c><spi_slave.c>
File 1,1,<.\fat16.c><fat16.c>
File 1,1,<.\i2c0.c><i2c0.c>
File 1,1,<.\i2c1.c><i2c1.c>
File 1,1,<.\sdc.c><sdc.c>
File 1,1,<.\settings.c><settings.c>
File 1,1,<.\ftphelper.c><ftphelper.c>
43,13 → 43,11
File 1,1,<.\buffer.c><buffer.c>
File 1,1,<.\eeprom.c><eeprom.c>
File 1,1,<.\ncmag.c><ncmag.c>
File 1,1,<.\mymath.c><mymath.c>
File 2,5,<.\ramfunc.h><ramfunc.h>
File 2,5,<.\main.h><main.h>
File 2,5,<.\menu.h><menu.h>
File 2,5,<.\settings.h><settings.h>
File 2,5,<.\i2c0.h><i2c0.h>
File 2,5,<.\i2c1.h><i2c1.h>
File 2,5,<.\i2c.h><i2c.h>
File 2,5,<.\spi_slave.h><spi_slave.h>
File 2,5,<.\sdc.h><sdc.h>
File 2,5,<.\ssc.h><ssc.h>
/trunk/compass.c
68,6 → 68,7
fifo_t CompassCalcStateFiFo;
 
volatile s16vec_t MagVector; // is written by mk3mag or ncmag implementation
volatile s16vec_t AccVector; // current acceleration vector of compass, not supported by any HW version
volatile s16 Compass_Heading; // is written by mk3mag or ncmag implementation
volatile u8 Compass_CalState; // is written by mk3mag or ncmag implementation
s16 Hx = 0, Hy = 0;
83,6 → 84,7
#define COMPASS_MK3MAG 1
#define COMPASS_NCMAG 2
u8 Compass_Device = COMPASS_NONE;
I2C_TypeDef* Compass_I2CPort = I2C1;
 
void Compass_Init(void)
{
92,27 → 94,18
UART1_PutString("\r\n Looking for compass");
if( MK3MAG_Init() ) Compass_Device = COMPASS_MK3MAG;
else if( NCMAG_Init() ) Compass_Device = COMPASS_NCMAG;
 
/* if(Version_HW > 11)
{
if( NCMAG_Init() ) Compass_Device = COMPASS_NCMAG;
else if( MK3MAG_Init()) Compass_Device = COMPASS_MK3MAG;
}
else
{
if( MK3MAG_Init() ) Compass_Device = COMPASS_MK3MAG;
else if( NCMAG_Init() ) Compass_Device = COMPASS_NCMAG;
}
*/
break;
 
case COMPASS_NCMAG:
UART1_PutString("\r\n Re-Init compass");
if( NCMAG_Init() ) Compass_Device = COMPASS_NCMAG;
else Compass_Device = COMPASS_NONE;
break;
 
case COMPASS_MK3MAG:
if( MK3MAG_Init() ) Compass_Device = COMPASS_MK3MAG;
else Compass_Device = COMPASS_NONE;
break;
 
default:
// nothing to do
break;
122,9 → 115,29
 
if(Compass_Device == COMPASS_MK3MAG) UART_VersionInfo.Flags |= NC_VERSION_FLAG_MK3MAG_PRESENT; else UART_VersionInfo.Flags &= ~NC_VERSION_FLAG_MK3MAG_PRESENT;
 
MagVector.X = 0;
MagVector.Y = 0;
MagVector.Z = 0;
Compass_Heading = -1;
}
 
 
void Compass_Check(void)
{
switch(Compass_Device)
{
case COMPASS_NCMAG:
NCMAG_CheckOrientation();
break;
 
case COMPASS_MK3MAG:
case COMPASS_NONE:
default:
// nothing to do
break;
}
}
 
void Compass_CalcHeading(void)
{
if((UART_VersionInfo.HardwareError[0] & NC_ERROR0_SPI_RX) || Compass_CalState)
167,31 → 180,31
{
case COMPASS_MK3MAG:
MK3MAG_Update();
DebugOut.Analog[24] = MagVector.X;
DebugOut.Analog[25] = MagVector.Y;
DebugOut.Analog[26] = MagVector.Z;
break;
case COMPASS_NCMAG:
if(check_value_counter == 2000)
{
UART1_PutString("\n\r Init Mag.-Sensor");
InitNC_MagnetSensor(); // 2 seconds no change of the compass value
}
else NCMAG_Update(0);
DebugOut.Analog[24] = MagRawVector.X;
DebugOut.Analog[25] = MagRawVector.Y;
DebugOut.Analog[26] = MagRawVector.Z;
NCMAG_Update(0);
break;
default:
break;
}
if(!((old.X == MagVector.X) || (old.Y == MagVector.Y) || (old.Z == MagVector.Z))) check_value_counter = 0; // Values are normally changing
 
if(check_value_counter > 5000)
{
Compass_Heading = -1; // values didn't change for 5 seconds -> probably a compass-fault
}
else check_value_counter++;
DebugOut.Analog[24] = MagVector.X;
DebugOut.Analog[25] = MagVector.Y;
DebugOut.Analog[26] = MagVector.Z;
 
if(!((old.X == MagVector.X) || (old.Y == MagVector.Y) || (old.Z == MagVector.Z))) check_value_counter = 0; // Values are normaly changing
 
if(check_value_counter == 2000)
{
UART1_PutString("\n\r Init Mag.-Sensor");
Compass_Init(); // 2 seconds no change of the compass value
}
else if(check_value_counter > 5000)
{
Compass_Heading = -1; // values didn't change for 5 seconds -> probably a compass-fault
}
else check_value_counter++;
 
old.X = MagVector.X;
old.Y = MagVector.Y;
old.Z = MagVector.Z;
/trunk/compass.h
1,6 → 1,9
#ifndef _COMPASS_H
#define _COMPASS_H
 
// this is the apstract interface for the magnetometer/compass sensor
// below this there are different special sensors that are supported
 
typedef struct
{
s16 X;
9,6 → 12,7
} __attribute__((packed)) s16vec_t;
 
extern volatile s16vec_t MagVector; // current magnetic field vector
extern volatile s16vec_t AccVector; // current acceleration vector of compass, not supported by any HW version
extern volatile s16 Compass_Heading; // current heading direction
extern volatile u8 Compass_CalState; // current calibration state
extern s32 EarthMagneticField;
24,11 → 28,13
#define COMPASS_MK3MAG 1
#define COMPASS_NCMAG 2
extern u8 Compass_Device;
extern I2C_TypeDef* Compass_I2CPort;
 
void Compass_Init(void);
void Compass_Update(void);
void Compass_CalcHeading(void);
void Compass_SetCalState(u8 CalState);
void Compass_UpdateCalState(void);
void Compass_Init(void); // initialization for compass sensor
void Compass_Check(void); // possible check for compass plausibility, called when FC gets calibrates
void Compass_Update(void); // updates sensor values, cyclic called
void Compass_CalcHeading(void); // calculates heading from magent vector componentes
void Compass_SetCalState(u8 CalState); // append to CalState queue
void Compass_UpdateCalState(void); // process CalState queue
 
#endif // _COMPASS_H
/trunk/config.h
64,8 → 64,8
#define UART2_BAUD_RATE 57600 //Baud Rate for the serial interfaces
 
//<o> I2C-Bus1 <22000=> 20 kBit <50000=> 50 kBit <100000=> 100 kBit <200000=> 200 kBit <400000=> 400 kBit
#define I2C1_CLOCK 50000 // Bit Rate for I2C
#define I2C0_CLOCK 50000 // Bit Rate for I2C
#define I2C0_CLOCK 50000 // Bit Rate for I2C
#define I2C1_CLOCK 50000 // Bit Rate for I2C
 
//</h>
//<<< end of configuration section >>>
/trunk/eeprom.c
56,7 → 56,7
#include <string.h>
#include <stdio.h>
#include "91x_lib.h"
#include "i2c1.h"
#include "i2c.h"
#include "uart1.h"
#include "timer1.h"
#include "eeprom.h"
63,7 → 63,10
#include "led.h"
 
 
 
// The EEPROM M24C64 (64k) ist connected via I2C1 interface to the controller.
#define EEPROM_I2C I2C1
 
// The E0, E2, E3 pins are set to low. Therefore the slave adressbits b3, b2, b1 are 0.
 
#define EEPROM_I2C_ADDRESS 0xA0
92,7 → 95,7
// ----------------------------------------------------------------------------------------
EEPROM_Result_t EEPROM_Transfer(u8 Direction, u16 Address, u8 *pData, u16 DataLen)
{
u16 i, TxBytes = 0;
u16 i;
u8 retry = 0;
EEPROM_Result_t retval = EEPROM_ERROR_UNKNOWN;
 
101,7 → 104,7
retval = EEPROM_ERROR_OUT_OF_ADDRESS_RANGE;
return(retval);
}
if((DataLen+2) > I2C1_BUFFER_LEN)
if((DataLen+2) > I2C_BUFFER_LEN)
{
retval = EEPROM_I2C_BUFFER_OVERRUN;
return(retval);
108,23 → 111,24
}
do
{
if(!I2C1_LockBuffer(I2C_IDLE_TIMEOUT)) return EEPROM_ERROR_I2C_IDLE_TIMEOUT;
if(!I2CBus_LockBuffer(EEPROM_I2C, I2C_IDLE_TIMEOUT)) return EEPROM_ERROR_I2C_IDLE_TIMEOUT;
// buffer is now locked
TxBytes = 0;
u8 TxBytes = 0;
u8 TxData[255];
// transmitt address
I2C1_Buffer[TxBytes++] = (u8)(0x00FF & (Address>>8));
I2C1_Buffer[TxBytes++] = (u8)(0x00FF & Address);
TxData[TxBytes++] = (u8)(0x00FF & (Address>>8));
TxData[TxBytes++] = (u8)(0x00FF & Address);
if(Direction == EEPROM_WRITE)
{ // copy data to i2c transfer buffer
for(i = 0; i<DataLen;i++)
{
I2C1_Buffer[TxBytes++] = pData[i];
TxData[TxBytes++] = pData[i];
}
// prepare pointer to rx data
EEPROM_pData = 0;
EEPROM_DataLen = 0;
// start transmission
if(!I2C1_Transmission(EEPROM_I2C_ADDRESS, TxBytes, 0, 0))
if(!I2CBus_Transmission(EEPROM_I2C, EEPROM_I2C_ADDRESS, TxData, TxBytes, 0, 0))
{
return(retval);
}
135,15 → 139,15
EEPROM_pData = pData;
EEPROM_DataLen = DataLen;
// start transmission
if(!I2C1_Transmission(EEPROM_I2C_ADDRESS, TxBytes, &EEPROM_RxDataHandler, DataLen))
if(!I2CBus_Transmission(EEPROM_I2C, EEPROM_I2C_ADDRESS, TxData, TxBytes, &EEPROM_RxDataHandler, DataLen))
{
return(retval);
}
}
//wait for end of this transfer
if(I2C1_WaitForEndOfTransmission(I2C_TRANSFER_TIMEOUT))
if(I2CBus_WaitForEndOfTransmission(EEPROM_I2C, I2C_TRANSFER_TIMEOUT))
{
if(I2C1_Error == I2C_ERROR_NONE) return(EEPROM_SUCCESS);
if(I2CBus(EEPROM_I2C)->Error == I2C_ERROR_NONE) return(EEPROM_SUCCESS);
else retval = EEPROM_DATA_TRANSFER_INCOMPLETE;
}
else// i2c transfer timed out
190,7 → 194,7
 
while(DataLen > 0)
{
if(DataLen > I2C1_BUFFER_LEN) RxLen = I2C1_BUFFER_LEN;
if(DataLen > I2C_BUFFER_LEN) RxLen = I2C_BUFFER_LEN;
else RxLen = DataLen;
retval = EEPROM_Transfer(EEPROM_READ, Address+AdrOffset, &(pData[AdrOffset]), RxLen);
/trunk/gpx.c
273,20 → 273,6
return(retvalue);
}
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + extended Current measurement -> 200 = 20A 201 = 21A 255 = 75A (20+55)
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
unsigned int BL3_Current(unsigned char who) // in 0,1A
{
if(Motor[who].Current <= 200) return((unsigned int) Motor[who].Current);
else
{
if(Motor_Version[who] & MOTOR_STATE_BL30) return(200 + 10 * (unsigned int) (Motor[who].Current-200));
else return((unsigned int) Motor[who].Current);
}
}
 
 
//________________________________________________________________________________________________________________________________________
// Function: u8 GPX_TrackSegementAddPoint(GPS_Pos_t * pGPS_Position ,GPX_Document_t *doc);
//
403,7 → 389,7
}
*/ // Compassind deg
i16_1 = FromFlightCtrl.GyroHeading / 10;
sprintf(string, "<Compass>%03d,%03d,%03d</Compass>\r\n", i16_1,ToFlightCtrl.CompassHeading, GyroCompassCorrected/10);
sprintf(string, "<Compass>%03d,%03d,%03d</Compass>\r\n", i16_1,ToFlightCtrl.CompassHeading,GyroCompassCorrected/10);
fputs_(string, doc->file);
// magnetic field
sprintf(string, "<MagnetField>%03d</MagnetField>\r\n",(u16) (EarthMagneticFieldFiltered/5));
/trunk/gpx.h
23,7 → 23,7
File_t *file; // filepointer to the file where the data should be saved.
} GPX_Document_t;
 
u8 GPX_LoggGPSCoordinates(GPX_Document_t *,unsigned char part); // intializes the gpx-document with standard filename and adds points to the file
u8 GPX_LoggGPSCoordinates(GPX_Document_t *,u8 part); // intializes the gpx-document with standard filename and adds points to the file
u8 GPX_DocumentInit(GPX_Document_t *); // Init the new gpx-document
u8 GPX_DocumentOpen(s8 *, GPX_Document_t *); // opens a new gpx-document. a new file is created on the sd-memorycard
u8 GPX_DocumentClose(GPX_Document_t *doc); // closes the specified document saving remaining data to the file.
31,7 → 31,6
u8 GPX_TrackEnd(GPX_Document_t *doc); // ends the actual track
u8 GPX_TrackSegmentBegin(GPX_Document_t *doc); // begins a new tracksegment within the actual track
u8 GPX_TrackSegmentEnd(GPX_Document_t *doc); // ends the actual track segment within the actual track
u8 GPX_TrackSegmentAddPoint(GPX_Document_t *,unsigned char part); // adds a point to the tracksegment
extern unsigned int BL3_Current(unsigned char who); // in 0,1A
u8 GPX_TrackSegmentAddPoint(GPX_Document_t *,u8 part); // adds a point to the tracksegment
 
#endif //_GPX_H
/trunk/i2c.c
0,0 → 1,714
/*#######################################################################################*/
/* !!! THIS IS NOT FREE SOFTWARE !!! */
/*#######################################################################################*/
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software Nutzungsbedingungen (english version: see below)
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
// + des Mitverschuldens offen.
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
// + 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.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software LICENSING TERMS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
// + 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
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
// + The Software may only be used with the Licensor's products.
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
// + agreement shall be the property of the Licensor.
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
// + features that can be used to identify the program may not be altered or defaced by the customer.
// + The customer shall be responsible for taking reasonable precautions
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
// + #### END OF LICENSING TERMS ####
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <string.h>
#include "i2c.h"
#include "uart1.h"
#include "timer1.h"
#include "config.h"
#include "led.h"
 
// the transfer buffer
u8 I2C0_Buffer[I2C_BUFFER_LEN];
u8 I2C1_Buffer[I2C_BUFFER_LEN];
 
volatile I2C_Bus_t I2C0_Bus;
volatile I2C_Bus_t I2C1_Bus;
 
// Retourns pointer to data structure of the selected bus
volatile I2C_Bus_t* I2CBus(I2C_TypeDef* I2Cx)
{
volatile I2C_Bus_t *pBus = NULL;
 
if(I2Cx == I2C0) pBus = &I2C0_Bus;
if(I2Cx == I2C1) pBus = &I2C1_Bus;
 
return(pBus);
}
 
//--------------------------------------------------------------
void I2CBus_Init(I2C_TypeDef* I2Cx)
{
volatile I2C_Bus_t *pBus = NULL;
I2C_InitTypeDef I2C_Struct;
GPIO_InitTypeDef GPIO_InitStructure;
u8 SCL_Pin = 0;
u8 SDA_Pin = 0;
u32 SCL_Clock = 0;
u32 APBPeriph = 0;
u8 VIC_Priority = 0;
 
if (I2Cx == I2C0)
{
UART1_PutString("\r\n I2C0 init...");
SCL_Pin = GPIO_Pin_0;
SDA_Pin = GPIO_Pin_1;
SCL_Clock = I2C0_CLOCK;
APBPeriph = __I2C0;
VIC_Priority = PRIORITY_I2C0;
 
pBus = &I2C0_Bus;
pBus->pData = I2C0_Buffer;
pBus->VIC_Source = I2C0_ITLine;
}
if (I2Cx == I2C1)
{
UART1_PutString("\r\n I2C1 init...");
SCL_Pin = GPIO_Pin_2;
SDA_Pin = GPIO_Pin_3;
SCL_Clock = I2C1_CLOCK;
APBPeriph = __I2C1;
VIC_Priority = PRIORITY_I2C1;
 
pBus = &I2C1_Bus;
pBus->pData = I2C1_Buffer;
pBus->VIC_Source = I2C1_ITLine;
}
if(pBus == NULL) return;
pBus->State = I2C_STATE_UNDEF;
pBus->Error = I2C_ERROR_UNKNOWN;
pBus->Timeout = 0;
pBus->TxBufferSize = 0;
pBus->RxBufferSize = 0;
pBus->Direction = 0;
pBus->SlaveAddr = 0;
pBus->pRxHandler = NULL;
 
// enable Port 2 peripherie
SCU_APBPeriphClockConfig(__GPIO2, ENABLE);
// disable a reset state
SCU_APBPeriphReset(__GPIO2, DISABLE);
 
// free a busy bus
 
// At switch on I2C devices can get in a state where they
// are still waiting for a command due to all the bus lines bouncing
// around at startup have started clocking data into the device(s).
// Enable the ports as open collector port outputs
// and clock out at least 9 SCL pulses, then generate a stop
// condition and then leave the clock line high.
 
// configure I2C_CLKOUT and I2C_DOUT to normal port operation
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Direction = GPIO_PinOutput;
GPIO_InitStructure.GPIO_Pin = SCL_Pin | SDA_Pin;
GPIO_InitStructure.GPIO_Type = GPIO_Type_OpenCollector;
GPIO_InitStructure.GPIO_IPInputConnected = GPIO_IPInputConnected_Disable;
GPIO_InitStructure.GPIO_Alternate = GPIO_OutputAlt1;
GPIO_Init(GPIO2, &GPIO_InitStructure);
 
u8 i;
u32 delay;
// set SCL high and then SDA to low (start condition)
GPIO_WriteBit(GPIO2, SCL_Pin, Bit_SET);
delay = SetDelay(1);
while (!CheckDelay(delay));
GPIO_WriteBit(GPIO2, SDA_Pin, Bit_RESET);
// toggle SCL at least 10 times from high to low to high
for(i = 0; i < 10; i++)
{
delay = SetDelay(1);
while (!CheckDelay(delay));
 
GPIO_WriteBit(GPIO2, SCL_Pin, Bit_RESET);
delay = SetDelay(1);
while (!CheckDelay(delay));
GPIO_WriteBit(GPIO2, SCL_Pin, Bit_SET);
}
delay = SetDelay(1);
while (!CheckDelay(delay));
// create stop condition setting SDA HIGH when SCL is HIGH
GPIO_WriteBit(GPIO2, SDA_Pin, Bit_SET);
 
 
// reconfigure I2C_CLKOUT and I2C_DOUT
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Direction = GPIO_PinOutput;
GPIO_InitStructure.GPIO_Pin = SCL_Pin | SDA_Pin;
GPIO_InitStructure.GPIO_Type = GPIO_Type_OpenCollector;
GPIO_InitStructure.GPIO_IPInputConnected = GPIO_IPInputConnected_Enable;
GPIO_InitStructure.GPIO_Alternate = GPIO_OutputAlt2; //I2C_CLKOUT, I2C_DOUT
GPIO_Init(GPIO2, &GPIO_InitStructure);
 
// enable I2C peripherie
SCU_APBPeriphClockConfig(APBPeriph, ENABLE);
// reset I2C peripherie
SCU_APBPeriphReset(APBPeriph, ENABLE);
SCU_APBPeriphReset(APBPeriph, DISABLE);
 
I2C_DeInit(I2Cx);
I2C_StructInit(&I2C_Struct);
I2C_Struct.I2C_GeneralCall = I2C_GeneralCall_Disable;
I2C_Struct.I2C_Ack = I2C_Ack_Enable;
I2C_Struct.I2C_CLKSpeed = SCL_Clock;
I2C_Struct.I2C_OwnAddress = 0x00;
I2C_Init(I2Cx, &I2C_Struct);
 
I2C_Cmd(I2Cx, ENABLE);
I2C_ITConfig(I2Cx, ENABLE);
 
VIC_Config(pBus->VIC_Source, VIC_IRQ , VIC_Priority);
pBus->Timeout = SetDelay(2*I2C_TIMEOUT);
I2C_GenerateSTOP(I2Cx, ENABLE);
pBus->State = I2C_STATE_IDLE;
 
// start some dummy transmissions cycles
// to get the irq routine to work
for(i = 0; i < 10; i++)
{
pBus->State = I2C_STATE_BUFFBUSY;
I2CBus_Transmission(I2Cx, 0, NULL, 1, 0, 0); // transfer 1 byte in the isr
if(I2CBus_WaitForEndOfTransmission(I2Cx, 10)) break;
UART1_Putchar('.');
}
UART1_PutString("ok");
}
 
 
//--------------------------------------------------------------
void I2CBus_Deinit(I2C_TypeDef* I2Cx)
{
volatile I2C_Bus_t *pBus = NULL;
GPIO_InitTypeDef GPIO_InitStructure;
u32 APBPeriph = 0;
u16 VIC_Source = 0;
u8 SCL_Pin = 0;
u8 SDA_Pin = 0;
 
if (I2Cx == I2C0)
{
UART1_PutString("\r\n I2C0 deinit...");
SCL_Pin = GPIO_Pin_0;
SDA_Pin = GPIO_Pin_1;
APBPeriph = __I2C0;
VIC_Source = I2C0_ITLine;
pBus = &I2C0_Bus;
}
if (I2Cx == I2C1)
{
UART1_PutString("\r\n I2C1 deinit...");
SCL_Pin = GPIO_Pin_2;
SDA_Pin = GPIO_Pin_3;
APBPeriph = __I2C1;
VIC_Source = I2C1_ITLine;
pBus = &I2C1_Bus;
}
 
if(pBus == NULL) return;
 
I2C_GenerateStart(I2Cx, DISABLE);
I2C_GenerateSTOP(I2Cx, ENABLE);
VIC_ITCmd(VIC_Source, DISABLE);
pBus->State = I2C_STATE_UNDEF;
I2C_ITConfig(I2Cx, DISABLE);
I2C_Cmd(I2Cx, DISABLE);
I2C_DeInit(I2Cx);
SCU_APBPeriphClockConfig(APBPeriph, DISABLE);
 
// set ports to input
SCU_APBPeriphClockConfig(__GPIO2, ENABLE);
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Direction = GPIO_PinInput;
GPIO_InitStructure.GPIO_Pin = SCL_Pin | SDA_Pin;
GPIO_InitStructure.GPIO_Type = GPIO_Type_PushPull;
GPIO_InitStructure.GPIO_IPInputConnected = GPIO_IPInputConnected_Disable;
GPIO_InitStructure.GPIO_Alternate = GPIO_InputAlt1;
GPIO_Init(GPIO2, &GPIO_InitStructure);
 
// empty rx and tx buffer
pBus->TxBufferSize = 0;
pBus->RxBufferSize = 0;
 
pBus->Timeout = SetDelay(2*I2C_TIMEOUT);
 
UART1_PutString("ok");
}
 
//--------------------------------------------------------------
void I2C0_IRQHandler(void)
{
static u8 Rx_Idx = 0, Tx_Idx = 0;
u16 status;
u16 timeout = 500;
 
//IENABLE; // do not enable IRQ nesting for I2C!!!!
// detemine I2C State
status = I2C_GetLastEvent(I2C0);
 
if(status & (I2C_FLAG_AF|I2C_FLAG_BERR)) // if an acknowledge failure or bus error occured
{ // Set and subsequently clear the STOP bit while BTF is set.
while(I2C_GetFlagStatus (I2C0, I2C_FLAG_BTF) != RESET)
{
I2C_GenerateSTOP (I2C0, ENABLE); // free the bus
I2C_GenerateSTOP (I2C0, DISABLE); // free the bus
if(--timeout == 0)
{
DebugOut.Analog[14]++; // count I2C error
break;
}
}
I2C0_Bus.State = I2C_STATE_IDLE;
I2C0_Bus.Error = I2C_ERROR_NOACK;
VIC_ITCmd(I2C0_ITLine, DISABLE);
return;
}
else
{ // depending on current i2c state
switch(status)
{
// the start condition was initiated on the bus
case I2C_EVENT_MASTER_MODE_SELECT:
// update current bus state variable
// jump to rx state if there is nothing to send
switch(I2C0_Bus.Direction)
{
case I2C_MODE_TRANSMITTER:
I2C0_Bus.State = I2C_STATE_TX_PROGRESS;
break;
 
case I2C_MODE_RECEIVER:
if (I2C0_Bus.RxBufferSize == 0) // nothing to send?
{
I2C_GenerateSTOP (I2C0, ENABLE);
VIC_ITCmd(I2C0_ITLine, DISABLE);
I2C0_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_NONE;
return;
}
else
{
I2C0_Bus.State = I2C_STATE_RX_PROGRESS;
}
break;
 
default: // invalid direction
I2C_GenerateSTOP (I2C0, ENABLE);
VIC_ITCmd(I2C0_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_UNKNOWN;
return;
}
// enable acknowledge
I2C_AcknowledgeConfig (I2C0, ENABLE);
// send address/direction byte on the bus
I2C_Send7bitAddress(I2C0, I2C0_Bus.SlaveAddr, I2C0_Bus.Direction);
break;
 
// the address byte was send
case I2C_EVENT_MASTER_MODE_SELECTED:
// Clear EV6 by set again the PE bit
I2C_Cmd(I2C0, ENABLE);
switch(I2C0_Bus.State)
{
case I2C_STATE_TX_PROGRESS:
// send 1st data byte
Tx_Idx = 0;
I2C_SendData(I2C0, I2C0_Bus.pData[Tx_Idx]);
Tx_Idx++;
// reset timeout
I2C0_Bus.Timeout = SetDelay(I2C_TIMEOUT); // after inactivity the I2C1 bus will be reset
break;
 
case I2C_STATE_RX_PROGRESS:
Rx_Idx = 0;
// disable acknoledge if only one byte has to be read
if(I2C0_Bus.RxBufferSize == 1) I2C_AcknowledgeConfig (I2C0, DISABLE);
break;
 
default: // unknown I2C state
// should never happen
I2C_GenerateSTOP (I2C0, ENABLE);
VIC_ITCmd(I2C0_ITLine, DISABLE);
I2C0_Bus.State = I2C_STATE_IDLE;
I2C0_Bus.Error = I2C_ERROR_UNKNOWN;
return;
break;
}
break;
 
// the master has transmitted a byte and slave has been acknowledged
case I2C_EVENT_MASTER_BYTE_TRANSMITTED:
 
// some bytes have to be transmitted
if(Tx_Idx < I2C0_Bus.TxBufferSize)
{
I2C_SendData(I2C0, I2C0_Bus.pData[Tx_Idx]);
Tx_Idx++;
}
else // last byte was send
{
// generate stop or repeated start condition
if (I2C0_Bus.RxBufferSize > 0) // is any answer byte expected?
{
I2C0_Bus.Direction = I2C_MODE_RECEIVER; // switch to master receiver after repeated start condition
I2C_GenerateStart(I2C0, ENABLE); // initiate repeated start condition on the bus
}
else
{ // stop communication
I2C_GenerateSTOP(I2C0, ENABLE); // generate stop condition to free the bus
VIC_ITCmd(I2C0_ITLine, DISABLE);
I2C0_Bus.State = I2C_STATE_IDLE; // ready for new actions
I2C0_Bus.Error = I2C_ERROR_NONE;
}
}
break;
 
// the master has received a byte from the slave
case I2C_EVENT_MASTER_BYTE_RECEIVED:
// some bytes have to be received
if ( Rx_Idx+1 < I2C0_Bus.RxBufferSize)
{ // copy received byte from the data register to the rx-buffer
I2C0_Bus.pData[Rx_Idx] = I2C_ReceiveData(I2C0);
}
else // if the last byte was received
{
// generate a STOP condition on the bus before reading data register
I2C_GenerateSTOP(I2C0, ENABLE);
I2C0_Bus.pData[Rx_Idx] = I2C_ReceiveData(I2C0);
// call the rx handler function to process recieved data
if(I2C0_Bus.pRxHandler != NULL) (*(I2C0_Bus.pRxHandler))(I2C0_Bus.pData, I2C0_Bus.RxBufferSize);
I2C0_Bus.Timeout = SetDelay(I2C_TIMEOUT);
DebugOut.Analog[15]++;
VIC_ITCmd(I2C0_ITLine, DISABLE);
I2C0_Bus.State = I2C_STATE_IDLE;
I2C0_Bus.Error = I2C_ERROR_NONE;
return;
}
Rx_Idx++;
// if the 2nd last byte was received disable acknowledge for the last one
if ( (Rx_Idx + 1) == I2C0_Bus.RxBufferSize )
{
I2C_AcknowledgeConfig(I2C0, DISABLE);
}
break;
 
default:// unknown event
// should never happen
I2C_GenerateSTOP (I2C0, ENABLE);
VIC_ITCmd(I2C0_ITLine, DISABLE);
I2C0_Bus.State = I2C_STATE_IDLE;
I2C0_Bus.Error = I2C_ERROR_UNKNOWN;
break;
}
}
//IDISABLE; // do not enable IRQ nesting for I2C!!!!
VIC1->VAR = 0xFF; // write any value to VIC1 Vector address register
}
 
//--------------------------------------------------------------
void I2C1_IRQHandler(void)
{
static u8 Rx_Idx = 0, Tx_Idx = 0;
u16 status;
u16 timeout = 500;
 
//IENABLE; // do not enable IRQ nesting for I2C!!!!
// detemine I2C State
status = I2C_GetLastEvent(I2C1);
 
if(status & (I2C_FLAG_AF|I2C_FLAG_BERR)) // if an acknowledge failure or bus error occured
{ // Set and subsequently clear the STOP bit while BTF is set.
while(I2C_GetFlagStatus (I2C1, I2C_FLAG_BTF) != RESET)
{
I2C_GenerateSTOP (I2C1, ENABLE); // free the bus
I2C_GenerateSTOP (I2C1, DISABLE); // free the bus
if(--timeout == 0)
{
DebugOut.Analog[14]++; // count I2C error
break;
}
}
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_NOACK;
VIC_ITCmd(I2C1_ITLine, DISABLE);
return;
}
else
{ // depending on current i2c state
switch(status)
{
// the start condition was initiated on the bus
case I2C_EVENT_MASTER_MODE_SELECT:
// update current bus state variable
// jump to rx state if there is nothing to send
switch(I2C1_Bus.Direction)
{
case I2C_MODE_TRANSMITTER:
I2C1_Bus.State = I2C_STATE_TX_PROGRESS;
break;
 
case I2C_MODE_RECEIVER:
if (I2C1_Bus.RxBufferSize == 0) // nothing to send?
{
I2C_GenerateSTOP (I2C1, ENABLE);
VIC_ITCmd(I2C1_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_NONE;
return;
}
else
{
I2C1_Bus.State = I2C_STATE_RX_PROGRESS;
}
break;
 
default: // invalid direction
I2C_GenerateSTOP (I2C1, ENABLE);
VIC_ITCmd(I2C1_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_UNKNOWN;
return;
}
// enable acknowledge
I2C_AcknowledgeConfig (I2C1, ENABLE);
// send address/direction byte on the bus
I2C_Send7bitAddress(I2C1, I2C1_Bus.SlaveAddr, I2C1_Bus.Direction);
break;
 
// the address byte was send
case I2C_EVENT_MASTER_MODE_SELECTED:
// Clear EV6 by set again the PE bit
I2C_Cmd(I2C1, ENABLE);
switch(I2C1_Bus.State)
{
case I2C_STATE_TX_PROGRESS:
// send 1st data byte
Tx_Idx = 0;
I2C_SendData(I2C1, I2C1_Bus.pData[Tx_Idx]);
Tx_Idx++;
// reset timeout
I2C1_Bus.Timeout = SetDelay(I2C_TIMEOUT); // after inactivity the I2C1 bus will be reset
break;
 
case I2C_STATE_RX_PROGRESS:
Rx_Idx = 0;
// disable acknoledge if only one byte has to be read
if(I2C1_Bus.RxBufferSize == 1) I2C_AcknowledgeConfig (I2C1, DISABLE);
break;
 
default: // unknown I2C state
// should never happen
I2C_GenerateSTOP (I2C1, ENABLE);
VIC_ITCmd(I2C1_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_UNKNOWN;
return;
break;
}
break;
 
// the master has transmitted a byte and slave has been acknowledged
case I2C_EVENT_MASTER_BYTE_TRANSMITTED:
 
// some bytes have to be transmitted
if(Tx_Idx < I2C1_Bus.TxBufferSize)
{
I2C_SendData(I2C1, I2C1_Bus.pData[Tx_Idx]);
Tx_Idx++;
}
else // last byte was send
{
// generate stop or repeated start condition
if (I2C1_Bus.RxBufferSize > 0) // is any answer byte expected?
{
I2C1_Bus.Direction = I2C_MODE_RECEIVER; // switch to master receiver after repeated start condition
I2C_GenerateStart(I2C1, ENABLE); // initiate repeated start condition on the bus
}
else
{ // stop communication
I2C_GenerateSTOP(I2C1, ENABLE); // generate stop condition to free the bus
VIC_ITCmd(I2C1_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE; // ready for new actions
I2C1_Bus.Error = I2C_ERROR_NONE;
}
}
break;
 
// the master has received a byte from the slave
case I2C_EVENT_MASTER_BYTE_RECEIVED:
// some bytes have to be received
if ( Rx_Idx+1 < I2C1_Bus.RxBufferSize)
{ // copy received byte from the data register to the rx-buffer
I2C1_Bus.pData[Rx_Idx] = I2C_ReceiveData(I2C1);
}
else // if the last byte was received
{
// generate a STOP condition on the bus before reading data register
I2C_GenerateSTOP(I2C1, ENABLE);
I2C1_Bus.pData[Rx_Idx] = I2C_ReceiveData(I2C1);
// call the rx handler function to process recieved data
if(I2C1_Bus.pRxHandler != NULL) (*(I2C1_Bus.pRxHandler))(I2C1_Bus.pData, I2C1_Bus.RxBufferSize);
I2C1_Bus.Timeout = SetDelay(I2C_TIMEOUT);
DebugOut.Analog[15]++;
VIC_ITCmd(I2C1_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_NONE;
return;
}
Rx_Idx++;
// if the 2nd last byte was received disable acknowledge for the last one
if ( (Rx_Idx + 1) == I2C1_Bus.RxBufferSize )
{
I2C_AcknowledgeConfig(I2C1, DISABLE);
}
break;
 
default:// unknown event
// should never happen
I2C_GenerateSTOP (I2C1, ENABLE);
VIC_ITCmd(I2C1_ITLine, DISABLE);
I2C1_Bus.State = I2C_STATE_IDLE;
I2C1_Bus.Error = I2C_ERROR_UNKNOWN;
break;
}
}
//IDISABLE; // do not enable IRQ nesting for I2C!!!!
VIC1->VAR = 0xFF; // write any value to VIC1 Vector address register
}
 
// ----------------------------------------------------------------------------------------
// wait for end of transmission
// returns 1 on success or 0 on timeout
u8 I2CBus_WaitForEndOfTransmission(I2C_TypeDef* I2Cx, u32 timeout)
{
volatile I2C_Bus_t *pBus = NULL;
u32 time = SetDelay(timeout);
 
if(I2Cx == I2C0) pBus = &I2C0_Bus;
if(I2Cx == I2C1) pBus = &I2C1_Bus;
if(pBus == NULL) return(0);
while(pBus->State != I2C_STATE_IDLE)
{
if(CheckDelay(time)) return(0);
}
return(1);
}
 
// ----------------------------------------------------------------------------------------
// try to get access to the transfer buffer within a timeout limit
// returs 1 on success and 0 on error/timeout
u8 I2CBus_LockBuffer(I2C_TypeDef* I2Cx, u32 timeout)
{
volatile I2C_Bus_t *pBus = NULL;
 
if(I2Cx == I2C0) pBus = &I2C0_Bus;
if(I2Cx == I2C1) pBus = &I2C1_Bus;
if(pBus == NULL) return(0);
if(I2CBus_WaitForEndOfTransmission(I2Cx, timeout))
{
pBus->State = I2C_STATE_BUFFBUSY;
pBus->Error = I2C_ERROR_UNKNOWN;
return(1);
}
else return(0);
}
// ----------------------------------------------------------------------------------------
// initate an i2c transmission
// before that function is called, the application has to call I2CBus_LockBuffer and has to fill the Buffer with data to be send
u8 I2CBus_Transmission(I2C_TypeDef* I2Cx, u8 SlaveAddr, u8* pTxData, u8 TxBytes, I2C_pRxHandler_t pRxHandler, u8 RxBytes)
{
u8 retval = 0;
volatile I2C_Bus_t *pBus = NULL;
 
if(I2Cx == I2C0) pBus = &I2C0_Bus;
if(I2Cx == I2C1) pBus = &I2C1_Bus;
if(pBus == NULL) return(0);
 
 
if(pBus->State == I2C_STATE_BUFFBUSY) // check for locked buffer
{
if((RxBytes > I2C_BUFFER_LEN) || (TxBytes > I2C_BUFFER_LEN))
{
pBus->State = I2C_STATE_IDLE;
return(retval);
}
pBus->RxBufferSize = RxBytes;
pBus->TxBufferSize = TxBytes;
// set direction to master transmitter
if( (pBus->TxBufferSize > 0) && (pBus->TxBufferSize < I2C_BUFFER_LEN) )
{
pBus->Direction = I2C_MODE_TRANSMITTER;
// copy data to send from source to tansfer buffer
if(pTxData) memcpy(pBus->pData, pTxData, pBus->TxBufferSize);
}
else if (( pBus->RxBufferSize > 0 ) && (pBus->RxBufferSize < I2C_BUFFER_LEN) )
{
pBus->Direction = I2C_MODE_RECEIVER;
}
else // nothing to send or receive
{
pBus->State = I2C_STATE_IDLE;
pBus->Error = I2C_ERROR_NONE;
pBus->TxBufferSize = 0;
pBus->RxBufferSize = 0;
return(retval);
}
// update slave address and rx data handler function pointer
pBus->SlaveAddr = SlaveAddr;
pBus->pRxHandler = pRxHandler;
// test on busy flag and clear it
I2C_ClearFlag(I2Cx, I2C_FLAG_BUSY);
// enable I2C IRQ
VIC_ITCmd(pBus->VIC_Source, ENABLE);
// initiate start condition on the bus
I2C_GenerateStart(I2Cx, ENABLE);
retval = 1;
}
return(retval);
}
/trunk/i2c.h
0,0 → 1,64
#ifndef __I2C_H
#define __I2C_H
 
#include "91x_lib.h"
 
// I2C states
#define I2C_STATE_UNDEF 0
#define I2C_STATE_IDLE 1
#define I2C_STATE_BUFFBUSY 2
#define I2C_STATE_TX_PENDING 3
#define I2C_STATE_TX_PROGRESS 4
#define I2C_STATE_RX_PENDING 5
#define I2C_STATE_RX_PROGRESS 6
// I2C Errors
#define I2C_ERROR_NONE 0
#define I2C_ERROR_UNKNOWN 1
#define I2C_ERROR_NOACK 2
 
// the pointer to the rxbuffer handler function
// called by the IRQ routine after all bytes are recieved from slave
typedef void (*I2C_pRxHandler_t) (u8* pRxBuffer, u8 RxBufferSize);
 
 
typedef struct
{
u8 State; // bus status
u8 Error; // bus error code
u32 Timeout; // # time of last transfer
u8 *pData; // # data buffer
u8 TxBufferSize; // # of bytes to send
u8 RxBufferSize; // # of bytes to read
u8 Direction; // bus direction
u8 SlaveAddr; // slave address
u16 VIC_Source; // irq source
I2C_pRxHandler_t pRxHandler; // function pointer to call back handler after transfer
} __attribute__((packed)) I2C_Bus_t;
 
#define I2C_TIMEOUT 500 // 500 ms
#define I2C_BUFFER_LEN 100 // define the size of the rx/tx buffer in bytes
 
// Retourns pointer to data structure of the selected bus
volatile I2C_Bus_t* I2CBus(I2C_TypeDef* I2Cx);
 
// initialize the I2C bus
void I2CBus_Init(I2C_TypeDef* I2Cx);
// deinitialize the I2C bus
void I2CBus_Deinit(I2C_TypeDef* I2Cx);
// try to allocate the I2C_Buffer within the timeout limit
// returns 1 on success
u8 I2CBus_LockBuffer(I2C_TypeDef* I2Cx, u32 timeout);
// Initiate i2c transmission
// A transmission sends first TxBytes from pTxData to slave
// and then RxBytes are read from slave to internal buffer
// replacing the byte that have been sent.
// Then the RxHandler function is called to handle the result.
// This function returns imediatly after a start condition in the bus.
// returns 1 if a transmission has been started, returns 0 otherwise
u8 I2CBus_Transmission(I2C_TypeDef* I2Cx, u8 SlaveAddr, u8* pTxData, u8 TxBytes, I2C_pRxHandler_t pRxHandler, u8 RxBytes);
// wait until transmission progess is finished or timeout
// returns 1 if no timeout occurs
u8 I2CBus_WaitForEndOfTransmission(I2C_TypeDef* I2Cx, u32 timeout);
 
#endif // I2C_H
 
/trunk/libstr91x/src/91x_it.c
21,7 → 21,6
 
/* Includes ------------------------------------------------------------------*/
#include "91x_it.h"
//#include "usb_lib.h"
#include "fat16.h"
#include "main.h"
#include "uart1.h"
373,7 → 372,6
* Output : None
* Return : None
*******************************************************************************/
 
void SSP1_IRQHandler(void)
{
}
/trunk/main.c
62,8 → 62,7
#include "uart1.h"
#include "uart2.h"
#include "gps.h"
#include "i2c0.h"
#include "i2c1.h"
#include "i2c.h"
#include "compass.h"
#include "ncmag.h"
#include "timer1.h"
82,9 → 81,9
#include "ssc.h"
#include "sdc.h"
#include "uart1.h"
#include "ncmag.h"
 
 
 
#ifdef FOLLOW_ME
u8 TransmitAlsoToFC = 0;
#endif
146,9 → 145,7
s32 newErrorCode = 0;
UART_VersionInfo.HardwareError[0] = 0;
 
if((I2C_CompassPort == I2C_INTERN_1 && CheckDelay(I2C1_Timeout)) || (I2C_CompassPort == I2C_EXTERN_0 && CheckDelay(I2C0_Timeout)) || (Compass_Heading < 0))
DebugOut.StatusRed |= AMPEL_COMPASS;
if(CheckDelay(I2CBus(Compass_I2CPort)->Timeout) || (Compass_Heading < 0)) DebugOut.StatusRed |= AMPEL_COMPASS;
else DebugOut.StatusRed &= ~AMPEL_COMPASS; // MK3Mag green status
 
if((FC.Error[1] & FC_ERROR1_I2C) || (FC.Error[1] & FC_ERROR1_BL_MISSING)) DebugOut.StatusRed |= AMPEL_BL;
157,45 → 154,27
if(UART_VersionInfo.HardwareError[0] || UART_VersionInfo.HardwareError[1]) DebugOut.StatusRed |= AMPEL_NC;
else DebugOut.StatusRed &= ~AMPEL_NC;
 
if(I2C_CompassPort == I2C_EXTERN_0) LED_RED_OFF_T;
 
if((FCCalibActive || CompassCalState) && FC_Version.Hardware)
{
{
sprintf(ErrorMSG,"Calibrate... ");
newErrorCode = 0;
ErrorCode = 0;
no_error_delay = 1;
}
else if(CheckDelay(I2C1_Timeout) && (I2C_CompassPort == I2C_INTERN_1))
}
else if(CheckDelay(I2CBus(Compass_I2CPort)->Timeout))
{
LED_RED_ON;
sprintf(ErrorMSG,"no compass communica");
//Reset I2CBus
I2C1_Deinit();
I2C1_Init();
//Reset Compass communication
Compass_Init();
newErrorCode = 4;
StopNavigation = 1;
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_RX;
DebugOut.StatusRed |= AMPEL_COMPASS;
}
else if(CheckDelay(I2C0_Timeout) && (I2C_CompassPort == I2C_EXTERN_0))
else if(CheckDelay(SPI0_Timeout))
{
LED_RED_ON;
LED_RED_ON_T;
sprintf(ErrorMSG,"no ext. compass ");
//Reset I2CBus
I2C0_Deinit();
I2C0_Init();
NCMAG_Update(1);
newErrorCode = 33;
StopNavigation = 1;
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_RX;
DebugOut.StatusRed |= AMPEL_COMPASS;
}
else
if(CheckDelay(SPI0_Timeout))
{
LED_RED_ON;
sprintf(ErrorMSG,"no FC communication ");
newErrorCode = 3;
StopNavigation = 1;
216,7 → 195,6
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_FC_INCOMPATIBLE;
DebugOut.StatusRed |= AMPEL_NC;
}
 
else if(FC.Error[0] & FC_ERROR0_GYRO_NICK)
{
LED_RED_ON;
288,12 → 266,12
LED_RED_ON;
// if(!(Parameter.GlobalConfig & FC_CFG_GPS_AKTIV)) sprintf(ErrorMSG,"GPS disconnected ");
// else
{
sprintf(ErrorMSG,"no GPS communication");
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_GPS_RX;
UART_VersionInfo.Flags &= ~NC_VERSION_FLAG_GPS_PRESENT;
newErrorCode = 5;
}
{
sprintf(ErrorMSG,"no GPS communication");
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_GPS_RX;
UART_VersionInfo.Flags &= ~NC_VERSION_FLAG_GPS_PRESENT;
newErrorCode = 5;
}
StopNavigation = 1;
// UBX_Timeout = SetDelay(500);
}
334,76 → 312,75
}
else if(ErrorGpsFixLost)
{
LED_RED_ON;
sprintf(ErrorMSG,"GPS Fix lost ");
newErrorCode = 21;
LED_RED_ON;
sprintf(ErrorMSG,"GPS Fix lost ");
newErrorCode = 21;
}
else if(ErrorDisturbedEarthMagnetField)
{
LED_RED_ON;
sprintf(ErrorMSG,"Magnet error ");
newErrorCode = 22;
DebugOut.StatusRed |= AMPEL_COMPASS | AMPEL_NC;
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_VALUE;
LED_RED_ON;
sprintf(ErrorMSG,"Magnet error ");
newErrorCode = 22;
DebugOut.StatusRed |= AMPEL_COMPASS | AMPEL_NC;
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_VALUE;
}
else if(((BL_MinOfMaxPWM == 40 && (FC.StatusFlags & FC_STATUS_FLY)) || BL_MinOfMaxPWM == 39) && !ErrorCode)
{
LED_RED_ON;
sprintf(ErrorMSG,"ERR:Motor restart ");
newErrorCode = 23;
DebugOut.StatusRed |= AMPEL_BL;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:Motor restart ");
newErrorCode = 23;
DebugOut.StatusRed |= AMPEL_BL;
}
else if(BL_MinOfMaxPWM < 30 && !ErrorCode)
{
unsigned int i;
for(i = 0; i < 12; i++) if(Motor[i].MaxPWM == BL_MinOfMaxPWM) break;
 
LED_RED_ON;
sprintf(ErrorMSG,"ERR:BL%2d Test:%2d ",i+1,BL_MinOfMaxPWM);
newErrorCode = 32;
DebugOut.StatusRed |= AMPEL_BL;
u16 i;
for(i = 0; i < 12; i++) if(Motor[i].MaxPWM == BL_MinOfMaxPWM) break;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:BL%2d Test:%2d ",i+1,BL_MinOfMaxPWM);
newErrorCode = 32;
DebugOut.StatusRed |= AMPEL_BL;
}
else if(BL_MinOfMaxPWM < 248 && (FC.StatusFlags & FC_STATUS_FLY) && !ErrorCode)
{
LED_RED_ON;
sprintf(ErrorMSG,"ERR:BL Limitation ");
newErrorCode = 24;
DebugOut.StatusRed |= AMPEL_BL;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:BL Limitation ");
newErrorCode = 24;
DebugOut.StatusRed |= AMPEL_BL;
}
else if(NCFlags & NC_FLAG_RANGE_LIMIT && (FC.StatusFlags & FC_STATUS_FLY) && !ErrorCode)
{
LED_RED_ON;
sprintf(ErrorMSG,"ERR:GPS range ");
newErrorCode = 25;
DebugOut.StatusRed |= AMPEL_NC;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:GPS range ");
newErrorCode = 25;
DebugOut.StatusRed |= AMPEL_NC;
}
else if((!SD_SWITCH || (SDCardInfo.Valid == 0)) && Parameter.GlobalConfig3 & CFG3_NO_SDCARD_NO_START && !(FC.StatusFlags & FC_STATUS_FLY))
{
LED_RED_ON;
sprintf(ErrorMSG,"ERR:No SD-Card ");
newErrorCode = 26;
DebugOut.StatusRed |= AMPEL_NC;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:No SD-Card ");
newErrorCode = 26;
DebugOut.StatusRed |= AMPEL_NC;
}
else if((SD_LoggingError || (SD_WatchDog < 2000 && SD_WatchDog != 0)) && Parameter.GlobalConfig3 & CFG3_NO_SDCARD_NO_START)
{
LED_RED_ON;
sprintf(ErrorMSG,"ERR:SD Logging abort");
newErrorCode = 27;
DebugOut.StatusRed |= AMPEL_NC;
SD_LoggingError = 0;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:SD Logging abort");
newErrorCode = 27;
DebugOut.StatusRed |= AMPEL_NC;
SD_LoggingError = 0;
}
else if(((AbsoluteFlyingAltitude) && (NaviData.Altimeter / 20 >= AbsoluteFlyingAltitude)) && (FC.StatusFlags & FC_STATUS_FLY))
{
LED_RED_ON;
sprintf(ErrorMSG,"ERR:Max Altitude ");
newErrorCode = 29;
DebugOut.StatusRed |= AMPEL_NC;
LED_RED_ON;
sprintf(ErrorMSG,"ERR:Max Altitude ");
newErrorCode = 29;
DebugOut.StatusRed |= AMPEL_NC;
}
else if(Parameter.GlobalConfig3 & CFG3_NO_GPSFIX_NO_START && !(NCFlags & NC_FLAG_GPS_OK) && ((FC.StatusFlags & (FC_STATUS_START | FC_STATUS_MOTOR_RUN)) || (FC.StickGas < -50 && FC.StickYaw < -50)))
{
LED_RED_ON;
sprintf(ErrorMSG,"No GPS Fix ");
newErrorCode = 30;
LED_RED_ON;
sprintf(ErrorMSG,"No GPS Fix ");
newErrorCode = 30;
}
else // no error occured
{
411,10 → 388,10
LED_RED_OFF;
if(no_error_delay) { no_error_delay--; }
else
{
sprintf(ErrorMSG,"No Error ");
ErrorCode = 0;
}
{
sprintf(ErrorMSG,"No Error ");
ErrorCode = 0;
}
}
 
if(newErrorCode)
499,8 → 476,8
int main(void)
{
static u32 ftimer =0;
static u8 fstate = 0;
// static u32 ftimer =0;
// static u8 fstate = 0;
// static File_t* f = NULL;
530,8 → 507,8
// initialize SPI0 to FC
SPI0_Init();
// initialize i2c busses (needs Timer 1)
I2C0_Init();
I2C1_Init();
I2CBus_Init(I2C0);
I2CBus_Init(I2C1);
 
// initialize fat16 partition on sd card (needs Timer 1)
Fat16_Init();
/trunk/main.h
194,8 → 194,8
u8 Error[5];
u8 StatusFlags2;
u8 FromFC_SpeakHoTT;
s16 FromFC_CompassOffset;
u8 FromFC_DisableDeclination;
s16 FromFC_CompassOffset;
u8 FromFC_DisableDeclination;
} __attribute__((packed)) FC_t; // from FC
 
 
/trunk/menu.c
68,7 → 68,6
#include "ncmag.h"
#include "logging.h"
#include "settings.h"
#include "gpx.h"
 
u8 DispPtr = 0;
s8 DisplayBuff[DISPLAYBUFFSIZE];
88,7 → 87,6
for( i = 0; i < DISPLAYBUFFSIZE; i++) DisplayBuff[i] = ' ';
}
 
 
// Display with 20 characters in 4 lines
void Menu_Update(u8 Keys)
{
358,7 → 356,8
LCD_printfxy(0,0,"GyroNick: %4i", FromFlightCtrl.GyroNick);
LCD_printfxy(0,1,"GyroRoll: %4i", FromFlightCtrl.GyroRoll);
LCD_printfxy(0,2,"GyroYaw: %4i", FromFlightCtrl.GyroYaw);
if(FC_is_Calibrated) LCD_printfxy(0,3,"Calibrated ") else LCD_printfxy(0,3,"not calibrated");
if(FC_is_Calibrated) LCD_printfxy(0,3,"Calibrated ")
else LCD_printfxy(0,3,"not calibrated");
break;
case 15:
// LCD_printfxy(0,0,"Ubat: %2i.%1i V", FC.BAT_Voltage/10, FC.BAT_Voltage%10);
366,13 → 365,13
LCD_printfxy(0,1,"Man.-Offset:%3i", FC.FromFC_CompassOffset / 10);
if(FC.FromFC_DisableDeclination)
{
LCD_printfxy(0,2,"Mag.Declinat.:disabl");
LCD_printfxy(0,2,"Mag.Declinat.:disabl");
}
else
{
if(GeoMagDec < 0) sign = '-';
else sign = '+';
LCD_printfxy(0,2,"Mag.Declinat.:%c%i.%1i", sign, abs(GeoMagDec)/10,abs(GeoMagDec)%10);
if(GeoMagDec < 0) sign = '-';
else sign = '+';
LCD_printfxy(0,2,"Mag.Declinat.:%c%i.%1i", sign, abs(GeoMagDec)/10,abs(GeoMagDec)%10);
}
LCD_printfxy(0,3,"True Compass: %3i", GyroCompassCorrected/10);
break;
427,7 → 426,8
LCD_printfxy(0,2,"Y:%5i",MagVector.Y);
LCD_printfxy(0,3,"Z:%5i",MagVector.Z);
LCD_printfxy(8,1,"Field:%3i",EarthMagneticField/5);
if(I2C_CompassPort == I2C_EXTERN_0) LCD_printfxy(11,2,"Extern %d",ExtCompassOrientation) else LCD_printfxy(11,2,"Intern");
if(Compass_I2CPort == NCMAG_PORT_EXTERN) LCD_printfxy(11,2,"Extern")
else LCD_printfxy(11,2,"Intern");
// LCD_printfxy(8,2,"Dec:%c%i.%1i", sign, abs(GeoMagDec)/10,abs(GeoMagDec)%10);
// LCD_printfxy(8,3,"Inc:%2i", EarthMagneticInclination);
LCD_printfxy(15,3,"(CAL)");
459,30 → 459,31
if(FreqGpsProcessedIn5Sec >= 350) LCD_printfxy(18,3,"OK") else LCD_printfxy(18,3,"!!");
break;
case 22:
LCD_printfxy(0,0,"BL Current" );
LCD_printfxy(11,3,"(in 0.1A)" );
for(i1 = 0; i1 < 3; i1++)
{
LCD_printfxy(0,0,"BL Current" );
LCD_printfxy(11,3,"(in 0.1A)" );
for(i1 = 0; i1 < 3; i1++)
{
LCD_printfxy(0,i1+1,"%3d %3d %3d %3d ",BL3_Current(i1*4),BL3_Current(i1*4+1),BL3_Current(i1*4+2),BL3_Current(i1*4+3));
if(Motor[4 + i1 * 4].State == 0) break;
}
break;
 
case 23:
LCD_printfxy(0,0,"Ext. Compass" );
if(I2C_CompassPort == I2C_EXTERN_0)
{
LCD_printfxy(0,0,"Ext. Compass" );
if(Compass_I2CPort == NCMAG_PORT_EXTERN)
{
u8 tmp;
LCD_printfxy(0,1,"ACC X Y Z");
LCD_printfxy(0,2," %5d %5d %5d",AccRawVector.X/40,AccRawVector.Y/40,AccRawVector.Z/40);
tmp = GetExtCompassOrientation();
LCD_printfxy(0,2," %5d %5d %5d", AccVector.X/40, AccVector.Y/40, AccVector.Z/40);
tmp = NCMAG_GetOrientationFromAcc();
LCD_printfxy(0,3,"Orientat.: ");
if(!tmp) LCD_printfxy(11,3,"??") else LCD_printfxy(11,3,"%2d",tmp);
LCD_printfxy(15,3,"(%d)",ExtCompassOrientation);
}
else
{
LCD_printfxy(0,1,"Not connected");
}
LCD_printfxy(15,3,"(%d)",NCMAG_Orientation);
}
else
{
LCD_printfxy(0,1,"Not connected");
}
break;
default:
//MaxMenuItem = MenuItem - 1;
/trunk/mk3mag.c
57,8 → 57,7
#include <string.h>
#include "91x_lib.h"
#include "mk3mag.h"
#include "i2c1.h"
#include "i2c0.h"
#include "i2c.h"
#include "timer1.h"
#include "led.h"
#include "main.h"
174,14 → 173,15
void MK3MAG_SendCommand(u8 command)
{
// try to catch the I2C buffer
if(I2C1_LockBuffer(0))
if(I2CBus_LockBuffer(I2C1, 0))
{
u8 TxData[100];
u16 TxBytes = 0;
u16 RxBytes = 0;
I2C_pRxHandler_t pRxHandlerFunc = NULL;
// update current command id
I2C1_Buffer[TxBytes++] = command;
TxData[TxBytes++] = command;
 
// set pointers to data area with respect to the command id
switch (command)
193,7 → 193,7
case MK3MAG_CMD_WRITE_CAL:
RxBytes = sizeof(MK3MAG_ReadCal)+1;
pRxHandlerFunc = &MK3MAG_UpdateCalibration;
memcpy((u8*)I2C1_Buffer+1, (u8*)&MK3MAG_WriteCal, sizeof(MK3MAG_WriteCal));
memcpy(TxData+TxBytes, (u8*)&MK3MAG_WriteCal, sizeof(MK3MAG_WriteCal));
TxBytes += sizeof(MK3MAG_WriteCal);
break;
case MK3MAG_CMD_READ_MAGVECT:
206,10 → 206,10
break;
}
// update packet checksum
I2C1_Buffer[TxBytes] = MK3MAG_CalcCRC((u8*)I2C1_Buffer, TxBytes);
TxData[TxBytes] = MK3MAG_CalcCRC(TxData, TxBytes);
TxBytes++;
// initiate I2C transmission
I2C1_Transmission(MK3MAG_SLAVE_ADDRESS, TxBytes, pRxHandlerFunc, RxBytes);
I2CBus_Transmission(I2C1, MK3MAG_SLAVE_ADDRESS, TxData, TxBytes, pRxHandlerFunc, RxBytes);
} // EOF I2C_State == I2C_IDLE
}
 
217,49 → 217,57
//----------------------------------------------------------------
u8 MK3MAG_Init(void)
{
u8 msg[64];
u8 repeat;
u32 timeout;
MK3MAG_Present = 0;
 
MK3MAG_Version.Major = 0xFF;
MK3MAG_Version.Minor = 0xFF;
MK3MAG_Version.Patch = 0xFF;
MK3MAG_Version.Compatible = 0xFF;
 
Compass_Heading = -1;
 
// polling of version info
repeat = 0;
do
if(MK3MAG_Present) // do only short init ! , full init was called before
{
MK3MAG_SendCommand(MK3MAG_CMD_VERSION);
if(Version_HW > 11) timeout = SetDelay(100);
else timeout = SetDelay(250);
 
do
{
if (MK3MAG_Version.Major != 0xFF) break; // break loop on success
}while (!CheckDelay(timeout));
UART1_PutString(".");
repeat++;
}while ((MK3MAG_Version.Major == 0xFF) && (repeat < 12)); // 12*250ms=3s
// if we got it
if (MK3MAG_Version.Major != 0xFF)
// try reconnect by reseting the I2C bus
I2CBus_Deinit(I2C1);
I2CBus_Init(I2C1);
}
else // full init
{
sprintf(msg, " MK3MAG V%d.%d%c", MK3MAG_Version.Major, MK3MAG_Version.Minor, 'a' + MK3MAG_Version.Patch);
UART1_PutString(msg);
if(MK3MAG_Version.Compatible != MK3MAG_I2C_COMPATIBLE)
u8 msg[64];
u8 repeat;
u32 timeout;
Compass_I2CPort = I2C1;
MK3MAG_Present = 0;
MK3MAG_Version.Major = 0xFF;
MK3MAG_Version.Minor = 0xFF;
MK3MAG_Version.Patch = 0xFF;
MK3MAG_Version.Compatible = 0xFF;
// polling of version info
repeat = 0;
do
{
UART1_PutString("\n\r MK3MAG not compatible!");
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_INCOMPATIBLE;
LED_RED_ON;
MK3MAG_SendCommand(MK3MAG_CMD_VERSION);
if(Version_HW > 11) timeout = SetDelay(100);
else timeout = SetDelay(250);
do
{
if (MK3MAG_Version.Major != 0xFF) break; // break loop on success
}while (!CheckDelay(timeout));
UART1_PutString(".");
repeat++;
}while ((MK3MAG_Version.Major == 0xFF) && (repeat < 12)); // 12*250ms=3s
// if we got it
if (MK3MAG_Version.Major != 0xFF)
{
sprintf(msg, " MK3MAG V%d.%d%c", MK3MAG_Version.Major, MK3MAG_Version.Minor, 'a' + MK3MAG_Version.Patch);
UART1_PutString(msg);
if(MK3MAG_Version.Compatible != MK3MAG_I2C_COMPATIBLE)
{
UART1_PutString("\n\r MK3MAG not compatible!");
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_INCOMPATIBLE;
LED_RED_ON;
}
else
{ // version ok
MK3MAG_Present = 1;
}
}
else
{ // version ok
MK3MAG_Present = 1;
}
}
return(MK3MAG_Present);
}
273,7 → 281,7
u8 msg[64];
u16 MinCaclibration = 500;
 
if( (I2C1_State == I2C_STATE_OFF) || !MK3MAG_Present ) return;
if( (I2CBus(I2C1)->State == I2C_STATE_UNDEF) || !MK3MAG_Present ) return;
if(CheckDelay(TimerUpdate))
{
/trunk/mkprotocol.c
54,10 → 54,10
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <stdarg.h>
#include <stdio.h>
#include "91x_lib.h"
#include "mkprotocol.h"
#include "ramfunc.h"
#include "usb.h"
#include "uart1.h"
#include "main.h"
 
/trunk/ncmag.c
55,12 → 55,11
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "91x_lib.h"
#include "ncmag.h"
#include "i2c1.h"
#include "i2c0.h"
 
#include "i2c.h"
#include "timer1.h"
#include "led.h"
#include "uart1.h"
72,16 → 71,7
u8 NCMAG_Present = 0;
u8 NCMAG_IsCalibrated = 0;
 
u8 I2C_CompassPort = 1;
u8 ExtCompassOrientation = 0;
 
u8 *I2C_BufferPnt;
u8 *I2C_ErrorPnt;
I2C_TransmissionFunc_t I2C_TransmissionFunc;
I2C_LockBufferFunc_t I2C_LockBufferFunc;
I2C_WaitForEndOfTransmissionFunc_t I2C_WaitForEndOfTransmissionFunc;
 
 
// supported magnetic sensor types
#define TYPE_NONE 0
#define TYPE_HMC5843 1
89,7 → 79,34
#define TYPE_LSM303DLM 3
 
u8 NCMAG_SensorType = TYPE_NONE;
u8 NCMAG_Orientation = 0;
 
// two calibrtion sets for extern and intern sensor
#define EEPROM_ADR_MAG_CALIBRATION_INTERN 50
#define EEPROM_ADR_MAG_CALIBRATION_EXTERN 70
 
#define CALIBRATION_VERSION 1
#define MAG_CALIBRATION_COMPATIBLE 0xA2
 
#define NCMAG_MIN_RAWVALUE -2047
#define NCMAG_MAX_RAWVALUE 2047
#define NCMAG_INVALID_DATA -4096
 
typedef struct
{
s16 Range;
s16 Offset;
} __attribute__((packed)) Scaling_t;
 
typedef struct
{
Scaling_t MagX;
Scaling_t MagY;
Scaling_t MagZ;
u8 Version;
u8 crc;
} __attribute__((packed)) Calibration_t;
 
Calibration_t Calibration; // calibration data in RAM
volatile s16vec_t AccRawVector;
volatile s16vec_t MagRawVector;
208,10 → 225,6
 
volatile MagConfig_t MagConfig;
 
 
 
 
 
// self test value
#define LSM303DLH_TEST_XSCALE 495
#define LSM303DLH_TEST_YSCALE 495
286,20 → 299,26
 
volatile AccConfig_t AccConfig;
 
u8 NCMag_CalibrationWrite(u8 intern) // two calibrtion sets for extern and intern sensor
// write calibration data for external and internal sensor seperately
u8 NCMag_CalibrationWrite(I2C_TypeDef* I2Cx)
{
u16 address;
u8 i, crc = MAG_CALIBRATION_COMPATIBLE;
u8 i = 0, crc = MAG_CALIBRATION_COMPATIBLE;
EEPROM_Result_t eres;
u8 *pBuff = (u8*)&Calibration;
Calibration.Version = CALIBRATION_VERSION;
 
if(intern == I2C_INTERN_1) address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
else
if (I2Cx == NCMAG_PORT_EXTERN)
{
address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
Calibration.Version = CALIBRATION_VERSION + ExtCompassOrientation * 16;
address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
Calibration.Version = CALIBRATION_VERSION + (NCMAG_Orientation<<4);;
}
else if (I2Cx == NCMAG_PORT_INTERN)
{
address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
Calibration.Version = CALIBRATION_VERSION;
}
else return(i);
 
for(i = 0; i<(sizeof(Calibration)-1); i++)
{
crc += pBuff[i];
311,14 → 330,16
return(i);
}
 
u8 NCMag_CalibrationRead(u8 intern) // two calibrtion sets for extern and intern sensor
// read calibration data for external and internal sensor seperately
u8 NCMag_CalibrationRead(I2C_TypeDef* I2Cx)
{
u8 i, crc = MAG_CALIBRATION_COMPATIBLE;
u8 address;
u8 i = 0, crc = MAG_CALIBRATION_COMPATIBLE;
u8 *pBuff = (u8*)&Calibration;
u16 address;
 
if(intern == I2C_INTERN_1) address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
else address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
if (I2Cx == NCMAG_PORT_EXTERN) address = EEPROM_ADR_MAG_CALIBRATION_EXTERN;
else if (I2Cx == NCMAG_PORT_INTERN) address = EEPROM_ADR_MAG_CALIBRATION_INTERN;
else return(0);
 
if(EEPROM_SUCCESS == EEPROM_ReadBlock(address, pBuff, sizeof(Calibration)))
{
328,7 → 349,7
}
crc = ~crc;
if(Calibration.crc != crc) return(0); // crc mismatch
if((Calibration.Version & 0x0f) == CALIBRATION_VERSION) return(1);
if((Calibration.Version & 0x0F) == CALIBRATION_VERSION) return(1);
}
return(0);
}
338,7 → 359,7
{
u8 msg[64];
static u8 speak = 0;
static s16 Xmin = 0, Xmax = 0, Ymin = 0, Ymax = 0, Zmin = 0, Zmax = 0, Zmin2 = 0, Zmax2 = 0;
static s16 Xmin = 0, Xmax = 0, Ymin = 0, Ymax = 0, Zmin = 0, Zmax = 0, Zmin2 = 0, Zmax2 = 0;;
static s16 X = 0, Y = 0, Z = 0;
static u8 OldCalState = 0;
s16 MinCalibration = 450;
359,20 → 380,21
Ymax = -10000;
Zmin = 10000;
Zmax = -10000;
speak = 1;
if(Compass_CalState != OldCalState) // avoid continously writing of eeprom!
speak = 1;
if(Compass_CalState != OldCalState) // only once per state
{
UART1_PutString("\r\nStarting compass calibration");
if(I2C_CompassPort == I2C_EXTERN_0)
{
if(!ExtCompassOrientation) ExtCompassOrientation = GetExtCompassOrientation();
UART1_PutString(" - External sensor ");
sprintf(msg, "with orientation: %d ",ExtCompassOrientation);
UART1_PutString(msg);
}
else UART1_PutString(" - Internal sensor ");
}
UART1_PutString("\r\nStarting compass calibration");
if(Compass_I2CPort == NCMAG_PORT_EXTERN)
{
if(!NCMAG_Orientation) NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
UART1_PutString(" - External sensor ");
sprintf(msg, "with orientation: %d ", NCMAG_Orientation);
UART1_PutString(msg);
}
else UART1_PutString(" - Internal sensor ");
}
break;
case 2: // 2nd step of calibration
// find Min and Max of the X- and Y-Sensors during rotation in the horizontal plane
if(X < Xmin) { Xmin = X; BeepTime = 20;}
379,9 → 401,8
else if(X > Xmax) { Xmax = X; BeepTime = 20;}
if(Y < Ymin) { Ymin = Y; BeepTime = 60;}
else if(Y > Ymax) { Ymax = Y; BeepTime = 60;}
if(Z < Zmin) { Zmin = Z; } // silent
if(Z < Zmin) { Zmin = Z; } // silent
else if(Z > Zmax) { Zmax = Z; }
 
if(speak) SpeakHoTT = SPEAK_CALIBRATE; speak = 0;
break;
 
392,14 → 413,12
 
case 4:
// find Min and Max of the Z-Sensor
if(Z < Zmin2) { Zmin2 = Z; BeepTime = 80;}
else if(Z > Zmax2) { Zmax2 = Z; BeepTime = 80;}
if(X < Xmin) { Xmin = X; BeepTime = 20;}
else if(X > Xmax) { Xmax = X; BeepTime = 20;}
if(Z < Zmin2) { Zmin2 = Z; BeepTime = 80;}
else if(Z > Zmax2) { Zmax2 = Z; BeepTime = 80;}
if(X < Xmin) { Xmin = X; BeepTime = 20;}
else if(X > Xmax) { Xmax = X; BeepTime = 20;}
if(Y < Ymin) { Ymin = Y; BeepTime = 60;}
else if(Y > Ymax) { Ymax = Y; BeepTime = 60;}
 
if(speak) SpeakHoTT = SPEAK_CALIBRATE; speak = 0;
break;
410,27 → 429,26
switch(NCMAG_SensorType)
{
case TYPE_HMC5843:
UART1_PutString("\r\nFinished: HMC5843 calibration\n\r");
MinCalibration = HMC5843_CALIBRATION_RANGE;
break;
UART1_PutString("\r\nFinished: HMC5843 calibration\n\r");
MinCalibration = HMC5843_CALIBRATION_RANGE;
break;
 
case TYPE_LSM303DLH:
case TYPE_LSM303DLM:
UART1_PutString("\r\nFinished: LSM303 calibration\n\r");
MinCalibration = LSM303_CALIBRATION_RANGE;
break;
UART1_PutString("\r\nFinished: LSM303 calibration\n\r");
MinCalibration = LSM303_CALIBRATION_RANGE;
break;
}
if(EarthMagneticStrengthTheoretic)
{
MinCalibration = (MinCalibration * EarthMagneticStrengthTheoretic) / 50;
sprintf(msg, "Earth field on your location should be: %iuT\r\n",EarthMagneticStrengthTheoretic);
UART1_PutString(msg);
}
{
MinCalibration = (MinCalibration * EarthMagneticStrengthTheoretic) / 50;
sprintf(msg, "Earth field on your location should be: %iuT\r\n",EarthMagneticStrengthTheoretic);
UART1_PutString(msg);
}
else UART1_PutString("without GPS\n\r");
 
if(Zmin2 < Zmin) { Zmin = Zmin2; }
else if(Zmax2 > Zmax) { Zmax = Zmax2; }
 
if(Zmin2 < Zmin) Zmin = Zmin2;
if(Zmax2 > Zmax) Zmax = Zmax2;
Calibration.MagX.Range = Xmax - Xmin;
Calibration.MagX.Offset = (Xmin + Xmax) / 2;
Calibration.MagY.Range = Ymax - Ymin;
439,7 → 457,7
Calibration.MagZ.Offset = (Zmin + Zmax) / 2;
if((Calibration.MagX.Range > MinCalibration) && (Calibration.MagY.Range > MinCalibration) && (Calibration.MagZ.Range > MinCalibration))
{
NCMAG_IsCalibrated = NCMag_CalibrationWrite(I2C_CompassPort);
NCMAG_IsCalibrated = NCMag_CalibrationWrite(Compass_I2CPort);
BeepTime = 2500;
UART1_PutString("\r\n-> Calibration okay <-\n\r");
SpeakHoTT = SPEAK_MIKROKOPTER;
454,7 → 472,7
UART1_PutString("\r\n");
 
// restore old calibration data from eeprom
NCMAG_IsCalibrated = NCMag_CalibrationRead(I2C_CompassPort);
NCMAG_IsCalibrated = NCMag_CalibrationRead(Compass_I2CPort);
}
sprintf(msg, "X: (%i - %i = %i)\r\n",Xmax,Xmin,Xmax - Xmin);
UART1_PutString(msg);
515,36 → 533,38
if(NCMAG_SensorType == TYPE_LSM303DLM) Y = raw; // here Z and Y are exchanged
else Z = raw;
}
switch(ExtCompassOrientation)
// correct compass orientation
switch(NCMAG_Orientation)
{
case 0:
case 1:
default:
case 0:
case 1:
default:
// 1:1 Mapping
MagRawVector.X = X;
MagRawVector.Y = Y;
MagRawVector.Z = Z;
break;
case 2:
case 2:
MagRawVector.X = -X;
MagRawVector.Y = Y;
MagRawVector.Z = -Z;
break;
case 3:
case 3:
MagRawVector.X = -Z;
MagRawVector.Y = Y;
MagRawVector.Z = X;
break;
case 4:
case 4:
MagRawVector.X = Z;
MagRawVector.Y = Y;
MagRawVector.Z = -X;
break;
case 5:
case 5:
MagRawVector.X = X;
MagRawVector.Y = -Z;
MagRawVector.Z = Y;
break;
case 6:
case 6:
MagRawVector.X = -X;
MagRawVector.Y = -Z;
MagRawVector.Z = -Y;
569,36 → 589,15
}
// rx data handler for acceleration raw data
void NCMAG_UpdateAccVector(u8* pRxBuffer, u8 RxBufferSize)
{ // if number of byte are matching
{ // if number of bytes are matching
if(RxBufferSize == sizeof(AccRawVector) )
{
{
// copy from I2C buffer
memcpy((u8*)&AccRawVector, pRxBuffer,sizeof(AccRawVector));
// scale and update Acc Vector, at the moment simply 1:1
memcpy((u8*)&AccVector, (u8*)&AccRawVector,sizeof(AccRawVector));
}
}
 
u8 GetExtCompassOrientation(void)
{
if(I2C_CompassPort != I2C_EXTERN_0) return(0);
 
if((abs(FromFlightCtrl.AngleNick) > 300) || (abs(FromFlightCtrl.AngleRoll) > 300))
{
// UART1_PutString("\r\nTilted");
return(0);
}
if(AccRawVector.Z > 3300) return(1); // Flach - Bestückung oben - Pfeil nach vorn
else
if(AccRawVector.Z < -3300) return(2); // Flach - Bestückung unten - Pfeil nach vorn
else
if(AccRawVector.X > 3300) return(3); // Flach - Bestückung Links - Pfeil nach vorn
else
if(AccRawVector.X < -3300) return(4); // Flach - Bestückung rechts - Pfeil nach vorn
else
if(AccRawVector.Y > 3300) return(5); // Stehend - Pfeil nach oben - 'front' nach vorn
else
if(AccRawVector.Y < -3300) return(6); // Stehend - Pfeil nach unten - 'front' nach vorn
return(0);
}
 
// rx data handler for reading magnetic sensor configuration
void NCMAG_UpdateMagConfig(u8* pRxBuffer, u8 RxBufferSize)
{ // if number of byte are matching
617,23 → 616,50
}
//----------------------------------------------------------------------
 
u8 NCMAG_GetOrientationFromAcc(void)
{
// only if external compass connected
if(Compass_I2CPort != NCMAG_PORT_EXTERN) return(0);
// MK must not be tilted
if((abs(FromFlightCtrl.AngleNick) > 300) || (abs(FromFlightCtrl.AngleRoll) > 300))
{
// UART1_PutString("\r\nTilted");
return(0);
}
// select orientation
if(AccRawVector.Z > 3300) return(1); // Flach - Bestückung oben - Pfeil nach vorn
else
if(AccRawVector.Z < -3300) return(2); // Flach - Bestückung unten - Pfeil nach vorn
else
if(AccRawVector.X > 3300) return(3); // Flach - Bestückung Links - Pfeil nach vorn
else
if(AccRawVector.X < -3300) return(4); // Flach - Bestückung rechts - Pfeil nach vorn
else
if(AccRawVector.Y > 3300) return(5); // Stehend - Pfeil nach oben - 'front' nach vorn
else
if(AccRawVector.Y < -3300) return(6); // Stehend - Pfeil nach unten - 'front' nach vorn
return(0);
}
 
// ---------------------------------------------------------------------
u8 NCMAG_SetMagConfig(void)
{
u8 retval = 0;
 
// try to catch the i2c buffer within 100 ms timeout
if(I2C_LockBufferFunc(100))
if(I2CBus_LockBuffer(Compass_I2CPort, 100))
{
u8 TxBytes = 0;
I2C_BufferPnt[TxBytes++] = REG_MAG_CRA;
memcpy((u8*)(&I2C_BufferPnt[TxBytes]), (u8*)&MagConfig, sizeof(MagConfig));
u8 TxData[sizeof(MagConfig) + 3];
TxData[TxBytes++] = REG_MAG_CRA;
memcpy(&TxData[TxBytes], (u8*)&MagConfig, sizeof(MagConfig));
TxBytes += sizeof(MagConfig);
if(I2C_TransmissionFunc(MAG_SLAVE_ADDRESS, TxBytes, 0, 0))
if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, 0, 0))
{
if(I2C_WaitForEndOfTransmissionFunc(100))
if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
{
if(*I2C_ErrorPnt == I2C_ERROR_NONE) retval = 1;
if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
}
}
}
645,15 → 671,16
{
u8 retval = 0;
// try to catch the i2c buffer within 100 ms timeout
if(I2C_LockBufferFunc(100))
if(I2CBus_LockBuffer(Compass_I2CPort, 100))
{
u8 TxBytes = 0;
I2C_BufferPnt[TxBytes++] = REG_MAG_CRA;
if(I2C_TransmissionFunc(MAG_SLAVE_ADDRESS, TxBytes, &NCMAG_UpdateMagConfig, sizeof(MagConfig)))
u8 TxData[3];
TxData[TxBytes++] = REG_MAG_CRA;
if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateMagConfig, sizeof(MagConfig)))
{
if(I2C_WaitForEndOfTransmissionFunc(100))
if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
{
if(*I2C_ErrorPnt == I2C_ERROR_NONE) retval = 1;
if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
}
}
}
664,18 → 691,19
u8 NCMAG_SetAccConfig(void)
{
u8 retval = 0;
// try to catch the i2c buffer within 100 ms timeout
if(I2C_LockBufferFunc(50))
// try to catch the i2c buffer within 50 ms timeout
if(I2CBus_LockBuffer(Compass_I2CPort, 50))
{
u8 TxBytes = 0;
I2C_BufferPnt[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
memcpy((u8*)(&I2C_BufferPnt[TxBytes]), (u8*)&AccConfig, sizeof(AccConfig));
u8 TxData[sizeof(AccConfig) + 3];
TxData[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
memcpy(&TxData[TxBytes], (u8*)&AccConfig, sizeof(AccConfig));
TxBytes += sizeof(AccConfig);
if(I2C_TransmissionFunc(ACC_SLAVE_ADDRESS, TxBytes, 0, 0))
if(I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, 0, 0))
{
if(I2C_WaitForEndOfTransmissionFunc(50))
if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 50))
{
if(*I2C_ErrorPnt == I2C_ERROR_NONE) retval = 1;
if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
}
}
}
687,15 → 715,16
{
u8 retval = 0;
// try to catch the i2c buffer within 100 ms timeout
if(I2C_LockBufferFunc(100))
if(I2CBus_LockBuffer(Compass_I2CPort, 100))
{
u8 TxBytes = 0;
I2C_BufferPnt[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
if(I2C_TransmissionFunc(ACC_SLAVE_ADDRESS, TxBytes, &NCMAG_UpdateAccConfig, sizeof(AccConfig)))
u8 TxData[3];
TxData[TxBytes++] = REG_ACC_CTRL1|REG_ACC_MASK_AUTOINCREMENT;
if(I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateAccConfig, sizeof(AccConfig)))
{
if(I2C_WaitForEndOfTransmissionFunc(100))
if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
{
if(*I2C_ErrorPnt == I2C_ERROR_NONE) retval = 1;
if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
}
}
}
707,19 → 736,20
{
u8 retval = 0;
// try to catch the i2c buffer within 100 ms timeout
if(I2C_LockBufferFunc(100))
if(I2CBus_LockBuffer(Compass_I2CPort, 100))
{
u16 TxBytes = 0;
u8 TxBytes = 0;
u8 TxData[3];
NCMAG_Identification.A = 0xFF;
NCMAG_Identification.B = 0xFF;
NCMAG_Identification.C = 0xFF;
I2C_BufferPnt[TxBytes++] = REG_MAG_IDA;
TxData[TxBytes++] = REG_MAG_IDA;
// initiate transmission
if(I2C_TransmissionFunc(MAG_SLAVE_ADDRESS, TxBytes, &NCMAG_UpdateIdentification, sizeof(NCMAG_Identification)))
if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateIdentification, sizeof(NCMAG_Identification)))
{
if(I2C_WaitForEndOfTransmissionFunc(100))
if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
{
if(*I2C_ErrorPnt == I2C_ERROR_NONE) retval = 1;
if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
}
}
}
730,17 → 760,18
{
u8 retval = 0;
// try to catch the i2c buffer within 100 ms timeout
if(I2C_LockBufferFunc(100))
if(I2CBus_LockBuffer(Compass_I2CPort, 100))
{
u16 TxBytes = 0;
u8 TxBytes = 0;
u8 TxData[3];
NCMAG_Identification2.Sub = 0xFF;
I2C_BufferPnt[TxBytes++] = REG_MAG_IDF;
TxData[TxBytes++] = REG_MAG_IDF;
// initiate transmission
if(I2C_TransmissionFunc(MAG_SLAVE_ADDRESS, TxBytes, &NCMAG_UpdateIdentification_Sub, sizeof(NCMAG_Identification2)))
if(I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateIdentification_Sub, sizeof(NCMAG_Identification2)))
{
if(I2C_WaitForEndOfTransmissionFunc(100))
if(I2CBus_WaitForEndOfTransmission(Compass_I2CPort, 100))
{
if(*I2C_ErrorPnt == I2C_ERROR_NONE) retval = 1;
if(I2CBus(Compass_I2CPort)->Error == I2C_ERROR_NONE) retval = 1;
}
}
}
749,16 → 780,17
 
 
// ----------------------------------------------------------------------------------------
void NCMAG_GetMagVector(void)
void NCMAG_GetMagVector(u8 timeout)
{
// try to catch the I2C buffer within 0 ms
if(I2C_LockBufferFunc(5))
// try to catch the I2C buffer within timeout ms
if(I2CBus_LockBuffer(Compass_I2CPort, timeout))
{
u16 TxBytes = 0;
u8 TxBytes = 0;
u8 TxData[3];
// set register pointer
I2C_BufferPnt[TxBytes++] = REG_MAG_DATAX_MSB;
TxData[TxBytes++] = REG_MAG_DATAX_MSB;
// initiate transmission
I2C_TransmissionFunc(MAG_SLAVE_ADDRESS, TxBytes, &NCMAG_UpdateMagVector, sizeof(MagVector));
I2CBus_Transmission(Compass_I2CPort, MAG_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateMagVector, sizeof(MagVector));
}
}
 
765,22 → 797,20
//----------------------------------------------------------------
void NCMAG_GetAccVector(u8 timeout)
{
// try to catch the I2C buffer within 0 ms
if(I2C_LockBufferFunc(timeout))
// try to catch the I2C buffer within timeout ms
if(I2CBus_LockBuffer(Compass_I2CPort, timeout))
{
u16 TxBytes = 0;
u8 TxBytes = 0;
u8 TxData[3];
// set register pointer
I2C_BufferPnt[TxBytes++] = REG_ACC_X_LSB|REG_ACC_MASK_AUTOINCREMENT;
TxData[TxBytes++] = REG_ACC_X_LSB|REG_ACC_MASK_AUTOINCREMENT;
// initiate transmission
I2C_TransmissionFunc(ACC_SLAVE_ADDRESS, TxBytes, &NCMAG_UpdateAccVector, sizeof(AccRawVector));
//DebugOut.Analog[16] = AccRawVector.X;
//DebugOut.Analog[17] = AccRawVector.Y;
//DebugOut.Analog[18] = AccRawVector.Z;
I2CBus_Transmission(Compass_I2CPort, ACC_SLAVE_ADDRESS, TxData, TxBytes, &NCMAG_UpdateAccVector, sizeof(AccRawVector));
}
}
 
//----------------------------------------------------------------
u8 InitNC_MagnetSensor(void)
u8 NCMAG_ConfigureSensor(void)
{
u8 crb_gain, cra_rate;
 
824,10 → 854,10
static u32 TimerUpdate = 0;
static s8 send_config = 0;
u32 delay = 20;
if(init) TimerUpdate = SetDelay(10);
 
// todo State Handling for both busses !!
if((I2C1_State == I2C_STATE_OFF) || (I2C_CompassPort == 0 && I2C0_State == I2C_STATE_OFF)/* || !NCMAG_Present*/ )
if( (I2CBus(Compass_I2CPort)->State == I2C_STATE_UNDEF) /*|| !NCMAG_Present*/ )
{
Compass_Heading = -1;
DebugOut.Analog[14]++; // count I2C error
834,13 → 864,13
TimerUpdate = SetDelay(10);
return;
}
if(CheckDelay(TimerUpdate))// && I2C0_State == I2C_STATE_IDLE && I2C1_State == I2C_STATE_IDLE)
if(CheckDelay(TimerUpdate))
{
if(Compass_Heading != -1) send_config = 0; // no re-configuration if value is valid
if(++send_config == 25) // 500ms
{
send_config = -25; // next try after 1 second
InitNC_MagnetSensor();
NCMAG_ConfigureSensor();
TimerUpdate = SetDelay(20); // back into the old time-slot
}
else
853,24 → 883,26
// in case of LSM303 type
switch(NCMAG_SensorType)
{
case TYPE_HMC5843:
NCMAG_GetMagVector();
delay = 20;
case TYPE_HMC5843:
delay = 20; // next cycle after 20 ms
NCMAG_GetMagVector(5);
break;
case TYPE_LSM303DLH:
case TYPE_LSM303DLM:
delay = 20;
//delay = 2;
if(s-- || (I2C_CompassPort == I2C_INTERN_1)) NCMAG_GetMagVector();
else
{
if(AccRawVector.X + AccRawVector.Y + AccRawVector.Z == 0) NCMAG_Init_ACCSensor();
NCMAG_GetAccVector(5);
delay = 10;
s = 40; // about 0,8 sec
};
if(!s) delay = 10; // ACC-Reading in the next step after 10ms
//if(!s) delay = 2; // ACC-Reading in the next step after 10ms
if(s-- || (Compass_I2CPort == NCMAG_PORT_INTERN))
{
delay = 20; // next cycle after 20 ms
NCMAG_GetMagVector(5);
}
else // having an external compass, read every 50th cycle the ACC vec
{ // try to initialize if no data are there
if((AccRawVector.X + AccRawVector.Y + AccRawVector.Z) == 0) NCMAG_Init_ACCSensor();
// get new data
NCMAG_GetAccVector(5);
delay = 10; // next cycle after 10 ms
s = 40; //reset downconter about 0,8 sec
}
break;
}
if(send_config == 24) TimerUpdate = SetDelay(15); // next event is the re-configuration
935,7 → 967,7
#define AVERAGE 20
for(i = 0; i<AVERAGE; i++)
{
NCMAG_GetMagVector();
NCMAG_GetMagVector(5);
time = SetDelay(20);
while(!CheckDelay(time));
XMax += MagRawVector.X;
951,7 → 983,7
// averaging
for(i = 0; i < AVERAGE; i++)
{
NCMAG_GetMagVector();
NCMAG_GetMagVector(5);
time = SetDelay(20);
while(!CheckDelay(time));
XMin += MagRawVector.X;
993,178 → 1025,191
}
 
 
//----------------------------------------------------------------
void NCMAG_SelectI2CBus(u8 busno)
{
if (busno == 0)
{
I2C_WaitForEndOfTransmissionFunc = &I2C0_WaitForEndOfTransmission;
I2C_LockBufferFunc = &I2C0_LockBuffer;
I2C_TransmissionFunc = &I2C0_Transmission;
I2C_BufferPnt = I2C0_Buffer;
I2C_ErrorPnt = &I2C0_Error;
}
else
{
I2C_WaitForEndOfTransmissionFunc = &I2C1_WaitForEndOfTransmission;
I2C_LockBufferFunc = &I2C1_LockBuffer;
I2C_TransmissionFunc = &I2C1_Transmission;
I2C_BufferPnt = I2C1_Buffer;
I2C_ErrorPnt = &I2C1_Error;
}
void NCMAG_CheckOrientation(void)
{ // only for external sensor
if(Compass_I2CPort == NCMAG_PORT_EXTERN)
{
NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
if(NCMAG_Orientation != (Calibration.Version>>4)) NCMAG_IsCalibrated = 0;
else NCMAG_IsCalibrated = 1;
}
}
 
//----------------------------------------------------------------
u8 NCMAG_Init(void)
{
u8 msg[64];
u8 retval = 0;
u8 repeat = 0;
 
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Search external sensor
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I2C_CompassPort = I2C_EXTERN_0;
NCMAG_SelectI2CBus(I2C_CompassPort);
 
// get id bytes
retval = 0;
for(repeat = 0; repeat < 5; repeat++)
MagRawVector.X = 0;
MagRawVector.Y = 0;
MagRawVector.Z = 0;
AccRawVector.X = 0;
AccRawVector.Y = 0;
AccRawVector.Z = 0;
if(NCMAG_Present) // do only short init ! , full init was called before
{
// retval = NCMAG_GetIdentification();
retval = NCMAG_GetAccConfig(); // only the sensor with ACC is supported
if(retval) break; // break loop on success
UART1_PutString("_");
}
//retval = 1;
if(!retval)
{
UART1_PutString(" internal sensor");
I2C_CompassPort = I2C_INTERN_1;
NCMAG_SelectI2CBus(I2C_CompassPort);
// reset I2C Bus
I2CBus_Deinit(Compass_I2CPort);
I2CBus_Init(Compass_I2CPort);
// try to reconfigure senor
NCMAG_ConfigureSensor();
NCMAG_Update(1);
}
else
else // full init
{
UART1_PutString(" external sensor ");
NCMAG_Init_ACCSensor();
u8 msg[64];
u8 retval = 0;
u8 repeat = 0;
//--------------------------------------------
// search external sensor first
//--------------------------------------------
Compass_I2CPort = NCMAG_PORT_EXTERN;
// get id bytes
retval = 0;
for(repeat = 0; repeat < 5; repeat++)
{
//retval = NCMAG_GetIdentification();
retval = NCMAG_GetAccConfig(); // only the external sensor with ACC is supported
if(retval) break; // break loop on success
UART1_PutString("_");
}
// Extenal sensor not found?
if(!retval)
{
// search internal sensor afterwards
UART1_PutString(" internal sensor");
Compass_I2CPort = NCMAG_PORT_INTERN;
NCMAG_Orientation = 0;
}
else
{
UART1_PutString(" external sensor ");
 
for(repeat = 0; repeat < 100; repeat++)
{
NCMAG_GetAccVector(10); // only the sensor with ACC is supported
ExtCompassOrientation = GetExtCompassOrientation();
if(ExtCompassOrientation && (ExtCompassOrientation == Calibration.Version / 16)) break;
//UART1_Putchar('-');
}
//DebugOut.Analog[19] = repeat;
 
if(!ExtCompassOrientation) UART1_PutString(" (Orientation unknown!)");
else
{
NCMag_CalibrationRead(I2C_CompassPort);
sprintf(msg, "with orientation: %d ",ExtCompassOrientation );
UART1_PutString(msg);
if(ExtCompassOrientation != Calibration.Version / 16)
{
sprintf(msg, "\n\r! Warning: calibrated orientation was %d !",Calibration.Version / 16);
UART1_PutString(msg);
}
else UART1_PutString("ok ");
}
 
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
NCMAG_Present = 0;
NCMAG_SensorType = TYPE_HMC5843; // assuming having an HMC5843
// polling for LSM302DLH/DLM option by ACC address ack
for(repeat = 0; repeat < 3; repeat++)
{
retval = NCMAG_GetAccConfig();
if(retval) break; // break loop on success
}
if(retval)
{
// initialize ACC sensor
NCMAG_Init_ACCSensor();
 
NCMAG_SensorType = TYPE_LSM303DLH;
// polling of sub identification
for(repeat = 0; repeat < 12; repeat++)
// initialize ACC sensor of the IC
NCMAG_Init_ACCSensor();
// try to get orientation by acc sensor values
for(repeat = 0; repeat < 100; repeat++)
{
NCMAG_GetAccVector(10); // only the sensor with ACC is supported
NCMAG_Orientation = NCMAG_GetOrientationFromAcc();
if(NCMAG_Orientation) break;
}
// check orientation result
if(NCMAG_Orientation)
{
sprintf(msg, "with orientation: %d ", NCMAG_Orientation );
UART1_PutString(msg);
}
else
{
UART1_PutString(" (Orientation unknown!)");
}
}
//-------------------------------------------
NCMAG_Present = 0;
NCMAG_SensorType = TYPE_HMC5843; // assuming having an HMC5843
// polling for LSM302DLH/DLM option by ACC address ack
repeat = 0;
for(repeat = 0; repeat < 3; repeat++)
{
retval = NCMAG_GetIdentification_Sub();
retval = NCMAG_GetAccConfig();
if(retval) break; // break loop on success
}
if(retval)
{
if(NCMAG_Identification2.Sub == MAG_IDF_LSM303DLM) NCMAG_SensorType = TYPE_LSM303DLM;
}
}
// get id bytes
for(repeat = 0; repeat < 3; repeat++)
{
retval = NCMAG_GetIdentification();
if(retval) break; // break loop on success
}
 
// if we got an answer to id request
if(retval)
{
u8 n1[] = "\n\r HMC5843";
u8 n2[] = "\n\r LSM303DLH";
u8 n3[] = "\n\r LSM303DLM";
u8* pn = n1;
switch(NCMAG_SensorType)
// initialize ACC sensor
NCMAG_Init_ACCSensor();
NCMAG_SensorType = TYPE_LSM303DLH;
// polling of sub identification
repeat = 0;
for(repeat = 0; repeat < 12; repeat++)
{
retval = NCMAG_GetIdentification_Sub();
if(retval) break; // break loop on success
}
if(retval)
{
if(NCMAG_Identification2.Sub == MAG_IDF_LSM303DLM) NCMAG_SensorType = TYPE_LSM303DLM;
}
}
// get id bytes
retval = 0;
for(repeat = 0; repeat < 3; repeat++)
{
case TYPE_HMC5843:
pn = n1;
break;
case TYPE_LSM303DLH:
pn = n2;
break;
case TYPE_LSM303DLM:
pn = n3;
break;
retval = NCMAG_GetIdentification();
if(retval) break; // break loop on success
}
 
sprintf(msg, " %s ID 0x%02x/%02x/%02x-%02x", pn, NCMAG_Identification.A, NCMAG_Identification.B, NCMAG_Identification.C,NCMAG_Identification2.Sub);
UART1_PutString(msg);
if ( (NCMAG_Identification.A == MAG_IDA)
&& (NCMAG_Identification.B == MAG_IDB)
&& (NCMAG_Identification.C == MAG_IDC))
// if we got an answer to id request
if(retval)
{
NCMAG_Present = 1;
 
if(EEPROM_Init())
u8 n1[] = "\n\r HMC5843";
u8 n2[] = "\n\r LSM303DLH";
u8 n3[] = "\n\r LSM303DLM";
u8* pn = n1;
switch(NCMAG_SensorType)
{
NCMAG_IsCalibrated = NCMag_CalibrationRead(I2C_CompassPort);
if(!NCMAG_IsCalibrated) UART1_PutString("\r\n Not calibrated!");
case TYPE_HMC5843:
pn = n1;
break;
case TYPE_LSM303DLH:
pn = n2;
break;
case TYPE_LSM303DLM:
pn = n3;
break;
}
else UART1_PutString("\r\n EEPROM data not available!!!!!!!!!!!!!!!");
// perform self test
if(!NCMAG_SelfTest())
{
UART1_PutString("\r\n Selftest failed!!!!!!!!!!!!!!!!!!!!\r\n");
sprintf(msg, " %s ID 0x%02x/%02x/%02x-%02x", pn, NCMAG_Identification.A, NCMAG_Identification.B, NCMAG_Identification.C,NCMAG_Identification2.Sub);
UART1_PutString(msg);
if ( (NCMAG_Identification.A == MAG_IDA)
&& (NCMAG_Identification.B == MAG_IDB)
&& (NCMAG_Identification.C == MAG_IDC))
{
NCMAG_Present = 1;
if(EEPROM_Init())
{
NCMAG_IsCalibrated = NCMag_CalibrationRead(Compass_I2CPort);
if(!NCMAG_IsCalibrated) UART1_PutString("\r\n Not calibrated!");
else // valid calibration data in EEPROM
{ // check current orientation
if(NCMAG_Orientation != Calibration.Version >> 4)
{
sprintf(msg, "\n\r! Warning: calibrated orientation was %d !",Calibration.Version >> 4);
UART1_PutString(msg);
}
else UART1_PutString("ok ");
}
}
else UART1_PutString("\r\n EEPROM data not available!!!!!!!!!!!!!!!");
// perform self test
if(!NCMAG_SelfTest())
{
UART1_PutString("\r\n Selftest failed!!!!!!!!!!!!!!!!!!!!\r\n");
LED_RED_ON;
//NCMAG_IsCalibrated = 0;
}
else UART1_PutString("\r\n Selftest ok");
// initialize magnetic sensor configuration
NCMAG_ConfigureSensor();
}
else
{
UART1_PutString("\n\r Not compatible!");
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_INCOMPATIBLE;
LED_RED_ON;
// NCMAG_IsCalibrated = 0;
}
else UART1_PutString("\r\n Selftest ok");
 
// initialize magnetic sensor configuration
InitNC_MagnetSensor();
}
}
else
else // nothing found
{
UART1_PutString("\n\r Not compatible!");
UART_VersionInfo.HardwareError[0] |= NC_ERROR0_COMPASS_INCOMPATIBLE;
LED_RED_ON;
NCMAG_SensorType = TYPE_NONE;
UART1_PutString("not found!");
}
}
else // nothing found
{
NCMAG_SensorType = TYPE_NONE;
UART1_PutString("not found!");
}
return(NCMAG_Present);
}
 
/trunk/ncmag.h
2,56 → 2,19
#define __NCMAG_H
 
#include "compass.h"
#include "i2c1.h"
#include "i2c.h"
 
extern s16vec_t ACC_Vector;
extern volatile s16vec_t MagRawVector;
extern volatile s16vec_t AccRawVector;
#define NCMAG_PORT_EXTERN I2C0
#define NCMAG_PORT_INTERN I2C1
 
#define EEPROM_ADR_MAG_CALIBRATION_INTERN 50 // two calibrtion sets for extern and intern sensor
#define EEPROM_ADR_MAG_CALIBRATION_EXTERN 70
 
#define CALIBRATION_VERSION 1
#define MAG_CALIBRATION_COMPATIBLE 0xA2
 
#define NCMAG_MIN_RAWVALUE -2047
#define NCMAG_MAX_RAWVALUE 2047
#define NCMAG_INVALID_DATA -4096
 
typedef struct
{
s16 Range;
s16 Offset;
} __attribute__((packed)) Scaling_t;
 
typedef struct
{
Scaling_t MagX;
Scaling_t MagY;
Scaling_t MagZ;
u8 Version;
u8 crc;
} __attribute__((packed)) Calibration_t;
 
extern Calibration_t Calibration; // calibration data in RAM
 
#define I2C_EXTERN_0 0
#define I2C_INTERN_1 1
 
extern u8 NCMAG_Init(void);
extern void NCMAG_Update(u8);
extern u8 NCMAG_Present;
extern u8 NCMAG_IsCalibrated;
extern u8 I2C_CompassPort;
extern u8 ExtCompassOrientation;
extern u8 NCMAG_Orientation;
 
u8 NCMAG_Init(void);
void NCMAG_Update(u8 init);
u8 NCMAG_GetOrientationFromAcc(void);
void NCMAG_CheckOrientation(void);
 
extern u8 *I2C_BufferPnt;
extern u8 *I2C_ErrorPnt;
 
typedef u8 (*I2C_TransmissionFunc_t) (u8 SlaveAddr, u8 TxBytes, I2C_pRxHandler_t pRxHandler, u8 RxBytes);
typedef u8 (*I2C_LockBufferFunc_t) (u32 timeout);
typedef u8 (*I2C_WaitForEndOfTransmissionFunc_t) (u32 timeout);
 
#endif // __NCMAG_H
 
/trunk/settings.c
92,7 → 92,7
{PID_MIN_EVENT_TIME , "MIN_EVENT_TIME \0" ,"minimum time of the Waypoint-Event value (seconds) ", 1, 2, 2, 0, 600}, // in seconds
{PID_WP_ACCELERATE , "WAYPOINT DYNAMIC\0" ,"dynamic for flying waypoints in percent (0-200) ", 1, 100, 100, 0, 255}, // in percent or Poti
{PID_WP_WAIT_FOR_LED , "WAIT_FOR_OUT1 \0" ,"Wait on Waypoint until Out-Pattern is finished (1=on 0=off) ", 1, 1, 1, 0, 1},
{PID_SEND_NMEA , "NMEA_INTERVAL \0" ,"NMEA Output interval in ms (0 = disabled) ", 1, 0, 0, 0, 60000}, // the log interval for GPX logging, 0 = off
{PID_SEND_NMEA , "NMEA_INTERVAL \0" ,"NMEA Output interval in ms (0 = disabled) ", 1, 0, 0, 0, 60000}, // the log interval for NMEA output, 0 = off
{PID_GPS_AUTOCONFIG , "GPSAUTOCONFIG \0" ,"GPS configmode (0 = off, 1 = on) ", 1, 1, 1, 0, 1}
};
 
/trunk/spi_slave.c
56,6 → 56,7
 
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "91x_lib.h"
#include "led.h"
#include "gps.h"
66,11 → 67,8
#include "timer2.h"
#include "config.h"
#include "main.h"
#include "compass.h"
#include "params.h"
#include "stdlib.h"
#include "settings.h"
#include "ncmag.h"
 
#define SPI_RXSYNCBYTE1 0xAA
#define SPI_RXSYNCBYTE2 0x83
586,34 → 584,34
}
else
{
if(FCCalibActive)
{
if(--FCCalibActive == 0)
{
FC_is_Calibrated = 1;
ExtCompassOrientation = GetExtCompassOrientation();
if(ExtCompassOrientation != Calibration.Version / 16) NCMAG_IsCalibrated = 0;
}
}
if(FCCalibActive)
{
if(--FCCalibActive == 0)
{
FC_is_Calibrated = 1;
Compass_Check();
}
}
}
if(FC.StatusFlags & FC_STATUS_START)
{
if(Compass_Heading != -1) HeadFreeStartAngle = (3600 + Compass_Heading * 10 - GeoMagDec) % 3600; else
HeadFreeStartAngle = GyroCompassCorrected;
}
{
if(Compass_Heading != -1) HeadFreeStartAngle = (3600 + Compass_Heading * 10 - GeoMagDec) % 3600; else
HeadFreeStartAngle = GyroCompassCorrected;
}
 
if((Parameter.ExtraConfig & CFG_TEACHABLE_CAREFREE))
{
if(!(FC.StatusFlags2 & FC_STATUS2_CAREFREE)) // CF ist jetzt ausgeschaltet -> neue Richtung lernen
{
if((NaviData.HomePositionDeviation.Distance > 200) && (NCFlags & NC_FLAG_GPS_OK)) // nur bei ausreichender Distance -> 20m
{
HeadFreeStartAngle = (10 * NaviData.HomePositionDeviation.Bearing + 1800 + 3600 - Parameter.OrientationAngle * 150) % 3600; // in 0.1°
}
else // Ansonsten die aktuelle Richtung übernehmen
HeadFreeStartAngle = GyroCompassCorrected; // in 0.1°
if((Parameter.ExtraConfig & CFG_TEACHABLE_CAREFREE))
{
if(!(FC.StatusFlags2 & FC_STATUS2_CAREFREE)) // CF ist jetzt ausgeschaltet -> neue Richtung lernen
{
if((NaviData.HomePositionDeviation.Distance > 200) && (NCFlags & NC_FLAG_GPS_OK)) // nur bei ausreichender Distance -> 20m
{
HeadFreeStartAngle = (10 * NaviData.HomePositionDeviation.Bearing + 1800 + 3600 - Parameter.OrientationAngle * 150) % 3600; // in 0.1°
}
else // Ansonsten die aktuelle Richtung übernehmen
HeadFreeStartAngle = GyroCompassCorrected; // in 0.1°
}
}
 
Parameter.ActiveSetting = FromFlightCtrl.Param.Byte[9];
FC.BAT_Voltage = FromFlightCtrl.Param.Byte[10];
DebugOut.Analog[7] = FC.BAT_Voltage;
672,7 → 670,7
CHK_POTI_MM(Parameter.NaviOut1Parameter,FromFlightCtrl.Param.Byte[0],0,255);
if(FromFlightCtrl.Param.Byte[1]) FC.FromFC_SpeakHoTT = FromFlightCtrl.Param.Byte[1]; // will be cleared in the SD-Logging
Parameter.FromFC_LandingSpeed = FromFlightCtrl.Param.Byte[2];
Parameter.ComingHomeAltitude = FromFlightCtrl.Param.Byte[3];
Parameter.ComingHomeAltitude = FromFlightCtrl.Param.Byte[3];
break;
case SPI_FCCMD_STICK:
FC.StickGas = FromFlightCtrl.Param.sByte[0];
741,14 → 739,14
FC.Error[1] |= FromFlightCtrl.Param.Byte[6];
if(FromFlightCtrl.Param.Byte[7] >= 68 && FromFlightCtrl.Param.Byte[7] <= 188)
{
FC.FromFC_DisableDeclination = 1;
FC.FromFC_CompassOffset = 10 * (signed char) ((unsigned char) FromFlightCtrl.Param.Byte[7] - 128);
GeoMagDec = 0;
FC.FromFC_DisableDeclination = 1;
FC.FromFC_CompassOffset = 10 * (s8) (FromFlightCtrl.Param.Byte[7] - 128);
GeoMagDec = 0;
}
else
{
FC.FromFC_DisableDeclination = 0;
FC.FromFC_CompassOffset = 10 * (signed char) FromFlightCtrl.Param.Byte[7];
FC.FromFC_DisableDeclination = 0;
FC.FromFC_CompassOffset = 10 * FromFlightCtrl.Param.sByte[7];
}
Parameter.GlobalConfig = FromFlightCtrl.Param.Byte[8];
Parameter.ExtraConfig = FromFlightCtrl.Param.Byte[9];
818,7 → 816,7
}while (!CheckDelay(timeout));
UART1_PutString(".");
repeat++;
// FCCalibActive = 1;
FCCalibActive = 1;
}while((FC_Version.Major == 0xFF) && (repeat < 40)); // 40*250ms = 10s
// if we got it
if (FC_Version.Major != 0xFF)
829,4 → 827,16
else UART1_PutString("\n\r not found!");
}
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + extended Current measurement -> 200 = 20A 201 = 21A 255 = 75A (20+55)
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
u16 BL3_Current(u8 who) // in 0,1A
{
if(Motor[who].Current <= 200) return((u16) Motor[who].Current);
else
{
if(Motor_Version[who] & MOTOR_STATE_BL30) return(200 + 10 * (u16) (Motor[who].Current - 200));
else return((u16) Motor[who].Current);
}
}
 
/trunk/spi_slave.h
49,11 → 49,7
extern u8 NC_Wait_for_LED;
extern s16 GyroCompassCorrected;
 
/*extern u8 MotorCurrent[12];
extern u8 MotorTemperature[12];
extern u8 MotorState[12];
extern u8 MotorMaxPwm[12];
*/
 
extern u8 BL_MinOfMaxPWM; // indication if all BL-controllers run on full power
extern u32 FC_I2C_ErrorConter;
extern u8 FromFC_VarioCharacter;
141,14 → 137,13
 
extern Motor_t Motor[12];
 
 
//Motor_Version[12]
#define MOTOR_STATE_NEW_PROTOCOL_MASK 0x01
#define MOTOR_STATE_FAST_MODE 0x02
#define MOTOR_STATE_BL30 0x04 // extended Current measurement -> 200 = 20A 201 = 21A 255 = 75A (20+55)
extern unsigned char Motor_Version[12]; // das kann nicht in die struct, weil der PC die Struktur bekommt
extern u8 Motor_Version[12]; // das kann nicht in die struct, weil der PC die Struktur bekommt
 
 
 
typedef struct
{
u8 Major;
168,5 → 163,6
void SPI0_Init(void);
void SPI0_GetFlightCtrlVersion(void);
void SPI0_UpdateBuffer(void);
u16 BL3_Current(u8 who); // in 0.1A
 
#endif //_SPI_SLAVE_H
/trunk/timer2.c
176,7 → 176,7
TIM2->OC2R += pulselen;
}
IDISABLE;
*/
*/
VIC0->VAR = 0xFF; // write any value to VIC0 Vector address register
}
 
185,7 → 185,7
//----------------------------------------------------------------------------------------------------
void TIMER2_Init(void)
{
/*
/*
GPIO_InitTypeDef GPIO_InitStructure;
TIM_InitTypeDef TIM_InitStructure;
 
248,7 → 248,7
TIM_CounterCmd(TIM2, TIM_START); // start the timer
UART1_PutString("ok\r\n");
*/
*/
}
 
void TIMER2_Deinit(void)
283,4 → 283,4
GPIO_InitStructure.GPIO_Alternate = GPIO_InputAlt1;
GPIO_Init(GPIO6, &GPIO_InitStructure);
}
*/
*/
/trunk/uart1.c
63,8 → 63,7
#include "config.h"
#include "menu.h"
#include "GPS.h"
#include "i2c0.h"
#include "i2c1.h"
#include "i2c.h"
#include "uart0.h"
#include "uart1.h"
#include "uart2.h"
686,70 → 685,71
//http://www.kowoma.de/gps/zusatzerklaerungen/NMEA.htm
void CreateNmeaGGA(void)
{
unsigned char array[200], i = 0, crc = 0, x;
long tmp1, tmp2;
i += sprintf(array, "$GPGGA,");
// +++++++++++++++++++++++++++++++++++++++++++
if(SystemTime.Valid)
{
i += sprintf(&array[i], "%02d%02d%02d.%02d,",SystemTime.Hour,SystemTime.Min,SystemTime.Sec,SystemTime.mSec/10);
}
else
{
i += sprintf(&array[i], ",");
}
// +++++++++++++++++++++++++++++++++++++++++++
if(GPSData.Flags & FLAG_GPSFIXOK)
{
tmp1 = abs(GPSData.Position.Latitude)/10000000L;
i += sprintf(&array[i],"%02d",(int)tmp1);
u8 array[200], i = 0, crc = 0, x;
s32 tmp1, tmp2;
i += sprintf(array, "$GPGGA,");
// +++++++++++++++++++++++++++++++++++++++++++
if(SystemTime.Valid)
{
i += sprintf(&array[i], "%02d%02d%02d.%02d,", SystemTime.Hour, SystemTime.Min, SystemTime.Sec, SystemTime.mSec/10);
}
else
{
i += sprintf(&array[i], ",");
}
// +++++++++++++++++++++++++++++++++++++++++++
if(GPSData.Flags & FLAG_GPSFIXOK)
{
tmp1 = abs(GPSData.Position.Latitude)/10000000L;
i += sprintf(&array[i],"%02d",(s16)tmp1);
 
tmp1 = abs(GPSData.Position.Latitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d",(int)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,",(int)tmp2);
tmp1 = abs(GPSData.Position.Latitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d", (s16)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,", (s16)tmp2);
 
if(GPSData.Position.Latitude >= 0) i += sprintf(&array[i],"N,");
else i += sprintf(&array[i],"S,");
// +++++++++++++++++++++++++++++++++++++++++++
if(GPSData.Position.Latitude >= 0) i += sprintf(&array[i],"N,");
else i += sprintf(&array[i],"S,");
// +++++++++++++++++++++++++++++++++++++++++++
 
tmp1 = abs(GPSData.Position.Longitude)/10000000L;
i += sprintf(&array[i],"%03d",(int)tmp1);
tmp1 = abs(GPSData.Position.Longitude)/10000000L;
i += sprintf(&array[i],"%03d", (s16)tmp1);
 
tmp1 = abs(GPSData.Position.Longitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d",(int)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,",(int)tmp2);
tmp1 = abs(GPSData.Position.Longitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d", (s16)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,", (s16)tmp2);
 
 
if(GPSData.Position.Longitude >= 0) i += sprintf(&array[i],"E,");
else i += sprintf(&array[i],"W,");
i += sprintf(&array[i],"%d,",GPSData.SatFix);
i += sprintf(&array[i],"%d,",GPSData.NumOfSats);
i += sprintf(&array[i],"%d.%d,",GPSData.Position_Accuracy/100,abs(GPSData.Position_Accuracy%100));
// i += sprintf(&array[i],"%d.%d,M,",GPSData.Position.Altitude/1000,abs(GPSData.Position.Altitude%1000)/100);
tmp1 = NaviData.Altimeter / 2; // in dm
i += sprintf(&array[i],"%d.%d,M,",tmp1 / 10,abs(tmp1 % 10));
i += sprintf(&array[i],",,,*");
}
else
{
i += sprintf(&array[i], ",,,,%d,00,99.99,,,,,,*",GPSData.NumOfSats);
}
for(x=1; x<i-1; x++)
{
crc ^= array[x];
}
i += sprintf(&array[i], "%02x%c%c",crc,0x0d,0x0a);
AddSerialData(&UART1_tx_buffer,array,i);
if(GPSData.Position.Longitude >= 0) i += sprintf(&array[i],"E,");
else i += sprintf(&array[i],"W,");
i += sprintf(&array[i],"%d,",GPSData.SatFix);
i += sprintf(&array[i],"%d,",GPSData.NumOfSats);
i += sprintf(&array[i],"%d.%d,",(s16)(GPSData.Position_Accuracy/100),abs(GPSData.Position_Accuracy%100));
// i += sprintf(&array[i],"%d.%d,M,",GPSData.Position.Altitude/1000,abs(GPSData.Position.Altitude%1000)/100);
tmp1 = NaviData.Altimeter / 2; // in dm
i += sprintf(&array[i],"%d.%d,M,",(s16)tmp1 / 10,abs((s16)tmp1 % 10));
i += sprintf(&array[i],",,,*");
}
else
{
i += sprintf(&array[i], ",,,,%d,00,99.99,,,,,,*",GPSData.NumOfSats);
}
for(x = 1; x < i-1; x++)
{
crc ^= array[x];
}
i += sprintf(&array[i], "%02x%c%c",crc,0x0d,0x0a);
AddSerialData(&UART1_tx_buffer,array,i);
 
// +++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++
}
 
//$GPRMC,162614.123,A,5230.5900,N,01322.3900,E,10.0,90.0,131006,1.2,E,A*13
757,144 → 757,144
 
void CreateNmeaRMC(void)
{
unsigned char array[200], i = 0, crc = 0, x;
int tmp_int;
long tmp1, tmp2;
// +++++++++++++++++++++++++++++++++++++++++++
i += sprintf(array, "$GPRMC,");
// +++++++++++++++++++++++++++++++++++++++++++
if(SystemTime.Valid)
{
i += sprintf(&array[i], "%02d%02d%02d.%03d,",SystemTime.Hour,SystemTime.Min,SystemTime.Sec,SystemTime.mSec);
}
else
{
i += sprintf(&array[i], ",");
}
if(GPSData.Flags & FLAG_GPSFIXOK)
{
// +++++++++++++++++++++++++++++++++++++++++++
tmp1 = abs(GPSData.Position.Latitude)/10000000L;
i += sprintf(&array[i],"A,%02d",(int)tmp1); // Status: A = Okay V = Warnung
 
tmp1 = abs(GPSData.Position.Latitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d",(int)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,",(int)tmp2);
if(GPSData.Position.Latitude >= 0) i += sprintf(&array[i],"N,");
else i += sprintf(&array[i],"S,");
// +++++++++++++++++++++++++++++++++++++++++++
tmp1 = abs(GPSData.Position.Longitude)/10000000L;
i += sprintf(&array[i],"%03d",(int)tmp1);
 
tmp1 = abs(GPSData.Position.Longitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d",(int)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,",(int)tmp2);
if(GPSData.Position.Longitude >= 0) i += sprintf(&array[i],"E,");
else i += sprintf(&array[i],"W,");
// +++++++++++++++++++++++++++++++++++++++++++
tmp_int = GPSData.Speed_Ground; // in cm/sek
tmp_int *= 90;
tmp_int /= 463;
i += sprintf(&array[i],"%02d.%d,",tmp_int/10,tmp_int%10); // in Knoten
// +++++++++++++++++++++++++++++++++++++++++++
i += sprintf(&array[i],"%03d.%d,",GyroCompassCorrected/10,GyroCompassCorrected%10);
// +++++++++++++++++++++++++++++++++++++++++++
if(SystemTime.Valid)
{
i += sprintf(&array[i], "%02d%02d%02d,",SystemTime.Day,SystemTime.Month,SystemTime.Year);
}
else
{
i += sprintf(&array[i], ",");
}
// +++++++++++++++++++++++++++++++++++++++++++
i += sprintf(&array[i],"%d.%1d,", abs(GeoMagDec)/10,abs(GeoMagDec)%10);
if(GeoMagDec < 0) i += sprintf(&array[i], "W,"); else i += sprintf(&array[i], "E,");
// +++++++++++++++++++++++++++++++++++++++++++
if(GPSData.Flags & FLAG_DIFFSOLN) i += sprintf(&array[i], "D,");
else i += sprintf(&array[i], "A,");
}
else // kein Satfix
{
i += sprintf(&array[i], "V,,,,,,,,,,N*");
}
// +++++++++++++++++++++++++++++++++++++++++++
// CRC
// +++++++++++++++++++++++++++++++++++++++++++
for(x=1; x<i-1; x++)
{
crc ^= array[x];
}
i += sprintf(&array[i], "%02x%c%c",crc,0x0d,0x0a);
// +++++++++++++++++++++++++++++++++++++++++++
AddSerialData(&UART1_tx_buffer,array,i);
// +++++++++++++++++++++++++++++++++++++++++++
u8 array[200], i = 0, crc = 0, x;
s16 tmp_int;
s32 tmp1, tmp2;
// +++++++++++++++++++++++++++++++++++++++++++
i += sprintf(array, "$GPRMC,");
// +++++++++++++++++++++++++++++++++++++++++++
if(SystemTime.Valid)
{
i += sprintf(&array[i], "%02d%02d%02d.%03d,", SystemTime.Hour, SystemTime.Min, SystemTime.Sec, SystemTime.mSec);
}
else
{
i += sprintf(&array[i], ",");
}
if(GPSData.Flags & FLAG_GPSFIXOK)
{
// +++++++++++++++++++++++++++++++++++++++++++
tmp1 = abs(GPSData.Position.Latitude)/10000000L;
i += sprintf(&array[i],"A,%02d", (s16)tmp1); // Status: A = Okay V = Warnung
tmp1 = abs(GPSData.Position.Latitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d", (s16)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,", (s16)tmp2);
if(GPSData.Position.Latitude >= 0) i += sprintf(&array[i],"N,");
else i += sprintf(&array[i],"S,");
// +++++++++++++++++++++++++++++++++++++++++++
tmp1 = abs(GPSData.Position.Longitude)/10000000L;
i += sprintf(&array[i],"%03d", (s16)tmp1);
tmp1 = abs(GPSData.Position.Longitude)%10000000L;
tmp1 *= 6; // in Minuten
tmp2 = tmp1 / 1000000L;
i += sprintf(&array[i],"%02d", (s16)tmp2);
tmp2 = tmp1 % 1000000L;
tmp2 /= 10; // eine Stelle zu viel
i += sprintf(&array[i],".%05d,", (s16)tmp2);
if(GPSData.Position.Longitude >= 0) i += sprintf(&array[i],"E,");
else i += sprintf(&array[i],"W,");
// +++++++++++++++++++++++++++++++++++++++++++
tmp_int = GPSData.Speed_Ground; // in cm/sek
tmp_int *= 90;
tmp_int /= 463;
i += sprintf(&array[i],"%02d.%d,",tmp_int/10,tmp_int%10); // in Knoten
// +++++++++++++++++++++++++++++++++++++++++++
i += sprintf(&array[i],"%03d.%d,",GyroCompassCorrected/10,GyroCompassCorrected%10);
// +++++++++++++++++++++++++++++++++++++++++++
if(SystemTime.Valid)
{
i += sprintf(&array[i], "%02d%02d%02d,",SystemTime.Day,SystemTime.Month,SystemTime.Year);
}
else
{
i += sprintf(&array[i], ",");
}
// +++++++++++++++++++++++++++++++++++++++++++
i += sprintf(&array[i],"%d.%1d,", abs(GeoMagDec)/10,abs(GeoMagDec)%10);
if(GeoMagDec < 0) i += sprintf(&array[i], "W,"); else i += sprintf(&array[i], "E,");
// +++++++++++++++++++++++++++++++++++++++++++
if(GPSData.Flags & FLAG_DIFFSOLN) i += sprintf(&array[i], "D,");
else i += sprintf(&array[i], "A,");
}
else // kein Satfix
{
i += sprintf(&array[i], "V,,,,,,,,,,N*");
}
// +++++++++++++++++++++++++++++++++++++++++++
// CRC
// +++++++++++++++++++++++++++++++++++++++++++
for(x=1; x<i-1; x++)
{
crc ^= array[x];
}
i += sprintf(&array[i], "%02x%c%c",crc,0x0d,0x0a);
// +++++++++++++++++++++++++++++++++++++++++++
AddSerialData(&UART1_tx_buffer,array,i);
// +++++++++++++++++++++++++++++++++++++++++++
/*
 
GPSData.Flags = (GPSData.Flags & 0xf0) | (UbxSol.Flags & 0x0f); // we take only the lower bits
GPSData.NumOfSats = UbxSol.numSV;
GPSData.SatFix = UbxSol.GPSfix;
GPSData.Position_Accuracy = UbxSol.PAcc;
GPSData.Speed_Accuracy = UbxSol.SAcc;
SetGPSTime(&SystemTime); // update system time
// NAV POSLLH
GPSData.Position.Status = INVALID;
GPSData.Position.Longitude = UbxPosLlh.LON;
GPSData.Position.Latitude = UbxPosLlh.LAT;
GPSData.Position.Altitude = UbxPosLlh.HMSL;
GPSData.Position.Status = NEWDATA;
// NAV VELNED
GPSData.Speed_East = UbxVelNed.VEL_E;
GPSData.Speed_North = UbxVelNed.VEL_N;
GPSData.Speed_Top = -UbxVelNed.VEL_D;
GPSData.Speed_Ground = UbxVelNed.GSpeed;
GPSData.Heading = UbxVelNed.Heading;
SystemTime.Year = 0;
SystemTime.Month = 0;
SystemTime.Day = 0;
SystemTime.Hour = 0;
SystemTime.Min = 0;
SystemTime.Sec = 0;
SystemTime.mSec = 0;
SystemTime.Valid = 0;
GPSData.Flags = (GPSData.Flags & 0xf0) | (UbxSol.Flags & 0x0f); // we take only the lower bits
GPSData.NumOfSats = UbxSol.numSV;
GPSData.SatFix = UbxSol.GPSfix;
GPSData.Position_Accuracy = UbxSol.PAcc;
GPSData.Speed_Accuracy = UbxSol.SAcc;
SetGPSTime(&SystemTime); // update system time
// NAV POSLLH
GPSData.Position.Status = INVALID;
GPSData.Position.Longitude = UbxPosLlh.LON;
GPSData.Position.Latitude = UbxPosLlh.LAT;
GPSData.Position.Altitude = UbxPosLlh.HMSL;
GPSData.Position.Status = NEWDATA;
// NAV VELNED
GPSData.Speed_East = UbxVelNed.VEL_E;
GPSData.Speed_North = UbxVelNed.VEL_N;
GPSData.Speed_Top = -UbxVelNed.VEL_D;
GPSData.Speed_Ground = UbxVelNed.GSpeed;
GPSData.Heading = UbxVelNed.Heading;
SystemTime.Year = 0;
SystemTime.Month = 0;
SystemTime.Day = 0;
SystemTime.Hour = 0;
SystemTime.Min = 0;
SystemTime.Sec = 0;
SystemTime.mSec = 0;
SystemTime.Valid = 0;
FromFlightCtrl.GyroHeading / 10;//NaviData.HomePositionDeviation.Bearing / 2;
if(GPSData.Position.Latitude < 0) ToFlightCtrl.Param.Byte[5] = 1; // 1 = S
else ToFlightCtrl.Param.Byte[5] = 0; // 1 = S
i1 = abs(GPSData.Position.Latitude)/10000000L;
i2 = abs(GPSData.Position.Latitude)%10000000L;
FromFlightCtrl.GyroHeading / 10;//NaviData.HomePositionDeviation.Bearing / 2;
if(GPSData.Position.Latitude < 0) ToFlightCtrl.Param.Byte[5] = 1; // 1 = S
else ToFlightCtrl.Param.Byte[5] = 0; // 1 = S
i1 = abs(GPSData.Position.Latitude)/10000000L;
i2 = abs(GPSData.Position.Latitude)%10000000L;
 
 
 
if(!(NCFlags & NC_FLAG_GPS_OK)) {i1 = 0; i2 = 0;}
i1 *= 100;
i1 += i2 / 100000;
i2 = i2 % 100000;
i2 /= 10;
ToFlightCtrl.Param.Byte[6] = i1 % 256;
ToFlightCtrl.Param.Byte[7] = i1 / 256;
ToFlightCtrl.Param.Byte[8] = i2 % 256;
ToFlightCtrl.Param.Byte[9] = i2 / 256;
break;
case 1:
ToFlightCtrl.Param.Byte[11] = HOTT_GPS_PACKET_ID;
ToFlightCtrl.Param.Byte[0] = 11+3; // index +3, weil bei HoTT V4 3 Bytes eingeschoben wurden
ToFlightCtrl.Param.Byte[1] = 8-1; // how many
//-----------------------------
if(GPSData.Position.Longitude < 0) ToFlightCtrl.Param.Byte[2] = 1; // 1 = E
else ToFlightCtrl.Param.Byte[2] = 0; // 1 = S
i1 = abs(GPSData.Position.Longitude)/10000000L;
i2 = abs(GPSData.Position.Longitude)%10000000L;
if(!(NCFlags & NC_FLAG_GPS_OK)) {i1 = 0; i2 = 0;}
i1 *= 100;
i1 += i2 / 100000;
i2 = i2 % 100000;
i2 /= 10;
ToFlightCtrl.Param.Byte[6] = i1 % 256;
ToFlightCtrl.Param.Byte[7] = i1 / 256;
ToFlightCtrl.Param.Byte[8] = i2 % 256;
ToFlightCtrl.Param.Byte[9] = i2 / 256;
break;
case 1:
ToFlightCtrl.Param.Byte[11] = HOTT_GPS_PACKET_ID;
ToFlightCtrl.Param.Byte[0] = 11+3; // index +3, weil bei HoTT V4 3 Bytes eingeschoben wurden
ToFlightCtrl.Param.Byte[1] = 8-1; // how many
//-----------------------------
if(GPSData.Position.Longitude < 0) ToFlightCtrl.Param.Byte[2] = 1; // 1 = E
else ToFlightCtrl.Param.Byte[2] = 0; // 1 = S
i1 = abs(GPSData.Position.Longitude)/10000000L;
i2 = abs(GPSData.Position.Longitude)%10000000L;
 
*/
}