Exemple #1
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main()
{
    int i;

    /*System clock configuration*/
    SystemInit();
    /* UART0 and UART1 configuration*/
    UART_StructInit(&UART_InitStructure);
    /* Configure UART0 */
    UART_Init(UART1,&UART_InitStructure);
    printf("########  I2C EEPROM TEST  #########\r\n");

    /* I2C Init */

    /*  I2C confiugred as follow:
     *  - I2C master mode
     *  - I2C slave address : 0xA0
     *  - I2C Prescale : 0x61
     *     /If MCU clock is 20MHz and Prescale value is 0x61, SCL occurs 100KHz as clock.
     *  - I2C Timeout : 0xFFFF
     */
    conf.mode = I2C_Master;
    conf.slave_address = 0xA0;
    conf.master.prescale = 0x61;
    conf.master.timeout = 0xFFFF;
    /* Cofigure I2C0 */
    I2C_Init(I2C0, conf);

    /* EEPROM Write Test*/
    /* It can transmit up to 9data bytes to the EEPROM(24AA02) ( mem_address 1byte, data 8bytes )   */
    if( I2C_Burst_Write(I2C0,conf.slave_address,&Transmit_Data[0],9,1) == -1 )
        return -1; 
    /*It must be use the delay function between Write operation and Read operation */
    I2C_Delay(0x000F0000);
    /*I2C Core reset */
    I2C_Reset(I2C0);

    // EEPROM Read Test
    /* I2C Start */
    I2C_Start(I2C0,conf.slave_address,I2C_WRITE_SA7);
    /* The memory address of EEPROM send to EEPROM and it wait the ack signal */
    I2C_SendDataAck(I2C0,0x00);         
    /*Once the Slave address and memotu address are clocked in and 
     *acknowledged by the EEPROM, the W7500 must generate another start condition.*/
    I2C_Restart_Structure(I2C0,conf.slave_address,I2C_READ_SA7);
    /* EEPROM Read Test*/
    for(i=0;i<MAX_SIZE;i++)
    {
        if(i != MAX_SIZE-1)     Recv_Data[i] = I2C_ReceiveData(I2C0,0);
        else                    Recv_Data[i] = I2C_ReceiveData(I2C0,1);
    }

    for(i=0;i<MAX_SIZE-2;i+=2)
        printf("[%02d]:%02x,  [%02d]:%02x\r\n",i,Recv_Data[i],i+1,Recv_Data[i+1]);

    return 0;
}
Exemple #2
0
inline int i2c_stop(i2c_t *obj)
{
    I2cHandle = (I2C_TypeDef *)(obj->i2c);

    // Generate the STOP condition
    I2C_Stop(I2cHandle);
    I2C_Reset(I2cHandle);
    obj->is_setAddress = 0;

    return 0;
}
Exemple #3
0
void I2C_Master_Init(I2C_TypeDef* I2Cx, uint32_t freq, pin_t scl, pin_t sda){
	if(I2Cx == I2C1){
		SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);
	}else if(I2Cx == I2C2){
		SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);
	}
	GPIO_ModeAF(scl, AF_OD, AF_4);
	GPIO_ModeAF(sda, AF_OD, AF_4);
	I2C_Reset(I2Cx);
	I2C_SetFreq(I2Cx, freq, I2C_MASTER);
}
Exemple #4
0
int i2c_init_master(i2c_t dev, i2c_speed_t speed)
{
    /* check if device is valid */
    if (dev >= I2C_NUMOF) {
        return -1;
    }

    /* initialize lock */
    mutex_init(&i2c_lock[dev]);

    /* enable clocks */
    CMU_ClockEnable(cmuClock_HFPER, true);
    CMU_ClockEnable(i2c_config[dev].cmu, true);

    /* configure the pins */
    gpio_init(i2c_config[dev].scl_pin, GPIO_OD);
    gpio_init(i2c_config[dev].sda_pin, GPIO_OD);

    /* ensure slave is in a known state, which it may not be after a reset */
    for (int i = 0; i < 9; i++) {
        gpio_set(i2c_config[dev].scl_pin);
        gpio_clear(i2c_config[dev].scl_pin);
    }

    /* reset and initialize the peripheral */
    I2C_Init_TypeDef init = I2C_INIT_DEFAULT;

    init.enable = false;
    init.freq = (uint32_t) speed;

    I2C_Reset(i2c_config[dev].dev);
    I2C_Init(i2c_config[dev].dev, &init);

    /* configure pin functions */
#ifdef _SILICON_LABS_32B_SERIES_0
    i2c_config[dev].dev->ROUTE = (i2c_config[dev].loc |
                                  I2C_ROUTE_SDAPEN | I2C_ROUTE_SCLPEN);
#else
    i2c_config[dev].dev->ROUTEPEN = I2C_ROUTEPEN_SDAPEN | I2C_ROUTEPEN_SCLPEN;
    i2c_config[dev].dev->ROUTELOC0 = i2c_config[dev].loc;
#endif

    /* enable interrupts */
    NVIC_ClearPendingIRQ(i2c_config[dev].irq);
    NVIC_EnableIRQ(i2c_config[dev].irq);

    /* enable peripheral */
    I2C_Enable(i2c_config[dev].dev, true);

    return 0;
}
Exemple #5
0
void i2c_reset(i2c_t *obj)
{
    I2cHandle = (I2C_TypeDef *)(obj->i2c);

    I2C_Reset(I2cHandle);
}
void SensorsTask(void)
{   
    // Array storing the status of each physical sensor.
    // If a sensor fails to initialize, or fails 3 sensor reads in a row, 
    // it will be disabled here until the next system reboot
    // 0 = tmp0
    // 1 = tmp1
    // 2 = tmp3
    // 3 = humidity / air temp
    // 4 = pressure
    // 5 = accelerometer
    uint8_t enabledSensors[7] = {3, 3, 3, 3, 3, 3, 3};
    uint8_t i;
    I2C_Status retVal = I2C_OK;
    
    INFO("(SENSORS_TASK) I2C Sensor failed to initialize\r\n");
    
    for(i = 0; i < 3; i++)
    {
        // If the temperature sensor initialized, set its enabled value to 3 (so it has 3 chances to respond to a read request)
        // Else, disable the sensor
        if(InitTempSensor(i) != I2C_OK)
        {
            I2C_Reset(SLB_I2C);
            enabledSensors[i] = 0;
            WARN("(SENSORS_TASK) I2C Sensor failed to initialize\r\n"); 
        }
    }
    
    if(InitHumiditySensor() != I2C_OK)
    {
        I2C_Reset(ALB_I2C);
        enabledSensors[3] = 0;
        WARN("(SENSORS_TASK) Humidity sensor failed to initialize\r\n");
    }
    
    if(InitPressureSensor() != I2C_OK)
    {
        I2C_Reset(ALB_I2C);
        enabledSensors[4] = 0;
        WARN("(SENSORS_TASK) Pressure sensor failed to initialize\r\n");
    }
    
    if(InitAccelerometer() != I2C_OK)
    {
        I2C_Reset(ALB_I2C);
        enabledSensors[5] = 0;
        WARN("(SENSORS_TASK) Accelerometer failed to initialize\r\n");
    }
    
    // Let other tasks in the system warmup before entering the sensor polling loop
    osDelay(2000);
    
    // TODO: re-initialize the sensors once a day to check for failures and for sensors that have come back online
    // TODO: report to the base station when a sensor fails
    
    while(1)
    {
        for(i = 0; i < 3; i++)
        {
            if(enabledSensors[i] > 0)
            {
                switch(i)
                {
                    case 0:
                        retVal = ReadTempSensor(0, &sensorData.temp0);
                        break;
                    case 1:
                        retVal = ReadTempSensor(1, &sensorData.temp1);
                        break;
                    case 2:
                        retVal = ReadTempSensor(2, &sensorData.temp2);
                        break;
                    default:
                        retVal = ReadTempSensor(0, &sensorData.temp0);
                        break;
                }
                
                // If the sensor read failed, indicate that the sensor has one less chance to respond correctly before being disabled
                if(retVal != I2C_OK)
                {
                    I2C_Reset(SLB_I2C);
                    enabledSensors[i]--;
                    WARN("(SENSORS_TASK) Temp sensor read failed\r\n");
                }
                // The sensor is still alive! Restore it to a full 3 chances to respond
                else if(enabledSensors[i] != 3)
                {
                    enabledSensors[i] = 3;
                    DEBUG("(SENSORS_TASK) Temp sensor connection restored\r\n");
                }
            }
        }
        
        if(enabledSensors[3] > 0)
        {
           do {
                if(ReadHumiditySensor(&sensorData.humid) != I2C_OK)
                {
                    I2C_Reset(ALB_I2C);
                    enabledSensors[3]--;
                    WARN("(SENSORS_TASK) Humidity sensor read failed\r\n");
                    break;
                }
                else if(enabledSensors[3] != 3)
                {
                   enabledSensors[3] = 3;
                   DEBUG("(SENSORS_TASK) Humidity sensor connection restored\r\n");
                }
               
                if(ReadAirTempSensor(&sensorData.tempAir) != I2C_OK)
                {
                    I2C_Reset(ALB_I2C);
                    enabledSensors[3]--;
                    WARN("(SENSORS_TASK) Air temp sensor read failed\r\n");
                }
                else if(enabledSensors[3] != 3)
                {
                   enabledSensors[3] = 3;
                   DEBUG("(SENSORS_TASK) Air temp sensor connection restored\r\n");
                }
            }
            while(0);
        }
        
        if(enabledSensors[4] > 0)
        {
            if(ReadPressureSensor(&sensorData.alt) != I2C_OK)
            {
                I2C_Reset(ALB_I2C);
                enabledSensors[4]--;
                WARN("(SENSORS_TASK) Altimeter sensor read failed\r\n");
            }
        }
        
        if(enabledSensors[5] > 0)
        {
            uint16_t x, y, z;
            if(ReadAccelerometer(&x, &y, &z) != I2C_OK)
            {
                I2C_Reset(ALB_I2C);
                enabledSensors[5]--;
                WARN("(SENSORS_TASK) Accelerometer sensor read failed\r\n");
            }
            
            DEBUG("X: %d, Y: %d, Z: %d", x, y, z);
        }
        
        ReadSoilMoisture(&sensorData.moist0, &sensorData.moist1, &sensorData.moist2);
        
        // Send sensor Data to the base station
        SendSensorData();
        
        osDelay(pollingRate);
    }
}
int ms_detection_polling_getinfo_callback(tNALMsrComInstance  *dev, unsigned char *inbuf, int len)
{
    unsigned char infoType;	
	PNALDebugLog("[ms_detection_polling_getinfo_callback]start, len = %d\n", len);

	if (len <= 0)
	{
        //PNALDebugLog("[ms_detection_polling_getinfo_callback]recvlen < 0");
		ms_detection_polling_req(dev);
		return 0;	
	}
	
    PNALDebugLog("[ms_detection_polling_getinfo_callback]inbuf:");
    PNALDebugLogBuffer(inbuf, len);
    
    //A3Rsp(1)[0x02] , Len(1)[n], SubFuncCode(1), ParamNum(1) [n1], ParaID(1)[0x03],ParamLen(1)[n1+1],ID(1), OriginalRsp(n1)
    //PS: ID format: DrvPL_Category_et | DrvPL_PLItem_et    
    if ((inbuf[4] != 0xA1) || (inbuf[5] <= 1)) 
    {
        PNALDebugLog("Queue data is empty, do detection.");
		ms_detection_polling_req(dev);
		return 0;
    }
	infoType = inbuf[6];
	PNALDebugError("SWP Reset Cnt= %d", dev->swp_reset_cnt);
	PNALDebugLog("Info Type= %x", infoType);
	switch(infoType)
	{
	    case DrvPL_PLItem_R_ISO43A:
			ms_A3_RFID_43A_Inventory_Callback(dev, inbuf+7, inbuf[5]-1);
			break;

	    case DrvPL_PLItem_R_ISO43B:
			ms_open_nfc_43b_inventory_cbrecv(dev, inbuf+7, inbuf[5]-1);
			break;			

		case DrvPL_PLItem_R_ISO693:
			ms_A3_RFID_693_Inventory_Callback(dev, inbuf+7, inbuf[5]-1); 
			break;

		case DrvPL_PLItem_R_Felica:
			ms_open_nfc_felica_Inventory_callback(dev, inbuf+7, inbuf[5]-1);
			break;

		case DrvPL_PLItem_R_Type1:
			ms_open_nfc_type1_detection_sens_new_callback(dev, inbuf+7, inbuf[5]-1);
			break;

	    case DrvPL_PLItem_PI_P2P_212:
			break;

		case DrvPL_PLItem_PI_P2P_424:
			ms_open_nfc_initiator_detection_212_424_callback(dev, inbuf+7, inbuf[5]-1);
			break;

		case DrvPL_PLItem_PT_P2P_106:
			break;

		case DrvPL_PLItem_PT_P2P_212:
			break;

		case DrvPL_PLItem_PT_P2P_424:
			dev->sendTargetSddEvt = W_FALSE;
	        dev->temp_target_buf_len = 0;
			ms_nfc_p2p_target_enable_callback(dev, inbuf+7, inbuf[5]-1);
			break;	

		case DrvPL_PLItem_C_ISO43A:
			PNALDebugLog("43A Card Mode Started.");
			Start_IRQ_Detect(dev);
			break;		

		case DrvPL_PLItem_C_ISO43B:
			PNALDebugLog("43B Card Mode Started.");
            Start_IRQ_Detect(dev);    
			break;	

		case DrvPL_PLItem_C_CONN:
			PNALDebugLog("EVT_CONNECTIVITION");
			Start_IRQ_Detect(dev); 
			break;

		case DrvPL_PLItem_C_TRAN:
			PNALDebugLog("EVT_TRANSACTION");
			Start_IRQ_Detect(dev); 
			break;			

		case DrvPL_PLItem_PIT_P2P_424:
			PNALDebugLog("P2P IT Mode Started.");
			if (inbuf[10] == DRVP2P_result_As_Initiator)
			{
                PNALDebugLog("P2P IT Mode Started: Initiator");
				ms_open_nfc_initiator_detection_212_424_callback(dev, inbuf+7, inbuf[5]-1);
			}
			else if (inbuf[10] == DRVP2P_result_As_Target)
			{
                PNALDebugLog("P2P IT Mode Started: Target");
				dev->sendTargetSddEvt = W_FALSE;
	        	dev->temp_target_buf_len = 0;
				ms_nfc_p2p_target_enable_callback(dev, inbuf+7, inbuf[5]-1);
			}
			else
			{
			    PNALDebugError("P2P IT Mode Report Error");
			}
			break;

		case DrvPL_PLItem_Reset:
			PNALDebugLog("Reader need to Reset");
			dev->swp_reset_cnt++;			
			I2C_Reset();
			ms_card_detection(dev);
			break;

		default:
			break;
	}
	PNALDebugLog("[ms_detection_polling_getinfo_callback]end");
	return 1;
}
Exemple #8
0
void i2c_reset(i2c_t *obj)
{
    /* EMLib function */
    I2C_Reset(obj->i2c.i2c);
}
Exemple #9
0
/***************************************************************************//**
 * @brief
 *  Initialize the specified IIC unit
 *
 * @details
 *
 * @note
 *
 * @param[in] unitNumber
 *  Unit number
 *
 * @param[in] location
 *  Pin location number
 ******************************************************************************/
