Example #1
0
static void initHardware(void)
{
	Chip_SetupXtalClocking();
	Chip_SYSCTL_SetFLASHAccess(FLASHTIM_100MHZ_CPU);
    SystemCoreClockUpdate();


/*====================[PARA MODULO RF]====================*/
	Chip_GPIO_WriteDirBit(LPC_GPIO, CE_PIN, 1); //Puerto CE
	Chip_GPIO_SetPinOutLow(LPC_GPIO, CE_PIN); //Puerto CE
	InitSPI ();

	begin();
	setPALevel(RF24_PA_LOW);
	openWritingPipe(&addresses2[0]);
	openReadingPipe(1,&addresses1[0]);	//1Node: Transmite paquetes el tx por este pide (addres)

	startListening();

/*========================================================*/



//    Board_Init();

//    Board_LED_Set(0, false);

    SysTick_Config(SystemCoreClock/1000);		//1000 ticks por segundo

	InitPWM_motores(0);			//Función inicialización modulo PWM
	InitPWM_motores(1);			//Función inicialización modulo PWM
	InitPWM_motores(2);			//Función inicialización modulo PWM
	InitPWM_motores(3);			//Función inicialización modulo PWM
	InitPWM0();
	InitGPIO(0);			//Llamo función para inicializar GPIO
	InitGPIO(1);			//Llamo función para inicializar GPIO
	InitGPIO(2);			//Llamo función para inicializar GPIO
	InitGPIO(3);			//Llamo función para inicializar GPIO
	Stop_and_Default(0);	//Condiciones iniciales
	Stop_and_Default(1);	//Condiciones iniciales
	Stop_and_Default(2);	//Condiciones iniciales
	Stop_and_Default(3);	//Condiciones iniciales


    P2_6ER = 1;    P2_7ER = 1;    P2_8ER = 1;

    P2_6EF = 1;    P2_7EF = 1;    P2_8EF = 1;



    P0_15ER = 1;    P0_16ER = 1;    P2_9ER = 1;

    P0_15EF = 1;    P0_16EF = 1;    P2_9EF = 1;

    NVIC_SetPriority(EINT3_IRQn,1);			//Le pongo la mayor prioridad a la interrupcion
    NVIC_EnableIRQ(EINT3_IRQn);


}
Example #2
0
int main()
{
  InitGPIO();
  //InitTIM3();
  //InitTIM4();

  InitIWDG();    // Init Watch Dog 
  InitBKP();
  
#ifdef DEBUG_OUTPUT_USB
  Set_System();
  Set_USBClock();
  USB_Interrupts_Config();
  USB_Init();
#else
  rtc_init();
#endif
  
  RTC_t date;
  date.year = 2015;
  date.month = 10;
  date.mday = 24;
  
  date.hour = 23;
  date.min = 20;
  date.sec = 0;
  rtc_settime(&date);
  
  // Start Task //
  xTaskCreate(vLcdPcf, "vLcdPcf", configMINIMAL_STACK_SIZE * 2, NULL, tskIDLE_PRIORITY + 1, &xHandlevLcdPcfTask);
  xTaskCreate(vDebugTask, "vDebugTask", configMINIMAL_STACK_SIZE * 2, NULL, tskIDLE_PRIORITY + 1, &xHandleDebugTask);
  
  // Start scheduler //
  osKernelStart(NULL, NULL);
}
Example #3
0
int main()
{
  InitGPIO();

  InitBKP();
  
  Set_System();
  Set_USBClock();
  USB_Interrupts_Config();
  USB_Init();
  
  
  rtc_init();
  
  /*
  RTC_t date;
  date.year = 2015;
  date.month = 10;
  date.mday = 24;
  
  date.hour = 23;
  date.min = 20;
  date.sec = 0;
  rtc_settime(&date);
  */
  
  // Start Task //
  xTaskCreate(vLcdTask, "vLcdTask", configMINIMAL_STACK_SIZE * 1, NULL, tskIDLE_PRIORITY + 1, &xHandleLcdTask);
  xTaskCreate(vDebugTask, "vDebugTask", configMINIMAL_STACK_SIZE * 1, NULL, tskIDLE_PRIORITY + 1, &xHandleDebugTask);
  
  // Start scheduler //
  osKernelStart(NULL, NULL);
}
Example #4
0
void i2c2_init(void)
{
	  gpio_request(PIN_SDA,"SDA");
    gpio_request(PIN_SCL,"SCL");
   
		InitGPIO();
}
Example #5
0
static int init(void)
{
	printk(KERN_ALERT "Modlue starting.\n");
	InitGPIO();
	InitPPC();
	return 0;
}
Example #6
0
File: mick.c Project: deazurain/uni
int main(int argc, char **argv) {
 
  InitGPIO();

  while(1) {
    print_motor_status();
    print_button_status();

    /*
    int * pins = (int *) malloc(sizeof(int) * 22);
    int i = 0;
    while(i < 22) {
      pins[i] = GetGPIOPin(i);

      printf("%d ", pins[i]);
      i++;
    }

    printf("\n");
    */

    sleep(1);
    
  }

  CleanupGPIO();
  CleanupPPC();

  return 0;
}
static int PixI2c_Ioctl(struct inode *inode, struct file *fp, unsigned int cmd, unsigned long arg)
{
    PPIX_IIC_DATA ptr_user_data;
    unsigned int ui_data_length;
    unsigned char uc_device_addr;
    unsigned char uc_sub_addr;
    void *ptr_data=NULL;
    int i_return=0;

    switch(cmd)
    {
    case IOCTL_PIX_I2C_INIT:
        InitGPIO();
        break;
    case IOCTL_PIX_I2C_TERMINATE:
        ReleaseGPIO();
        break;
    case IOCTL_PIX_I2C_READ:
        ptr_user_data = (PPIX_IIC_DATA)arg;
        if((i_return=get_user(uc_device_addr, &ptr_user_data->device_addr))<0)
        {
            goto ERROR_IOCTL;
        }
        if((i_return=get_user(uc_sub_addr, &ptr_user_data->sub_addr))<0)
        {
            goto ERROR_IOCTL;
        }
        if((i_return=get_user(ui_data_length, &ptr_user_data->ui_data_length))<0)
        {
            goto ERROR_IOCTL;
        }
        ptr_data = kmalloc(ui_data_length,GFP_KERNEL);
        if((i_return=PixI2cRead(uc_device_addr, uc_sub_addr, ptr_data, ui_data_length))<0)
            goto ERROR_IOCTL;
        if((i_return=copy_to_user((void*)ptr_user_data->ptr_data, ptr_data, ui_data_length))<0)
            goto ERROR_IOCTL;
        break;
    case IOCTL_PIX_I2C_WRITE:
        ptr_user_data = (PPIX_IIC_DATA)arg;
        if((i_return=get_user(uc_device_addr, &ptr_user_data->device_addr))<0)
            goto ERROR_IOCTL;
        if((i_return=get_user(uc_sub_addr, &ptr_user_data->sub_addr))<0)
            goto ERROR_IOCTL;
        if((i_return=get_user(ui_data_length, &ptr_user_data->ui_data_length))<0)
            goto ERROR_IOCTL;
        ptr_data = kmalloc(ui_data_length,GFP_KERNEL);
        if((i_return=copy_from_user(ptr_data, (const void*)ptr_user_data->ptr_data, ui_data_length))<0)
            goto ERROR_IOCTL;
        if((i_return=PixI2cWrite(uc_device_addr, uc_sub_addr, ptr_data, ui_data_length))<0)
            goto ERROR_IOCTL;
        break;
    default:
        i_return=-EINVAL;
        break;
    }
ERROR_IOCTL:
    KERNEL_FREE(ptr_data);
    return i_return;
}
Example #8
0
int main(void)
{
	ms = 0;
	InitGPIO();
	InitLCD();
	InitSysTick();
	limpaLCD();
	
	for(;;) {	}
} 
Example #9
0
/**
 *  @fn void MCUInit()
 *
 *  @brief Sets the microcontroller to a predetermined state. Handles initialization
 *         for all categories of peripherals: Analog, Architecture, Communication,
 *         Data Converters, GPIO, LCD, Special Modules, Timers.
 *
 */
void MCUInit()
{
  #if defined(__MCU_MSP430_SERIES)
    InitAnalog();				                                // Initialize the Analog modules
    InitArchitecture();			                                        // Initialize the Architecture modules
    InitCommunication();			                                // Initialize the Communication modules
    InitDataConverters();			                                // Initialize the Data Converter modules
    InitGPIO();				                                        // Initialize the GPIO modules
    InitLCD();				                                        // Initialize the LCD modules
    InitSpecialModules();			                                // Initialize the Special modules
    InitTimers();				                                // Initialize the Timers modules
  #endif
}
int __init PixI2c_Init(void)
{
    int nResult;
    nResult = misc_register(&pix_i2c_dev);
    if(nResult)
    {
        DPRINTK("[init PixI2c_Init]fail to regist dev...................!!!!!!!!!!!!!!!!!\n");
        return nResult;
    }
    InitGPIO();

    return 0;
}
Example #11
0
int 
initpwm(void)
{
  int i;
  int retval;

  for(i = 0; i < RC_NUM; i++)
    {
      up_interval[i] = RANGE_MAP100(ranges[i][0], ranges[i][1], 0);
      reconfigured[i] = 0;
    }

  retval = InitGPIO(channels, sizeof(channels) / sizeof(channels[0]));
  if(retval)
  {
    rtdm_printk("TB6612FNG: GPIO initialization failed\n");
    return retval;
  }
  rtdm_printk("TB6612FNG: GPIO initialized\n");

  rtdm_printk("TB6612FNG: Starting PWM generation timers.\n");
  retval = rtdm_timer_init(&up_timer, pwm_up, "up timer");
  if(retval)
    {
      rtdm_printk("TB6612FNG: error initializing up-timer: %i\n", retval);
      return retval;
    }

  for(i = 0; i < RC_NUM; i++)
    {
      retval = rtdm_timer_init(&down_timer[i], pwm_down, "down timer");
      if(retval)
	{
	  rtdm_printk("TB6612FNG: error initializing down-timer #%i: %i\n", i, retval);
	  return retval;
	}
    }

  retval = rtdm_timer_start(&up_timer, 
			    PERIOD, // we will use periodic timer
			    PERIOD, // PERIOD period
			    RTDM_TIMERMODE_RELATIVE);
  if(retval)
    {
      rtdm_printk("TB6612FNG: error starting up-timer: %i\n", retval);
      return retval;
    }
  rtdm_printk("TB6612FNG: timers created\n");

  return 0;
}
void MCU_Init() {
  InitGPIO();
  delay_ms(5000);
  UART2_Init(115200);
  Delay_ms(100);
  ble2_hal_init();
  data_len = 0;
  data_ready = 0;
  U2IP0_bit = 0;
  U2IP1_bit = 1;
  U2IP2_bit = 1;
  U2RXIE_bit = 1;
  EnableInterrupts();
}
Example #13
0
void I2C::Initialize (uint32_t clockSpeed, bool isDuty16_9, bool isFmMode, bool initializeGPIO)
{
    Enable(false);
    SetSoftwareReset(true);
    SetSoftwareReset(false);
    EnablePeripheralClock(true);
    SetClock(clockSpeed, isDuty16_9, isFmMode);
    if (initializeGPIO)
    {
        InitGPIO();
    }
    Enable(true);
    _stuckBUSY = false;

}
Example #14
0
int main(void)
{

	float tempf;

	InitRCC();
	InitGPIO();
	InitADC();

	I2CInit();
	InitIT();
	Delay_Init(24);

	// reset pot value
	PotWrite(0x00);


    while(1) {
    	if (mode == MODE_CAL) {
    		LED_GREEN_ON();
    		LED_RED_OFF();
    		uint16_t av = ADC_GetConversionValue(AN_ADCx);
    		if (av > trig_level) {
    			trig_level = av;
    			tempf = GetADCVolt(trig_level)*VOLT_DIV; // get voltage from piezo
    			tempf = GetTargetK(tempf);		// get target amp coefficient
    			tempf = GetTargetR(tempf);		// get R2 for opamp feedback
    			tempf = GetPotR(tempf);			// get target resistance for pot as part of R2
    			PotWrite(GetWStep(tempf));		// write step to pot
    		}

    	} else {
    		// turn on red for working mode indication, turn green if mcu gets opamp output high
    		LED_RED_ON();
    		if (GPIO_ReadInputDataBit(OP_PORT, OP_PIN) == SET) {
    			LED_GREEN_ON();
    			delay_ms(500);
    		} else {
    			LED_GREEN_OFF();
    		}


    	}

    }

}
Example #15
0
int main(int argc, char** argv)
{

    //Initializations
    InitCLK();
    InitGPIO();
    InitDAC();
    InitSPI();
    InitTimer0();
    InitWatchdog();

    //Setup interrupts
    PEIE = 1;
    GIE = 1;

    SPI_CS = CS_IDLE; //must be changed!


    SSPCON1bits.SSPEN=0;  // Disable SPI Port
    //PORTCbits.RC5 = 0;    //Set MOSI low
    //PORTCbits.RC3 = 0;    //Set SCK low
    PORTCbits.PORTC = LATCbits.LATC & 0xD7; //set MOSI and SCK low

    while(1)
    {
        SPI_CS = CS_IDLE; //hands off mode for testing the launcher

        //Check if beacon has been launched
        CheckDisconnect(); //DONE+TESTED

        if(playbackFlag&&!MEM_ACCESS)
        {
            PlaybackMode();
            playbackFlag = 0;
        }

        //Transmit message
        if(transmitFlag) //DONE+TESTED
            TransmitMode(); //DONE+TESTED

        //Go back to sleep, wait for interrupts
        Hibernate();
    }

    return (EXIT_SUCCESS);
}
Example #16
0
int main(void)
{
	// Check that you flashed to the correct microcontroller
	uint32_t chipId1 = TM_ID_GetUnique32(0);
	uint32_t chipId2 = TM_ID_GetUnique32(1);
	uint32_t chipId3 = TM_ID_GetUnique32(2);
	if(chipId1 != 0x00290044 || chipId2 != 0x30345117 || chipId3 != 0x37333838){
		while(1);
	}
	
	// Configure the system clock.
	// The system clock is 168Mhz.
	RCC_HSEConfig(RCC_HSE_ON); // ENABLE HSE (HSE = 8Mhz)
	while(!RCC_WaitForHSEStartUp());  // Wait for HSE to stabilize
	
	SystemCoreClockUpdate();
	RCC_PCLK1Config(RCC_HCLK_Div4); // Set APB1=42Mhz (168/4)

	
	// Initialize peripheral modules
	InitGPIO();
	InitNVIC();
	InitPedalIntegrity();
	InitADC();
	InitCAN();
//	MCO_Config(); // Clock output
	
	
	
	
	/* Main code */
	while(1)
	{
		Delay(0xFF);
		/*
		if(CAN_GetITStatus(CAN1,CAN_IT_FMP0) == SET){
		
		CAN_Receive(CAN1,CAN_FIFO0,&msgRx);
		if(msgRx.StdId == 0x1){
			GPIOC->ODR |= GPIO_Pin_6;
		}
	}
		*/
	}
}
Example #17
0
int main(void)
{
	// Configure the system clock.
	// The system clock is 168Mhz.
	RCC_HSEConfig(RCC_HSE_ON); // ENABLE HSE (HSE = 8Mhz)
	while(!RCC_WaitForHSEStartUp());  // Wait for HSE to stabilize
	
	SystemCoreClockUpdate();
	RCC_PCLK1Config(RCC_HCLK_Div4); // Set APB1=42Mhz (168/4)

	// Initialize peripheral modules
	InitCAN();
	InitGPIO();
	InitButtons();
	InitEXTI();
	InitNVIC();
	InitTim();
	InitSystick();
	InitWatchdog();
	
	/* 
	Check if the IWDG reset has occoured
	*/
	/*if(RCC_GetFlagStatus(RCC_FLAG_IWDGRST) == SET){
		GPIOA->ODR |= GPIO_Pin_6; //temp action
		RCC_ClearFlag();
	}*/
	
	while(1)
	{ 	
		if(clk10msWheel == COMPLETE){
			TxWheelrpm();
			clk10msWheel = RESTART;
		}
		
		checkButtons();
		
		LED_SetState(LED_GREEN, (GPIOE->IDR & BUTTON_START_GPIO_PIN) ? DISABLE : ENABLE);
		LED_SetState(LED_RED,   (GPIOE->IDR & BUTTON_STOP_GPIO_PIN)  ? ENABLE : DISABLE);
	}
}
Example #18
0
int main(int argc, char **argv)
{
    printf("Begin\n");
    InitGPIO();
    //while(GetGPIOPin(8)) {
    //	if(!GetGPIOPin(9)) {
    //		printf("button is pressed\n");
    //	}
    //}
    SetGPIOPinDir(2,1);
    SetGPIOPinDir(3,1);
    SetGPIOPinDir(4,1);
    SetGPIOPinDir(5,1);
    SetGPIOPinDir(6,1);
    SetGPIOPinDir(7,1);

    SetGPIOPin(4);
    SetGPIOPin(7);

    while (1) {

        int left = GetGPIOPin(3);
        int right = GetGPIOPin(6);

        if(!GetGPIOPin(8)) {
            if(left) SetGPIOPin(3);
            else {
                ClearGPIOPin(3);
            }
        }
        if(!GetGPIOPin(9)) {
            if(left) SetGPIOPin(6);
            else {
                ClearGPIOPin(6);
            }
        }
        sleep(5);
    }
    CleanupGPIO();
    return 0;
}
Example #19
0
//=========================================================================
//----- (00000C48) --------------------------------------------------------
__myevic__ void InitHardware()
{
	SYS_UnlockReg();

	//  32.768kHz external crystal
	if ( dfStatus.x32off )
	{
		CLK_DisableXtalRC( CLK_PWRCTL_LXTEN_Msk );
	}
	else
	{
		SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF0MFP_Msk|SYS_GPF_MFPL_PF1MFP_Msk);
		SYS->GPF_MFPL |=  (SYS_GPF_MFPL_PF0MFP_X32_OUT|SYS_GPF_MFPL_PF1MFP_X32_IN);

		CLK_EnableXtalRC( CLK_PWRCTL_LXTEN_Msk );
		CLK_WaitClockReady( CLK_STATUS_LXTSTB_Msk );
	}

	SetPWMClock();

	SYS_LockReg();

	#if (ENABLE_UART)
	InitUART0();
	#endif

	InitGPIO();

	if ( !PD3 )
	{
		gFlags.noclock = 1;
	}

	InitSPI0();
	InitEADC();
	InitPWM();
	InitTimers();
	InitUSB();
}
Example #20
0
int main(int argc, char** argv) {
    
    //Initializations
    InitCLK();
    InitGPIO();
    InitADC();
    //InitSPI();
    InitTimer0();
    InitTimer1();
    InitWatchdog();
    InitUART();             //Initialize UART module

    unsigned char periodicCounter = MIN_PERIOD;
    gpsIndex = 0;

    INTCONbits.GIE = 1;

    ToggleSleepGPS();       //Turn GPS on
    SetupGPS();             //Setup Lat/Long recording

    PORTBbits.PORTB = LATBbits.LATB & 0xDF; //turn red LED off
    PORTBbits.PORTB = LATBbits.LATB | 0x10; //turn green LED on
    __delay_ms(100);
    PORTBbits.PORTB = LATBbits.LATB & 0xEF; //turn green LED off
    
    
    SPI_CS = CS_IDLE;//prerecord
    
    while(1){
        
        //PRE_RECORD FUNCTION
        //InitSPI();            //Start-up SPI again
        //PreRecordMode();
        //SSPCON1bits.SSPEN=0;  // Disable SPI Port
        //PORTCbits.RC5 = 0;    //Set MOSI low
        //SPI_CS = CS_IDLE;//prerecord
        //__delay_ms(5);
        
        SPI_CS = CS_IDLE;
        
        //Check Flags
        if(PORTAbits.RA1)
        {
             //Strobe LED
            PORTBbits.RB0 = 1;
            __delay_ms(100);
            PORTBbits.RB0 = 0;
        }

        if(recordFlag)
        {
          RecordMode();
          recordFlag = 0;
          __delay_ms(500); //trying to get gps to not hangup
        }

        //Not recording, Update the GPS
        if(gpsTimeoutState==0)
            UpdateGPS(); //tell GPS to send an update
        else if(gpsTimeoutState==1)
        {
            ToggleSleepGPS();
            gpsTimeoutState = 2;
        }
        else if(gpsTimeoutState==2)
        {
            ToggleSleepGPS();
            gpsTimeoutState = 3;
        }
        else if(gpsTimeoutState==3)
        {
            __delay_ms(1000);
            gpsTimeoutState = 0;
        }
        else
        {
            gpsTimeoutState = 0;
        }

        if(gpsInvalidFlag) //turn on red LED if invalid message
        {
            PORTBbits.PORTB = LATBbits.LATB | 0x20; //turn red LED on
            PORTBbits.PORTB = LATBbits.LATB & 0xEF; //turn green LED off
            __delay_ms(250);
            PORTBbits.PORTB = LATBbits.LATB & 0xDF; //turn red LED off
            if(periodicCounter < MAX_PERIOD)
                periodicCounter++;
        }
        else //turn on green LED if valid message
        {
            PORTBbits.PORTB = LATBbits.LATB | 0x10; //turn green LED on
            PORTBbits.PORTB = LATBbits.LATB & 0xDF; //turn red LED off
            __delay_ms(250);
            PORTBbits.PORTB = LATBbits.LATB & 0xEF; //turn green LED off
            periodicCounter = MIN_PERIOD;
        }
        
        if(!recordFlag)
        {
            if(PORTAbits.RA1) //check strobe
                GoToSleep(MIN_PERIOD);
            else if(gpsInvalidFlag)
                GoToSleep(periodicCounter);
            else
            {
                ToggleSleepGPS();       //Turn GPS off
                Hibernate();
                ToggleSleepGPS();       //Turn GPS on
            }
        }
        

    }

    return (EXIT_SUCCESS);
}
Example #21
0
int main(void)
{
    //STATIC_ASSERT(sizeof(uint16_t) == 2);
    InitGPIO();
    InitSPI_soft();
    InitI2C_soft();
    InitADC();
    InitSystemTimer();
    InitTimers();
    InitMessages();
    InitCC2500(preferredSettings); //(const uint8_t **)conf(+6bytes of code), preferredSettings
    uart0_init( UART_BAUD_SELECT(RS485_BAUDRATE, F_CPU) );
    //_delay_ms(5000);
    //InitEXTI();
    //MCUCR |= (_BV(ISC11) | _BV(ISC01));

    /*check Watchdog reset flag*/
    if(bit_is_set(MCUCSR, WDRF)) {
      //increase wathcdog reset counter and save in eeprom
    }

    set_sleep_mode(SLEEP_MODE_IDLE); //варианты SLEEP_MODE_PWR_SAVE SLEEP_MODE_IDLE SLEEP_MODE_ADC
    //wdt_enable(WDTO_2S);
    sei(); //enable interrupts

    for (uint8_t i = 0; i<0x05; i++) {
          //_spi_start();
          //spi_TxRx(0x9D);
          //_spi_stop();
          _delay_ms(100);
          PORTC |= _BV(PC2); //blink for test
          _delay_ms(100);
          PORTC &= ~_BV(PC2);
          _delay_ms(100);

          RS485_DE_HIGH;
          uart0_putc(0xba);
          _delay_ms(2);
          RS485_DE_LOW;
        }
        RS485_DE_LOW;

    while(1) {
      cc_table_state[CC_state]();


      ProcessTimers(&sys_timer);
      ProcessMessages();
      wdt_reset();

      /*enter in sleep mode until interrupts occured*/
//      cli(); //disable interrupts
//      if (some_condition)
//      {
//        sleep_enable();
//        sei();
//        sleep_cpu();
//        sleep_disable();
//      }
//      sei();
    }

    return 0;
}
Example #22
0
void Motor_init(void){
	InitGPIO();
}
// MAIN PROGRAM
int main(void)
{
	Board_SystemInit();
	uint8_t Giro = 0, Giro0 = 0, CloseLoop=0, Inertia=0xFF;
	//Init All
	//-----------------------------------------------------------------------------------------------
	Stop_and_Default();	//Condiciones iniciales
	InitGPIO();			//Llamo función para inicializar GPIO
	InitPWM();			//Función inicialización modulo PWM
	Start_Up_Brushless();		//Arranque del motor   **********************7777777777777777777777777777744444444444***************
	Giro=1;
	//Main Loop
	//-----------------------------------------------------------------------------------------------
	while (1)
	{
		//Lectura Pulsadores
		//-------------------------------------------------------------------------------------------
		if (Chip_GPIO_ReadPortBit(LPC_GPIO, PULS_PORT, PULS1)==0 && Chip_GPIO_ReadPortBit(LPC_GPIO, PULS_PORT, PULS2)==0)
		{
			//Detencion y valores de reinicio
			Stop_and_Default();	//Detencion del motor
			Giro = 0;			//Flag que no siga girando
			Giro0 = 0;			//Flag para arranque
			CloseLoop=0;		//Flag para lazo cerrado
			Inertia=0xFF;		//Contador para mantener velocidad hasta encontrar BEMF

			AntiRebo = REBOTE_;	//Reestablezco anti rebote
		}
		if (Chip_GPIO_ReadPortBit(LPC_GPIO, PULS_PORT, PULS1) == 0	&& AntiRebo == 0)
		{
			//Arranque Motor PWM + Period
			if (Giro0 == 0) {				//Primer pulso:
				Start_Up_Brushless();		//Arranque del motor
				Giro = 1;					//Flag que continue girando
			} else {
				if (DutyCycle > 20)
					DutyCycle = DutyCycle - 5;	//Decrementar ciclo actividad
			}
			AntiRebo = REBOTE_;	//Restablezco anti rebote
		}
		if (Chip_GPIO_ReadPortBit(LPC_GPIO, PULS_PORT, PULS2) == 0	&& AntiRebo == 0)
		{
			if (DutyCycle < 980 && Giro0 == 1)
				DutyCycle = DutyCycle + 5;	//Incremento ciclo actividad

			AntiRebo = REBOTE_;	//Restablezco anti rebote
		}
		//-------------------------------------------------------------------------------------------
		if (AntiRebo > 0)
			AntiRebo--;		//Antirebote a lo croto

		//Test PWM
		//-------------------------------------------------------------------------------------------
		if(CloseLoop==0){		//Lazo abierto
			if (Match_Cnt1>=StepPeriod && Giro)
			{
				NextPWM1();		//Conmutación
				NextPWM2();
				Giro0 = 1;		//Flag para incrementar o decrementar duty
				Inertia--;		//Contador decreciente para encontrar BEMF
				if(Inertia==0)
					CloseLoop=1;	//Final del contador -> entro en lazo cerrado
			}
		}else{					//Lazo cerrado
			//Zero_Detect1();		//Detección de cruces por cero (cincronismo)
			//Zero_Detect2();
			if(Conmutar1){
				NextPWM1();
				Conmutar1=0;
			}
			if(Conmutar2){
				NextPWM2();
				Conmutar2=0;
			}
		}
		//-------------------------------------------------------------------------------------------
		//End Test
	}
	return 1;
}
Example #24
0
int main(void)
{
    /* Configure the oscillator both devices */
    
    ConfigureOscillator();
    
    /* Initialize IO ports and peripherals for both devices */
   
    InitGPIO(); 
    InitUART();
    InitI2c();
    InitI2cCompass();
  
    /* Program for the bracelet */
    
#ifdef PROTECTED
    
    /* Initialize IO ports and peripherals */

      InitTimerUS();
 
    /* The values of the magnetic field will be save in x and y */
    s16 x = 0;
    s16 y = 0;   
    
    while(1)
    {
       I2cReadData(&x, &y);
       ComputeAngle(&angle, x, y);
       PutData16(angle);
       __delay_ms(500);
    }
    
#endif
    
    /* Program for the bodyguard*/
    
#ifdef BODY_GUARD
    

    /* Initialize IO ports and peripherals */
    InitADC();
    InitPWM();
    InitLcd();
    InitTimerServo();
    
    /* TODO <INSERT USER APPLICATION CODE HERE> */
    
    u16 ADC_values[NMB_SENSORS];
    u16 average[NMB_SENSORS];
    u8 i;
    u8 j;
    
    /* The values of the magnetic field will be save in x and y */
    s16 x = 0;
    s16 y = 0;
    
    u16 angle2=0;
    
    char T[5];
    
    
    memset(ADC_values,0x00,sizeof(ADC_values));
    memset(average, 0x00,sizeof(average));

    /*
    for(i=0; i<NMB_SENSORS; i++) 
    {
        ADC_values[i]=0;
    }*/
    LcdClear();
    
#if MAGNETIC_SENSOR    
    while(1)
    {
       I2cReadData(&x, &y);
       angle2=((-atan2(x,y)*180)/3.14)+180;
        /* Computes the angle using the arctan2 which provides an angle
        * between -180° and 180°, then converts the result that is in radian
        * into degree (*180/pi) and in the end add 180° so the angle is between
        * 0° and 360° */
       //LcdPutFloat(angle2,0);
       LcdPutFloat(angle2,0);
       LcdGoto(1,2);
       LcdPutFloat(angle,0);
       __delay_ms(500);
       LcdClear();
        
    }
#endif

#ifdef BODY_GUARD_MODE
   while(1)
    { 
        
        for(j=0; j<NMB_MEASURES; j++)
        {
            /* SENSORS SAMPLING */
            for(i=0; i<NMB_SENSORS; i++)
            {
                StartADC(ADC_values);
            }
            ObjectDetection(ADC_values, average);
        }
        LcdClear();
        
        LcdPutFloat(CCP2RB, 0);
       
        //__delay_ms(1000);
        
        LcdClear();
        
        /* Set Flags */       
        ObjectReaction(average);        
        DistanceFlag(average[US]);
        
        /* react */
        
        AutoBodyGuard();

    }
#endif
               
#ifdef AUTO_FLEE
    while(1)
    { 
        
        for(j=0; j<NMB_MEASURES; j++)
        {
            /* SENSORS SAMPLING */
            for(i=0; i<NMB_SENSORS; i++)
            {
                StartADC(ADC_values);
            }
            ObjectDetection(ADC_values, average);
        }
        LcdClear();
        
        /* Set Flags */       
        ObjectReaction(average);        
        //DistanceFlag(average[US]);
        AutoFLee();

    }
    
#endif
#endif
    return 0;
}
Example #25
0
void I2C::AutoRecover()
{
    //save registers

    //cr1
    bool isAck = (*_pI2C_CR1  & I2C_CR1_ACK);
    //isAck = true;
    bool isENARP = (*_pI2C_CR1  & I2C_CR1_ENARP);
    bool isENPEC = (*_pI2C_CR1  & I2C_CR1_ENPEC);
    bool isENGC = (*_pI2C_CR1  & I2C_CR1_ENGC);

    uint16_t cr2 = *_pI2C_CR2;
    uint16_t oar1 = *_pI2C_OAR1;
    uint16_t oar2 = *_pI2C_OAR2;
    uint16_t ccr = *_pI2C_CCR;
    uint16_t trise = *_pI2C_TRISE;

    if (_stuckBUSY)
    {
        ClearBUSY();
    }

    /*
    Initialize(100000, false, false);



    SetModeI2C();
    EnableACK(true);
    SetOwnAddr7Bit(0x00);
    return;
     */


    Enable(false);
    SetSoftwareReset(true);
    SetSoftwareReset(false);
    EnablePeripheralClock(true);

    InitGPIO();


    //restore registers;

    EnableACK(isAck);
    EnableARP(isENARP);
    EnablePEC(isENPEC);
    EnableGeneralCall(isENGC);

    *_pI2C_CR2 = cr2;
    *_pI2C_OAR1 = oar1;
    *_pI2C_OAR2 = oar2;
    *_pI2C_CCR = ccr;
    *_pI2C_TRISE = trise;

    _stuckBUSY = false;

    Enable(true);


}
Example #26
0
BOOL CSDHControllerCh1::InitCh() {
    if (!InitClkPwr()) return FALSE;
    if (!InitGPIO()) return FALSE;
    if (!InitHSMMC()) return FALSE;
    return TRUE;
}
Example #27
0
int main(void)
{
  int LogOn = 0;
  int ComOn = 0;
  int dT;
  int16_t data[32];
  uint32_t x;
  UINT cnt;

  InitSystemTick();
  InitGPIO();
  InitTimer();
  STM_EVAL_LEDOn(LED4);

  InitUART(115200);
  InitPressureSensor();
  InitFlowMeter();

  InitAccAndMag();
  InitGyro();

  STM_EVAL_LEDOn(LED7); // zapnem LED7 - zelena

  Delta_us();
  while(1)
  {
    // sample period is time elapsed since previous sampling of sensors
    sampleSensors(a,m,g);
    // update timebase for next time
    dT = Delta_us();
    samplePeriod = 0.000001f * dT;
    // convert gyro deg/s to rad/s
    imuDegToRadV3(g);
    // update AHRS
    MadgwickFullAHRSUpdate(g, a, m, samplePeriod, quaternion);

    if (LogOn) {
      sprintf(text, "%5d%6d%6d%6d%7d%7d%7d%5d%5d%5d\r\n",
              dT,
              aRawData[0], aRawData[1], aRawData[2],
              gRawData[0], gRawData[1], gRawData[2],
              mRawData[0], mRawData[1], mRawData[2]);
      f_write(&File, text, strlen(text), &cnt);
    }

    if(STM_EVAL_PBGetState(BUTTON_USER)) {   // zmena rezimu vystupu
      if (LogOn) {
        // Stop logdata
        LogOn = 0;
        STM_EVAL_LEDOff(LED5); // zapnem LED7 - zelena
        if (f_close(&File) == 0)
          xprintf("Stop login data.\n\r");
        else
          xprintf("Error write datafile.\n\r");
      } else {
        // Start logdata
        if (newFile() == 0)
          xprintf("Start login data.\n\r");
        else
          xprintf("Error create datafile.\n\r");
        STM_EVAL_LEDOn(LED5); // zapnem LED7 - zelena
        LogOn = 1;
      }
    }

    if (ComOn) {
      data[0] = dT;
      data[1] = aRawData[0];
      data[2] = aRawData[1];
      data[3] = aRawData[2];
      data[4] = gRawData[0];
      data[5] = gRawData[1];
      data[6] = gRawData[2];
      data[7] = mRawData[0];
      data[8] = mRawData[1];
      data[9] = mRawData[2];
      data[10] = 0x8080;
      SendDataUART((uint8_t*) data, 22);
    }

    if (IsReceiveUART()) {
      if (ReadByteUART() == 's') {
        STM_EVAL_LEDOn(LED10); // zapnem LED7 - zelena
        ComOn = 1;
      } else {
        STM_EVAL_LEDOff(LED10); // zapnem LED7 - zelena
        ComOn = 0;
      }
    }
/*
    if (x = GetFlowMeter()) {
      printf("Flow: %d\n\r", x);
    }
*/
  }
}
Example #28
0
int main(void)
{

	/* Init board */
	BoardInit();

	/* Init GPIO */
	InitGPIO();

	/* Init UART */
	MAP_PRCMPeripheralClkEnable(PRCM_UARTA0, PRCM_RUN_MODE_CLK);
    InitTerm();

    /* Init I2C */
    I2C_IF_Open(I2C_MASTER_MODE_FST);

    /* Init the internet! */
    // http://azug.minpet.unibas.ch/~lukas/bricol/ti_simplelink/resources/swru368.pdf SECTION 10
	dhcpParams.lease_time = 1000;
	dhcpParams.ipv4_addr_start = 0xc0a80102;
	dhcpParams.ipv4_addr_last = 0xc0a801fe;


	sl_Start(NULL,NULL,NULL);
	MAP_UtilsDelay(8000000);

	// config IP etc
	ipV4.ipV4 = 0xc0a80101;
	ipV4.ipV4Mask = 0xFFFFFF00;
	ipV4.ipV4Gateway = 0xc0a80101;
	ipV4.ipV4DnsServer = 0xc0a80101;
	sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, 1 ,sizeof(SlNetCfgIpV4Args_t), (unsigned char*) &ipV4);

	sl_WlanSetMode(ROLE_AP);

	// config SSID
	sl_WlanSet(SL_WLAN_CFG_AP_ID,WLAN_AP_OPT_SSID, strlen(myssid), (unsigned char*) myssid);

	sl_Stop(100);
	sl_Start(NULL,NULL,NULL);

	// start DHCP server
	sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID);
	sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, outLen,(unsigned char*) &dhcpParams);
	sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID);


	//Stop Internal HTTP Serve
	long lRetVal = -1;
	lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
	ASSERT_ON_ERROR( lRetVal);

	//Start Internal HTTP Server
	lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
	ASSERT_ON_ERROR( lRetVal);

	 /* Finished init the internet! */

	setRLED();

    /* Wait for operator */
    while(!readDIP1());

    clearRLED();

    /* Init IMU (alongside timers and interrupt */
    imu_setup();

    /* Init odometers */
    odometer_setup();

    set_controller_parameters(kp, ki, kd);
    set__odo_controller_parameters(kp_odo, ki_odo, kd_odo);

    /* Init motors (alongside motor GPIO, timers and interrupt */
	motorSetup();



    controller_setup();
    odometer_controller_setup();      // MUST be the last init called!


	while(1)
	{
		_SlNonOsMainLoopTask();
	}
}