static struct efm32_iic_device_t *rt_hw_iic_unit_init(
    struct efm32_iic_block  *block,
    rt_uint8_t              unitNumber,
    rt_uint8_t              location)
{
    struct efm32_iic_device_t   *iic;
    CMU_Clock_TypeDef           iicClock;
    GPIO_Port_TypeDef           port_scl, port_sda;
    rt_uint32_t                 pin_scl, pin_sda;
    I2C_Init_TypeDef            init = I2C_INIT_DEFAULT;
    efm32_irq_hook_init_t       hook;
    rt_uint8_t                  name[RT_NAME_MAX];

    do
    {
        /* Allocate device */
        iic = rt_malloc(sizeof(struct efm32_iic_device_t));
        if (iic == RT_NULL)
        {
            iic_debug("IIC err: no MEM for IIC%d driver\n", unitNumber);
            break;
        }
        iic->counter        = 0;
        iic->timer          = &block->timer;
        iic->timeout        = false;
        iic->state          |= IIC_STATE_MASTER;
        iic->address        = 0x0000;
        iic->rx_buffer      = RT_NULL;

        /* Initialization */
        if (unitNumber >= I2C_COUNT)
        {
            break;
        }
        switch (unitNumber)
        {
        case 0:
            iic->iic_device = I2C0;
            iicClock        = (CMU_Clock_TypeDef)cmuClock_I2C0;
            port_scl            = AF_I2C0_SCL_PORT(location);
            pin_scl             = AF_I2C0_SCL_PIN(location);
            port_sda            = AF_I2C0_SDA_PORT(location);
            pin_sda             = AF_I2C0_SDA_PIN(location);
            break;
#if (I2C_COUNT > 1)
        case 1:
            iic->iic_device = I2C1;
            iicClock        = (CMU_Clock_TypeDef)cmuClock_I2C1;
            port_scl            = AF_I2C1_SCL_PORT(location);
            pin_scl             = AF_I2C1_SCL_PIN(location);
            port_sda            = AF_I2C1_SDA_PORT(location);
            pin_sda             = AF_I2C1_SDA_PIN(location);
            break;
#endif
        default:
            break;
        }
        rt_sprintf(name, "iic%d", unitNumber);

        /* Enabling clock */
        CMU_ClockEnable(iicClock, true);

        /* Reset */
        I2C_Reset(iic->iic_device);

        /* Config GPIO */
        GPIO_PinModeSet(
            port_scl,
            pin_scl,
            gpioModeWiredAndPullUpFilter,
            1);
        GPIO_PinModeSet(
            port_sda,
            pin_sda,
            gpioModeWiredAndPullUpFilter,
            1);

        hook.type       = efm32_irq_type_iic;
        hook.unit       = unitNumber;
        hook.cbFunc     = rt_hw_iic_slave_isr;
        hook.userPtr    = (void *)&block->device;
        efm32_irq_hook_register(&hook);

        /* Enable SDZ and SCL pins and set location */
        iic->iic_device->ROUTE = I2C_ROUTE_SDAPEN | I2C_ROUTE_SCLPEN | \
                    (location << _I2C_ROUTE_LOCATION_SHIFT);

        /* Initializing IIC */
        init.enable = false;
        I2C_Init(iic->iic_device, &init);

        /* Abort current TX data and clear TX buffers */
        iic->iic_device->CMD = I2C_CMD_ABORT | I2C_CMD_CLEARPC | I2C_CMD_CLEARTX;

        /* Initialize lock */
        iic->lock = &block->lock;
        if (rt_sem_init(iic->lock, name, 1, RT_IPC_FLAG_FIFO) != RT_EOK)
        {
            break;
        }

        /* Initialize timer */
        rt_timer_init(iic->timer, name, rt_iic_timer, &iic->timeout,
            IIC_TIMEOUT_PERIOD, RT_TIMER_FLAG_ONE_SHOT);

        return iic;
    } while(0);

    if (iic)
    {
        rt_free(iic);
    }

    iic_debug("IIC err: Unit %d init failed!\n", unitNumber);
    return RT_NULL;
}
Exemple #10
0
//############################################################################
//Hauptprogramm
int main (void)
//############################################################################
{
	unsigned int timer,i,timer2 = 0, timerPolling;

    DDRB  = 0x00;
    PORTB = 0x00;
    for(timer = 0; timer < 1000; timer++); // verzögern
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
	PlatinenVersion = 21;
#else
	if(PINB & 0x01)
     {
      if(PINB & 0x02) PlatinenVersion = 13;
       else           PlatinenVersion = 11;
     }
    else
     {
      if(PINB & 0x02) PlatinenVersion = 20;
       else           PlatinenVersion = 10;
     }
#endif
    DDRC  = 0x81; // SCL
    DDRC  |=0x40; // HEF4017 Reset
    PORTC = 0xff; // Pullup SDA
    DDRB  = 0x1B; // LEDs und Druckoffset
    PORTB = 0x01; // LED_Rot
    DDRD  = 0x3E; // Speaker & TXD & J3 J4 J5
	PORTD = 0x47; // LED
    HEF4017R_ON;
    MCUSR &=~(1<<WDRF);
    WDTCSR |= (1<<WDCE)|(1<<WDE);
    WDTCSR = 0;

    beeptime = 2500;
	StickGier = 0; PPM_in[K_GAS] = 0; StickRoll = 0; StickNick = 0;
    if(PlatinenVersion >= 20)  GIER_GRAD_FAKTOR = 1220; else GIER_GRAD_FAKTOR = 1291; // unterschiedlich für ME und ENC
    ROT_OFF;

    Timer_Init();
	TIMER2_Init();
	UART_Init();
    rc_sum_init();
   	ADC_Init();
	I2C_Init(1);
	SPI_MasterInit();
	Capacity_Init();
	LIBFC_Init();
	GRN_ON;
    sei();
	ParamSet_Init();


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Check connected BL-Ctrls
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check connected BL-Ctrls
	BLFlags |= BLFLAG_READ_VERSION;
	motor_read = 0;  // read the first I2C-Data
	SendMotorData();
	timer = SetDelay(500);
	while(!(BLFlags & BLFLAG_TX_COMPLETE) && !CheckDelay(timer)); //wait for complete transfer

    printf("\n\rFound BL-Ctrl: ");
    timer = SetDelay(4000);
	for(i=0; i < MAX_MOTORS; i++)
	{
		SendMotorData();
		while(!(BLFlags & BLFLAG_TX_COMPLETE)  && !CheckDelay(timer)); //wait for complete transfer
		if(Mixer.Motor[i][0] > 0) // wait max 4 sec for the BL-Ctrls to wake up
		{
			while(!CheckDelay(timer) && !(Motor[i].State & MOTOR_STATE_PRESENT_MASK) )
			{
				SendMotorData();
				while(!(BLFlags & BLFLAG_TX_COMPLETE) && !CheckDelay(timer)); //wait for complete transfer
			}
		}
		if(Motor[i].State & MOTOR_STATE_PRESENT_MASK)
		{
			printf("%d",i+1);
			FoundMotors++;
//			if(Motor[i].Version & MOTOR_STATE_NEW_PROTOCOL_MASK) printf("(new) ");
		}
	}
	for(i=0; i < MAX_MOTORS; i++)
	{
		if(!(Motor[i].State & MOTOR_STATE_PRESENT_MASK) && Mixer.Motor[i][0] > 0)
		{
			printf("\n\r\n\r!! MISSING BL-CTRL: %d !!",i+1);
			ServoActive = 2; // just in case the FC would be used as camera-stabilizer
		}
		Motor[i].State &= ~MOTOR_STATE_ERROR_MASK; // clear error counter
	}
 	printf("\n\r===================================");

    if(RequiredMotors < FoundMotors) VersionInfo.HardwareError[1] |= FC_ERROR1_MIXER;

	//if(EE_Parameter.GlobalConfig & CFG_HOEHENREGELUNG)
	{
		printf("\n\rCalibrating pressure sensor..");
		timer = SetDelay(1000);
		SucheLuftruckOffset();
		while (!CheckDelay(timer));
		printf("OK\n\r");
	}

	SetNeutral(0);

	ROT_OFF;

    beeptime = 2000;
    ExternControl.Digital[0] = 0x55;


	FlugMinuten = (unsigned int)GetParamByte(PID_FLIGHT_MINUTES) * 256 + (unsigned int)GetParamByte(PID_FLIGHT_MINUTES + 1);
	FlugMinutenGesamt = (unsigned int)GetParamByte(PID_FLIGHT_MINUTES_TOTAL) * 256 + (unsigned int)GetParamByte(PID_FLIGHT_MINUTES_TOTAL + 1);

	if((FlugMinutenGesamt == 0xFFFF) || (FlugMinuten == 0xFFFF))
	{
		FlugMinuten = 0;
		FlugMinutenGesamt = 0;
	}
    printf("\n\rFlight-time %u min  Total:%u min", FlugMinuten, FlugMinutenGesamt);

	printf("\n\rControl: ");
	if (EE_Parameter.GlobalConfig & CFG_HEADING_HOLD) printf("HeadingHold");
	else printf("Normal (ACC-Mode)");

    LcdClear();
    I2CTimeout = 5000;
    WinkelOut.Orientation = 1;
    LipoDetection(1);

	LIBFC_ReceiverInit(EE_Parameter.Receiver);

	printf("\n\r===================================\n\r");
	//SpektrumBinding();
    timer = SetDelay(2000);
	timerPolling = SetDelay(250);

	Debug(ANSI_CLEAR "FC-Start!\n\rFlugzeit: %d min", FlugMinutenGesamt);  	// Note: this won't waste flash memory, if #DEBUG is not active
    DebugOut.Status[0] = 0x01 | 0x02;
	JetiBeep = 0;
	while (1)
	{
	
	if (JetiUpdateModeActive) while (1);
	
	if(CheckDelay(timerPolling))
	{
	  timerPolling = SetDelay(100);
	  LIBFC_Polling();
	}
	if(UpdateMotor && AdReady)      // ReglerIntervall
            {
  		    UpdateMotor=0;
            if(WinkelOut.CalcState) CalMk3Mag();
            else  MotorRegler();
			SendMotorData();
            ROT_OFF;
            if(SenderOkay)  { SenderOkay--; VersionInfo.HardwareError[1] &= ~FC_ERROR1_PPM; }
			else
			{
				TIMSK1 |= _BV(ICIE1); // enable PPM-Input
				PPM_in[0] = 0; // set RSSI to zero on data timeout
				VersionInfo.HardwareError[1] |= FC_ERROR1_PPM;
			}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//if(HoehenReglerAktiv && NaviDataOkay && SenderOkay < 160 && SenderOkay > 10 && FromNaviCtrl_Value.SerialDataOkay > 220) SenderOkay = 160;
//if(HoehenReglerAktiv && NaviDataOkay && SenderOkay < 101 && SenderOkay > 10 && FromNaviCtrl_Value.SerialDataOkay > 1) SenderOkay = 101;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            if(!--I2CTimeout || MissingMotor)
                {
                  if(!I2CTimeout)
				   {
				    I2C_Reset();
                    I2CTimeout = 5;
					DebugOut.Analog[28]++; // I2C-Error
					VersionInfo.HardwareError[1] |= FC_ERROR1_I2C;
					DebugOut.Status[1] |= 0x02; // BL-Error-Status
  				   }
                  if((BeepMuster == 0xffff) && MotorenEin)
                   {
                    beeptime = 10000;
                    BeepMuster = 0x0080;
                   }
                }
            else
                {
                 ROT_OFF;
				 if(!beeptime)
				  {
				   VersionInfo.HardwareError[1] &= ~FC_ERROR1_I2C;
				  }
                }
          if(!UpdateMotor)
		   {
			if(CalculateServoSignals) CalculateServo();
			DatenUebertragung();
			BearbeiteRxDaten();
			if(CheckDelay(timer))
			{
				static unsigned char second;
				timer += 20; // 20 ms interval
				if(MissingMotor)
				 {
				  VersionInfo.HardwareError[1] |= FC_ERROR1_BL_MISSING;
				  DebugOut.Status[1] |= 0x02; // BL-Error-Status
				 }
				 else
				 {
				   VersionInfo.HardwareError[1] &= ~FC_ERROR1_BL_MISSING;
				   if(I2CTimeout > 6) DebugOut.Status[1] &= ~0x02; // BL-Error-Status
				 }

			    if(I2CTimeout > 6) VersionInfo.HardwareError[1] &= ~FC_ERROR1_I2C;

				if(PcZugriff) PcZugriff--;
				else
				{
					ExternControl.Config = 0;
					ExternStickNick = 0;
					ExternStickRoll = 0;
					ExternStickGier = 0;
					if(BeepMuster == 0xffff && SenderOkay == 0)
					{
						beeptime = 15000;
						BeepMuster = 0x0c00;
					}
				}
				if(NaviDataOkay > 200)
				{
					NaviDataOkay--;
					VersionInfo.HardwareError[1] &= ~FC_ERROR1_SPI_RX;
				}
				else
				{
					if(NC_Version.Compatible)
					 {
						VersionInfo.HardwareError[1] |= FC_ERROR1_SPI_RX;
                       if(BeepMuster == 0xffff && MotorenEin)
						{
							beeptime = 15000;
							BeepMuster = 0xA800;
						}
					 }
					GPS_Nick = 0;
					GPS_Roll = 0;
					//if(!beeptime)
                    FromNaviCtrl.CompassValue = -1;
                    NaviDataOkay = 0;
				}
			   if(UBat < BattLowVoltageWarning)
				{
					FC_StatusFlags |= FC_STATUS_LOWBAT;
					if(BeepMuster == 0xffff)
					{
						beeptime = 6000;
						BeepMuster = 0x0300;
					}
				}
				else if(!beeptime) FC_StatusFlags &= ~FC_STATUS_LOWBAT;

				SPI_StartTransmitPacket();
				SendSPI = 4;
				if(!MotorenEin) timer2 = 1450; // 0,5 Minuten aufrunden
				else
                if(++second == 49)
				 {
				   second = 0;
				   FlugSekunden++;
				 }
				if(++timer2 == 2930)  // eine Minute
				 {
				   timer2 = 0;
               	   FlugMinuten++;
	               FlugMinutenGesamt++;
                   SetParamByte(PID_FLIGHT_MINUTES,FlugMinuten / 256);
                   SetParamByte(PID_FLIGHT_MINUTES+1,FlugMinuten % 256);
                   SetParamByte(PID_FLIGHT_MINUTES_TOTAL,FlugMinutenGesamt / 256);
                   SetParamByte(PID_FLIGHT_MINUTES_TOTAL+1,FlugMinutenGesamt % 256);
				   timer = SetDelay(20); // falls "timer += 20;" mal nicht geht
	  		     }
			}
           LED_Update();
           Capacity_Update();
           } //else DebugOut.Analog[26]++;
          }
     if(!SendSPI) { SPI_TransmitByte(); }
    }
 return (1);
}