示例#1
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Reset of all peripherals and Initialize the Systick. */
  HAL_Init();

  /* Configure the system clock to 180 MHz */
  SystemClock_Config();
  
  /* Set the Vector Table base location at 0x08004000 
    (this is already done in system_stm32f4xx.c file) */ 
  
  /* Add your own code here...    
    */

  /* Initialize Leds mounted on STM32469I_EVAL board */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED4);

  /* Turn on LED1 and LED3 */
  BSP_LED_On(LED1);
  BSP_LED_On(LED3);

  /* Setup SysTick Timer for 1 msec interrupts.
     ------------------------------------------
    1. The SysTick_Config() function is a CMSIS function which configure:
       - The SysTick Reload register with value passed as function parameter.
       - Configure the SysTick IRQ priority to the lowest value (0x0F).
       - Reset the SysTick Counter register.
       - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
       - Enable the SysTick Interrupt.
       - Start the SysTick Counter.
    
    2. You can change the SysTick Clock source to be HCLK_Div8 by calling the
       SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8) just after the
       SysTick_Config() function call. The SysTick_CLKSourceConfig() is defined
       inside the misc.c file.

    3. You can change the SysTick IRQ priority by calling the
       NVIC_SetPriority(SysTick_IRQn,...) just after the SysTick_Config() function 
       call. The NVIC_SetPriority() is defined inside the core_cm3.h file.

    4. To adjust the SysTick time base, use the following formula:
                            
         Reload Value = SysTick Counter Clock (Hz) x  Desired Time base (s)
    
       - Reload Value is the parameter to be passed for SysTick_Config() function
       - Reload Value should not exceed 0xFFFFFF
   */
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* Capture error */ 
    while (1)
    {}
  }

  while (1)
  {
    /* Toggle LED2 and LED4 */
    BSP_LED_Toggle(LED2);
    BSP_LED_Toggle(LED4);

    /* Insert 50 ms delay */
    HAL_Delay(50);

    /* Toggle LED1 and LED3 */
    BSP_LED_Toggle(LED1);
    BSP_LED_Toggle(LED3);

    /* Insert 100 ms delay */
    HAL_Delay(100);
  }
}
示例#2
0
文件: main.c 项目: phaltness/32f4
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
//	int c;
   /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */     
    SystemInit();
	RCC_GetClocksFreq(&RCC_Clocks);
    SysTick_Config(SystemCoreClock / SYSTICK_FREQUENCY_HZ);

#ifdef TRACEUART
    TRACEUART_Configuration();
#endif //TRACEUART
	UART_Configuration();

	LED_Init();

	/* Output a message on Hyperterminal using printf function */
	printf("\n\r\n\r");
	printf("*** LATTICE FW LOADER V1.00 Build by phalt on ("__DATE__ "-" __TIME__ ")\n\r");
	printf("*** LATTICE FW LOADER V1.00 Rebooting ...\n\r");

	/*
     * wait for a keystroke (or a button press if you want.)
	*/
//    printf("\n\rPress Return to start, any other key To Enter the Console ...\n\r");
//	c = awaitkey(DEFAULT_BOOT_DELAY);
	if(1) 			//(((c != '\r') && (c != '\n') && (c != '\0')))
    {
		Delay(500);
		GPIO_ResetBits(BLINK_PORT, (0xF << LED1));
//		traceprintf("\rtrace start OK\n\r");
//		Codec_GPIO_Init();
//		Delay(1);
//		/* Reset the Codec Registers */
//		Codec_Reset();
//		Delay(1);
//		/* Initialize the Control interface of the Audio Codec */
//		Codec_CtrlInterface_Init();
//		Delay(1);
		if(1)
		{
	        GPIO_SetBits(BLINK_PORT, (0xF << LED1));
//	        WavePlayBack(AUDIOFREQ, 1);
	        WavePlayerInit(AUDIOFREQ);
	        GPIO_ResetBits(BLINK_PORT, (0xF << LED1));
		}
		while(1)						//eugene loop
		{
//			Codec_CtrlInterface_Init();
			GPIO_SetBits(BLINK_PORT, (0x1 << LED1));
//			Codec_Write();
			Codec_ReadRegister(0x00); //test read of codec
			GPIO_ResetBits(BLINK_PORT, (0x1 << LED1));
			Delay(1000);
		}

		if(1)									//test
		{
			init_builtin_cmds();
			serial_term();
		}


    }
	printf("*** JUMP to Application now ...\n\r");
    run_app(0x08000000);



    /* Infinite loop */
	while (1);
}
/**
  * @brief  Initializes the System Timer and its interrupt, and starts the System Tick Timer.
  *         Counter is in free running mode to generate periodic interrupts.
  * @param  TicksNumb: Specifies the ticks Number of ticks between two interrupts.
  * @retval status:  - 0  Function succeeded.
  *                  - 1  Function failed.
  */
uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb)
{
   return SysTick_Config(TicksNumb);
}
示例#4
0
void init() {
	GPIO_InitTypeDef  GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	DAC_InitTypeDef  DAC_InitStructure;

	// ---------- SysTick timer -------- //
	if (SysTick_Config(SystemCoreClock / 1000)) {
		// Capture error
		while (1){};
	}

	// GPIOD Periph clock enable
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

	// Configure PD12, PD13, PD14 and PD15 in output pushpull mode
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13| GPIO_Pin_14| GPIO_Pin_15;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOD, &GPIO_InitStructure);
	// Configure PA1 (push button) in input mode
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	// ------ UART ------ //

	// Clock
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

	// IO
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
	GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);

	// Conf
	USART_InitStructure.USART_BaudRate = 115200;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	USART_Init(USART2, &USART_InitStructure);

	// Enable
	USART_Cmd(USART2, ENABLE);


	// ---------- DAC ---------- //

	// Clock
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

	// Configuration
	DAC_InitStructure.DAC_Trigger = DAC_Trigger_None;
	DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_None;
	DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Disable;
	DAC_Init(DAC_Channel_1, &DAC_InitStructure);

	// IO
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	// Enable DAC Channel1
	DAC_Cmd(DAC_Channel_1, ENABLE);

	// Set DAC Channel1 DHR12L register
	DAC_SetChannel1Data(DAC_Align_12b_R, 0);
}
示例#5
0
/**
 * @brief	Main routine for WWDT example
 * @return	Nothing
 */
int main(void)
{
	uint32_t wdtFreq;

	/* Board Setup */
	Board_Init();

	/* Initialize WWDT (also enables WWDT clock) */
	Chip_WWDT_Init(LPC_WWDT);

	/* Prior to initializing the watchdog driver, the clocking for the
	   watchdog must be enabled. This example uses the watchdog oscillator
	   set at a 50KHz (1Mhz / 20) clock rate. */
	Chip_SYSCTL_PowerUp(SYSCTL_POWERDOWN_WDTOSC_PD);
	Chip_Clock_SetWDTOSC(WDTLFO_OSC_1_05, 20);

	/* The WDT divides the input frequency into it by 4 */
	wdtFreq = Chip_Clock_GetWDTOSCRate() / 4;

	/* LPC1102/4, LPC11XXLV, and LPC11CXX devices select the watchdog
	   clock source from the SYSCLK block, while LPC11AXX, LPC11EXX, and
	   LPC11UXX devices select the clock as part of the watchdog block. */
	/* Select watchdog oscillator for WDT clock source */
#if defined(CHIP_LPC110X) || defined(CHIP_LPC11XXLV) || defined(CHIP_LPC11CXX) || defined(CHIP_LPC11EXX)
	Chip_Clock_SetWDTClockSource(SYSCTL_WDTCLKSRC_WDTOSC, 1);
#else
	Chip_WWDT_SelClockSource(LPC_WWDT, WWDT_CLKSRC_WATCHDOG_WDOSC);
#endif

	Board_LED_Set(0, false);

	/* Set watchdog feed time constant to approximately 2s
	   Set watchdog warning time to 512 ticks after feed time constant
	   Set watchdog window time to 3s */
	Chip_WWDT_SetTimeOut(LPC_WWDT, wdtFreq * 2);
#if !defined(CHIP_LPC11CXX)
	Chip_WWDT_SetWarning(LPC_WWDT, 512);
	Chip_WWDT_SetWindow(LPC_WWDT, wdtFreq * 3);
#endif

#if !defined(CHIP_LPC11CXX)
	/* Configure WWDT to reset on timeout */
	Chip_WWDT_SetOption(LPC_WWDT, WWDT_WDMOD_WDRESET);
#endif

	/* Setup Systick to feed the watchdog timer. This needs to be done
	 * at a rate faster than the WDT warning. */
	SysTick_Config(Chip_Clock_GetSystemClockRate() / 50);

	/* Clear watchdog warning and timeout interrupts */
#if !defined(CHIP_LPC11CXX)	
	Chip_WWDT_ClearStatusFlag(LPC_WWDT, WWDT_WDMOD_WDTOF | WWDT_WDMOD_WDINT);
#else
	Chip_WWDT_ClearStatusFlag(LPC_WWDT, WWDT_WDMOD_WDTOF);
#endif	

	/* Clear and enable watchdog interrupt */
	NVIC_ClearPendingIRQ(WDT_IRQn);
	NVIC_EnableIRQ(WDT_IRQn);

	/* Start watchdog */
	Chip_WWDT_Start(LPC_WWDT);

	/* Idle while waiting */
	while (1) {
		__WFI();
	}
}
示例#6
0
void SysTim_Config(void)
{
  RCC_ClocksTypeDef RCC_Clocks;
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);  
}
示例#7
0
int main(void)
{
	static char ledsta;
	/***********************************/
	SystemClock_HSI(9);           //系统时钟初始化,时钟源内部HSI
	cycleCounterInit();				    // Init cycle counter
	SysTick_Config(SystemCoreClock / 1000);	//SysTick开启系统tick定时器并初始化其中断,1ms
	UART1_init(SysClock,uart1baudSet); //串口1初始化
  NVIC_INIT();	                //中断初始化
  STMFLASH_Unlock();            //内部flash解锁
  LoadParamsFromEEPROM();				//加载系统参数配置表
  LedInit();	                  //IO初始化
  Adc_Init();										//摇杆AD初始化
	KeyInit();										//按键初始化
 	NRF24L01_INIT();              //NRF24L01初始化
  SetTX_Mode();                 //设无线模块为接收模式
  controlClibra();							//遥控摇杆校准
#ifdef UART_DEBUG  
	TIM3_Init(SysClock,2000);			//定时器初始化,1s为周期打印摇杆值
#endif
	TIM4_Init(SysClock,TIME4_Preiod);	  //定时器4初始化,定时时间单位:(TIME4_Preiod)微秒
	
	LedSet(led2,1);
	LedSet(led3,1);
	
	LoadRCdata();                //摇杆赋值
	//RockerUnlockcrazepony();	 //摆杆启动
  Lockflag = 0;								 //解锁标志,1表示产生了一次按键操作,0表示该按键操作已经发送到飞控
	
  LedSet(led2,0);
	LedSet(led3,0);
	 
  while (1)             
	{ 
		//10Hz loop
		if(flag10Hz == 1)  //10Hz 
		{		
			flag10Hz = 0;
			/*status led*/
			ledsta = !ledsta;
			LedSet(signalLED,ledsta);				        
			/*crazepony Lock*/
			KeyLockcrazepony();
			/*IMUcalibrate  */
			IMUcalibrate();
			/*remote calibrate*/
			Remotecalibrate();
		}

		//50Hz loop
		if(flag50Hz == 1)
		{
			LoadRCdata();
			flag50Hz = 0;
			
		}
		
		// 80Hz 12.5ms
		if(flag80Hz)
		{
			flag80Hz = 0;
			CommUAVUpload(MSP_SET_4CON);   
		}
	}
}
示例#8
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  int      toggleLED = 0;
  bool     redraw = false;
  EMSTATUS status;
  GLIB_Rectangle_t rect = {
    .xMin =   0,
    .yMin =   0,
    .xMax = 319,
    .yMax = 239,
  };

  /* Use 48MHZ HFXO as core clock frequency */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  /* This demo currently only works in EBI mode */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000))
  {
    while (1) ;
  }

  /* Wait until we have control over display */
  while(!redraw)
  {
    redraw = TFT_AddressMappedInit();
  }

  /* Init graphics context - abort on failure */
  status = GLIB_contextInit(&gc);
  if (status != GLIB_OK) while (1) ;

  /* Clear framebuffer */
  gc.foregroundColor = GLIB_rgbColor(20, 40, 20);
  GLIB_drawRectFilled(&gc, &rect);

  /* Update TFT display forever */
  while (1)
  {
    /* Check if we should control TFT display instead of AEM/board controller */
    redraw = TFT_AddressMappedInit();
    if(redraw)
    {
      /* Update display */
      TFT_displayUpdate(&gc);
    }
    else
    {
      /* No need to refresh display when BC is active */
      Delay(200);
    }
    /* Toggle led after each TFT_displayUpdate iteration */
    if (toggleLED)
    {
      BSP_LedsSet(0x0000);
      toggleLED = 0;
    }
    else
    {
      BSP_LedsSet(0x000f);
      toggleLED = 1;
    }
  }
}
示例#9
0
int main () {

	CHIP_Init();				//Initialize Chip

	initMCU();
	initGPIO();				//Initialize GPIO
	sdi2c_Init();				//Initialize I2C
	initTimer();		//initialize timer for timer interuprt

	/* Setup SysTick Timer for 10 msec interrupts  */
	if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000)) {
	while (1) ;
	}

	/*Enable all sensors and GPS */
	GPIO_PinOutSet(GPS_PORT, ENABLE);			//Enable GPS Sensor board
	BMP180_GetCalData();		//Enable and get calibration data from BMP180
	initLSM303_LowPower();		//Enable Accel in low power mode
	initL3GD20H_Normal();			//Enable Gyro in normal mode
	GPIO_PinOutToggle(EXT_LED, YEL_LED);

	/* Acceleromter Data */
	Delay(10);
	LSM303_GetAccelData();
	LSM303_PowerOff();
	GPIO_PinOutToggle(EXT_LED, YEL_LED);

	/*Gyroscope Data */
	Delay(10);
	L3GD20H_GetGyroData();
	L3GD20H_PowerOff();
	GPIO_PinOutToggle(EXT_LED, YEL_LED);

	/*Temperature/Barometric Pressure */
	Delay(10);
	BMP180_GetTemp();
	BMP180_GetPressure();
	BMP180_CalcRealTemperature();
	BMP180_CalcRealPressure();
	GPIO_PinOutToggle(EXT_LED, YEL_LED);

	/*Power Sensor*/
	INA219_GetVoltage();
	GPIO_PinOutClear(EXT_LED, YEL_LED);

	GPIO_PinOutToggle(EXT_LED, GRE_LED);
	Delay(100);
	GPIO_PinOutToggle(EXT_LED, GRE_LED);


	/* GPS Information */
	timeout = 0;		//reset timeout
	initGPS();		//Initialize GPS UART
	coldrestart();		//Send cold restart command
	while(fullread == 0) {		//while not a full read, do the following
		if(satfix == 1) {			//if there is a satellite fix, then...
			GPIO_PinOutSet(EXT_LED, YEL_LED);		//toggle LED for debug
			readdata();		//readdata
			timeout = 0;
		}
		if(timeout > 20) {
			GPIO_PinOutClear(EXT_LED, YEL_LED);
			GPStimeout();
			break;
		}
	}

	GPIO_PinOutSet(EXT_LED, GRE_LED);
	Delay(500);

	printGPS(0);		//Print GPS to screen for debug

	concact();


	/* Infinite loop */
	while(1) {
	  if(GPIO_PinInGet(BUT_PORT, RIGHT_BUT) == 0) {
		  r = r + 1;
		  if(r > 2) {		//wrap around to beginning
			  r = 0;
		  }
		  printGPS(r);
	  }
	  if(GPIO_PinInGet(BUT_PORT, LEFT_BUT) == 0) {
			  r = r - 1;
			  if(r < 0) {		//wrap around to beginning
				  r = 2;
			  }
			  printSENSORS();
		  }
//	  if(GPIO_PinInGet(GPS_PORT, FIX) == 1) {
//		  GPIO_PinOutToggle(EXT_LED, RED_LED);
//	  }
	}
}
示例#10
0
void init( void )
{
  SystemInit();

  // Set Systick to 1ms interval, common to all SAM3 variants
  if (SysTick_Config(SystemCoreClock / 1000))
  {
    // Capture error
    while (true);
  }

  // Disable watchdog
  //WDT_Disable(WDT);
  // Initialize C library
  __libc_init_array();

  // Disable pull-up on every pin
  for (int i = 0; i < PINS_COUNT; i++)
      digitalWrite(i, LOW);

  // Enable parallel access on PIO output data registers
  PIOA->PIO_OWER = 0xFFFFFFFF;
  PIOB->PIO_OWER = 0xFFFFFFFF;
  PIOC->PIO_OWER = 0xFFFFFFFF;
  PIOD->PIO_OWER = 0xFFFFFFFF;

  // Initialize Serial port U(S)ART pins
  PIO_Configure(
    g_APinDescription[PINS_UART].pPort,
    g_APinDescription[PINS_UART].ulPinType,
    g_APinDescription[PINS_UART].ulPin,
    g_APinDescription[PINS_UART].ulPinConfiguration);
  digitalWrite(0, HIGH); // Enable pullup for RX0
  PIO_Configure(
    g_APinDescription[PINS_USART0].pPort,
    g_APinDescription[PINS_USART0].ulPinType,
    g_APinDescription[PINS_USART0].ulPin,
    g_APinDescription[PINS_USART0].ulPinConfiguration);
  PIO_Configure(
    g_APinDescription[PINS_USART1].pPort,
    g_APinDescription[PINS_USART1].ulPinType,
    g_APinDescription[PINS_USART1].ulPin,
    g_APinDescription[PINS_USART1].ulPinConfiguration);
  PIO_Configure(
    g_APinDescription[PINS_USART3].pPort,
    g_APinDescription[PINS_USART3].ulPinType,
    g_APinDescription[PINS_USART3].ulPin,
    g_APinDescription[PINS_USART3].ulPinConfiguration);

  // Initialize USB pins
  PIO_Configure(
    g_APinDescription[PINS_USB].pPort,
    g_APinDescription[PINS_USB].ulPinType,
    g_APinDescription[PINS_USB].ulPin,
    g_APinDescription[PINS_USB].ulPinConfiguration);

  // Initialize CAN pins
  PIO_Configure(
    g_APinDescription[PINS_CAN0].pPort,
    g_APinDescription[PINS_CAN0].ulPinType,
    g_APinDescription[PINS_CAN0].ulPin,
    g_APinDescription[PINS_CAN0].ulPinConfiguration);
  PIO_Configure(
    g_APinDescription[PINS_CAN1].pPort,
    g_APinDescription[PINS_CAN1].ulPinType,
    g_APinDescription[PINS_CAN1].ulPin,
    g_APinDescription[PINS_CAN1].ulPinConfiguration);

  // Initialize Analog Controller
  pmc_enable_periph_clk(ID_ADC);
  adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
  adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1);
  adc_configure_trigger(ADC, ADC_TRIG_SW, 0); // Disable hardware trigger.
  adc_disable_interrupt(ADC, 0xFFFFFFFF); // Disable all ADC interrupts.
  adc_disable_all_channel(ADC);

  // Initialize analogOutput module
  analogOutputInit();
}
示例#11
0
文件: main.c 项目: DanMills/j4cDAC
int main(int argc, char **argv) {
	time = 0;

	int i;

	SysTick_Config(SystemCoreClock / 10000);
	serial_init();

	/* LEDs */
	LPC_GPIO0->FIODIR |= (1 << 0);
	LPC_GPIO1->FIODIR |= (1 << 28);
	LPC_GPIO1->FIOSET = (1 << 28);
	LPC_GPIO1->FIODIR |= (1 << 29);

	outputf("=== j4cDAC ===");

	outputf("skub_init()");
	skub_init();

	outputf("lwip_init()");
	lwip_init();

	outputf("== hardware ==");

	for (i = 0; i < TABLE_LENGTH(hardware); i++) {
		outputf("%s()", hardware_table[i].name);
		hardware_table[i].f();
	}

	outputf("== protocol ==");

	for (i = 0; i < TABLE_LENGTH(protocol); i++) {
		outputf("%s()", protocol_table[i].name);
		protocol_table[i].f();
	}

	outputf("ilda player");
	ilda_open("ildatest.ild");

	outputf("Entering main loop...");

/*
	playback_src = SRC_ILDAPLAYER;
	playback_source_flags = ILDA_PLAYER_PLAYING | ILDA_PLAYER_REPEAT;
*/

	__enable_irq();

	int status = 0;

	for (i = 0; i < (sizeof(events) / sizeof(events[0])); i++) {
		events_last[i] = events[i].start + time;
	}

	dac_set_rate(12000);
	ilda_set_fps_limit(30);

	while (1) {
		/* If we're playing from something other than the network,
		 * refill the point buffer. */
		if (playback_src != SRC_NETWORK)
			playback_refill();

		if (!(LPC_GPIO1->FIOPIN & (1 << 26))) {
			outputf("Blocking...");
			while (!(LPC_GPIO1->FIOPIN & (1 << 26)));
		}


//		LPC_GPIO1->FIOCLR = (1 << 28);

		if (status) {
			LPC_GPIO0->FIOPIN = 1;
			LPC_GPIO1->FIOPIN = 0;
			status = 0;
		} else {
			LPC_GPIO0->FIOPIN = 0;
			LPC_GPIO1->FIOPIN = (1 << 29);
			status = 1;
		}

//		LPC_GPIO1->FIOSET = (1 << 28);

		/* Check for periodic events */
		for (i = 0; i < (sizeof(events) / sizeof(events[0])); i++) {
			if (time > events_last[i] + events[i].period) {
				events[i].f();
				events_last[i] += events[i].period;
			}
		}

		/* Check the stuff we check on each loop iteration. */
		for (i = 0; i < TABLE_LENGTH(poll); i++) {
			poll_table[i].f();
		}
	}
}
示例#12
0
/**
 *  \brief DAC Sinewave application entry point.
 *
 *  \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint8_t uc_key;
	uint32_t ul_freq, ul_amp;

	/* Initialize the system */
	sysclk_init();
	board_init();

	/* Initialize debug console */
	configure_console();

	/* Output example information */
	puts(STRING_HEADER);

	/* Enable clock for DACC */
#if SAM4L
	sysclk_enable_peripheral_clock(DACC_BASE);
#else
	sysclk_enable_peripheral_clock(DACC_ID);
#endif

	/* Reset DACC registers */
	dacc_reset(DACC_BASE);

	/* Half word transfer mode */
	dacc_set_transfer_mode(DACC_BASE, 0);

	/* Initialize timing, amplitude and frequency */
#if (SAM3N) || (SAM4L) || (SAM4N)
	/* Timing:
	 * startup                - 0x10 (17 clocks)
	 * internal trigger clock - 0x60 (96 clocks)
	 */
	dacc_set_timing(DACC_BASE, 0x10, 0x60);

	/* Enable DAC */
	dacc_enable(DACC_BASE);
#else
	/* Power save:
	 * sleep mode  - 0 (disabled)
	 * fast wakeup - 0 (disabled)
	 */
	dacc_set_power_save(DACC_BASE, 0, 0);
	/* Timing:
	 * refresh        - 0x08 (1024*8 dacc clocks)
	 * max speed mode -    0 (disabled)
	 * startup time   - 0x10 (1024 dacc clocks)
	 */
	dacc_set_timing(DACC_BASE, 0x08, 0, 0x10);

	/* Disable TAG and select output channel DACC_CHANNEL */
	dacc_set_channel_selection(DACC_BASE, DACC_CHANNEL);

	/* Enable output channel DACC_CHANNEL */
	dacc_enable_channel(DACC_BASE, DACC_CHANNEL);

	/* Set up analog current */
	dacc_set_analog_control(DACC_BASE, DACC_ANALOG_CONTROL);
#endif /* (SAM3N) */

	g_l_amplitude = MAX_AMPLITUDE / 2;
	g_ul_frequency = DEFAULT_FREQUENCY;

	SysTick_Config(sysclk_get_cpu_hz() / (g_ul_frequency * SAMPLES));

	/* Main menu */
	display_menu();

	while (1) {
		usart_serial_getchar((Usart *)CONSOLE_UART, &uc_key);

		switch (uc_key) {
		case '0':
			printf("Frequency:\t");
			ul_freq = get_input_value(MIN_FREQUENCY, MAX_FREQUENCY);
			printf("\r\n");

			if (ul_freq != VAL_INVALID) {
				printf("Set frequency to : %luHz\n\r", (unsigned long)ul_freq);
				SysTick_Config(sysclk_get_cpu_hz() / (ul_freq * SAMPLES));
				g_ul_frequency = ul_freq;
			}
			break;

		case '1':
			printf("Amplitude:\t");
			ul_amp = get_input_value(MIN_AMPLITUDE, MAX_AMPLITUDE);
			printf("\r\n");
			if (ul_amp != VAL_INVALID) {
				printf("Set amplitude to : %lu\n\r", (unsigned long)ul_amp);
				g_l_amplitude = ul_amp;
			}
			break;

		case 'i':
		case 'I':
			printf("-I- Frequency : %lu Hz Amplitude : %ld\n\r",
				(unsigned long)g_ul_frequency, (long)g_l_amplitude);
			break;

		case 'w':
		case 'W':
			printf("-I- Switch wave to : %s\n\r", g_uc_wave_sel ?
				"SINE" : "Full Amplitude SQUARE");
			g_uc_wave_sel = (g_uc_wave_sel + 1) & 1;
			break;

		case 'm':
		case 'M':
			display_menu();
			break;
		}
		puts("Press \'m\' or \'M\' to display the main menu again!\r");
	}
}
示例#13
0
文件: main.c 项目: jwag/BCI
//***************************************************************************************
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
        system_stm32f4xx.c file
     */

  /* Initialize Leds mounted on STM32F4-Discovery board */
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);

  init_USART1(9600); // initialize USART1 @ 9600 baud

  char hello[]  = "Init complete! Hello World!/n";
  USART_puts_chars(USART1, hello); // just send a message to indicate that it works


  /* ADC3 configuration *******************************************************/
  /*  - Enable peripheral clocks                                              */
  /*  - DMA2_Stream0 channel2 configuration                                   */
  /*  - Configure ADC Channel12 pin as analog input                           */
  /*  - Configure ADC3 Channel12                                              */
  ADC3_CH12_DMA_Config();

  /* Start ADC3 Software Conversion */
  ADC_SoftwareStartConv(ADC3);

  DMA_ITConfig(DMA2_Stream0,DMA_IT_TC,ENABLE);

  /* TIM Configuration */
  TIM_Config();

  PWM_Config();

  /* Setup SysTick Timer for 1 msec interrupts.
     ------------------------------------------
    1. The SysTick_Config() function is a CMSIS function which configure:
       - The SysTick Reload register with value passed as function parameter.
       - Configure the SysTick IRQ priority to the lowest value (0x0F).
       - Reset the SysTick Counter register.
       - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
       - Enable the SysTick Interrupt.
       - Start the SysTick Counter.

    2. You can change the SysTick Clock source to be HCLK_Div8 by calling the
       SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8) just after the
       SysTick_Config() function call. The SysTick_CLKSourceConfig() is defined
       inside the misc.c file.

    3. You can change the SysTick IRQ priority by calling the
       NVIC_SetPriority(SysTick_IRQn,...) just after the SysTick_Config() function
       call. The NVIC_SetPriority() is defined inside the core_cm4.h file.

    4. To adjust the SysTick time base, use the following formula:

         Reload Value = SysTick Counter Clock (Hz) x  Desired Time base (s)

       - Reload Value is the parameter to be passed for SysTick_Config() function
       - Reload Value should not exceed 0xFFFFFF
   */
  if (SysTick_Config(SystemCoreClock / (6250)))
  {
    /* Capture error */
    while (1);
  }

  set_PWM_duty( 75, LEFT_LED_880);
  static uint8_t duty_cycle = 0;
  while (1)
  {
    /* Toggle LED3 and LED6 */
    //STM_EVAL_LEDToggle(LED3);
    //Delay(100);
    STM_EVAL_LEDToggle(LED4);
    Delay(100);
    STM_EVAL_LEDToggle(LED6);
    Delay(100);
    STM_EVAL_LEDToggle(LED5);
    Delay(100);
  }
}
示例#14
0
void SystickTimer(unsigned long tick){
	SysTick_Config(SystemCoreClock/1000);
	unsigned long systickcnt;
	systickcnt = SysTickCnt;
	while ((SysTickCnt - systickcnt) < tick);
}
示例#15
0
/**
  * @brief  ADC configuration.
  * @param  None
  * @retval None
  */
static void ADC_Config(void)
{
  __IO uint16_t calibration_value = 0x00;
  
  ADC_InitTypeDef   ADC_InitStructure;
  ADC_CommonInitTypeDef ADC_CommonInitStructure;  
  NVIC_InitTypeDef  NVIC_InitStructure;

  /* Configure the ADC clock */
  RCC_ADCCLKConfig(RCC_ADC12PLLCLK_Div1);
  
  /* Enable ADC1 clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ADC12, ENABLE);

  /* Setup SysTick Timer for 1 µsec interrupts  */
  if (SysTick_Config(SystemCoreClock / 1000000))
  { 
    /* Capture error */ 
    while (1)
    {}
  }  
  
  /* ADC Channel3 configuration */
   /* GPIO PA0 configuration is done within OPAMP_Config function
      as the ADC channel3 is the OPAMP1 output*/
  
  ADC_StructInit(&ADC_InitStructure);

  /* Calibration procedure */
  ADC_VoltageRegulatorCmd(ADC1, ENABLE);
  
  /* Insert delay equal to 10 µs */
  Delay(10);
  
  ADC_SelectCalibrationMode(ADC1, ADC_CalibrationMode_Single);
  ADC_StartCalibration(ADC1);
  
  while(ADC_GetCalibrationStatus(ADC1) != RESET );
  calibration_value = ADC_GetCalibrationValue(ADC1);

  /* Configure the ADC1 in continuous mode */
  ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;                                                                    
  ADC_CommonInitStructure.ADC_Clock = ADC_Clock_AsynClkMode;                    
  ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;             
  ADC_CommonInitStructure.ADC_DMAMode = ADC_DMAMode_OneShot;                  
  ADC_CommonInitStructure.ADC_TwoSamplingDelay = 0;      
  ADC_CommonInit(ADC1, &ADC_CommonInitStructure);
  
  ADC_InitStructure.ADC_ContinuousConvMode = ADC_ContinuousConvMode_Enable;
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b; 
  ADC_InitStructure.ADC_ExternalTrigConvEvent = ADC_ExternalTrigConvEvent_0;         
  ADC_InitStructure.ADC_ExternalTrigEventEdge = ADC_ExternalTrigEventEdge_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_OverrunMode = ADC_OverrunMode_Disable;
  ADC_InitStructure.ADC_AutoInjMode = ADC_AutoInjec_Disable;  
  ADC_InitStructure.ADC_NbrOfRegChannel = 1;
  ADC_Init(ADC1, &ADC_InitStructure);
  
  /* ADC1 regular channel3 configuration */ 
  ADC_RegularChannelConfig(ADC1, ADC_Channel_3, 1, ADC_SampleTime_1Cycles5);
  
  /* Enable EOC interrupt */
  ADC_ITConfig(ADC1, ADC_IT_EOC, ENABLE);

  /* Enable ADC1 IRQ */
  NVIC_InitStructure.NVIC_IRQChannel = ADC1_2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable ADC1 */
  ADC_Cmd(ADC1, ENABLE);

  /* wait for ADRDY */
  while(ADC_GetFlagStatus(ADC1, ADC_FLAG_RDY) == RESET);

  /* ADC1 start Conversion */
  ADC_StartConversion(ADC1);
}
示例#16
0
int main(void)
{  	
	u8 i;
	u8 RecvBuf[32];
	u8 SendBuf[32];
	u8 offline = 0;
	u8 recv_flag = 0;
	u32 pd2ms=0,pd20ams=0,pd20bms=0,pd100ms=0;

	SystemInit();
	RCC_Configuration();
	NVIC_Configuration();
	GPIO_Configuration();
	
	USART1_Configuration();
	dbgPrintf(" Init Ticktack !\r\n");
	cycleCounterInit();
	SysTick_Config(SystemCoreClock / 1000);	
	for(i=0;i<2;i++)
	{
		OP_LED1;OP_LED2;OP_LED3;OP_LED4;
		delay_ms(500);
		OP_LED1;OP_LED2;OP_LED3;OP_LED4;
		delay_ms(500);
	}
	FilterInit();
	controllerInit();

	dbgPrintf(" Init eeprom!\r\n");
	FLASH_Unlock();	
	EE_Init();
	EE_Read_ACC_GYRO_Offset();
	/* 如果PID丢失或者错误,将下面两行注释去掉,重新编译烧写,运行一遍,可将PID还原,然后重新注释,再烧写一遍 */
	//EE_Write_PID();
	//EE_Write_Rate_PID();
	EE_Read_PID();
	EE_Read_Rate_PID();

	dbgPrintf(" Init adc!\r\n");
	ADC_DMA_Init();

	dbgPrintf(" Init NRF24L01 !\r\n");
	SPI_NRF_Init();	
	Nrf24l01_Init();
	NRF24l01_SetRxMode();
	
	while(Nrf24l01_Check())	
	{
		dbgPrintf("NRF24L01 Fault !\r\n");
		delay_ms(500);
	}
	dbgPrintf("NRF24L01 Is Detected !\r\n");

	dbgPrintf("Init MPU6050...\r\n");
	IIC_Init();
	MPU6050_initialize();


	dbgPrintf("Init Motor...\r\n");
	Motor_Init();
	Motor_SetPwm(0,0,0,0);


	pd20bms = TIMIRQCNT + 10*ITS_PER_MS;
	while(1)
	{
		if(TIMIRQCNT>pd2ms + 2*ITS_PER_MS-1)	// every 4ms
		{
			GetEulerAngle();
			if(lock_flag==UNLOCK) 
				AttitudeToMotors(angle.y,angle.x,angle.z);
			else
			{
				MOTOR1=0;	 			
				MOTOR2=0;				
				MOTOR3=0;				
				MOTOR4=0;				
			}
			Motor_SetPwm(MOTOR1,MOTOR2,MOTOR3,MOTOR4);
			pd2ms = TIMIRQCNT;
		}
		
		if(TIMIRQCNT>pd20ams + 20*ITS_PER_MS-1)	// every 20ms
		{
				if(NRF24l01_Recv(RecvBuf)>10)
				{
						if((RecvBuf[RecvBuf[2]+3]==CheckSum(RecvBuf, RecvBuf[2]+3))&&(RecvBuf[0]==0xAA))
						{
								if(RecvBuf[1]!=0xC0)		
									OP_LED1;		
								offline=0;
								switch(RecvBuf[1])
								{
										case 0xC0:  //control
												Getdesireddata(RecvBuf);
												OP_LED2;
												break;
										case 0x10:  //W PID
												SetPID(RecvBuf);
												break;
										case 0x11:  //W Attitude
												SetAccGyroOffset(RecvBuf);
												break;
										case 0x12:  //W Control offset
												break;
										case 0x14:  //W Rate PID
												SetRatePID(RecvBuf);
												break;
										case 0x20:  //R PID
												recv_flag = RESEND;
												GetPID(SendBuf);
												break;
										case 0x21:  //R Attitude
												recv_flag = RESEND;
												GetAccGyroOffset(SendBuf);
												break;
										case 0x22:  //R Control offset
												break;
										case 0x24:  //R Rate PID
												recv_flag = RESEND;
												GetRatePID(SendBuf);
												break;
										case 0x40:	//校准姿态
												EnableCalibration();
												break;
										case 0x41:	//校准遥控器零点												
												break;
									 default:
												break;
								}
						}
				}
				pd20ams = TIMIRQCNT;
		}
		if(TIMIRQCNT>pd20bms + 20*ITS_PER_MS-1)	// every 20ms
		{
			if(recv_flag==0)
         		GetState(SendBuf);
      		else
         		recv_flag--;
			NRF_SendData(SendBuf);
			OP_LED3;
			pd20bms = TIMIRQCNT;
		}
		
		if(TIMIRQCNT>pd100ms + 100*ITS_PER_MS-1)	// every 100ms
		{
			if(offline>20)
				lock_flag = LOCK;
			offline++;
//			OP_LED4;
			pd100ms = TIMIRQCNT;
		}
	}
}
示例#17
0
文件: timer.c 项目: rokrupnik/vinokuh
void timerInit() {
	SysTick_Config(SystemCoreClock/1000); // zacnemo SysTick, ki ga prozimo vsako ms
	clockCounter = 0;
}
示例#18
0
int main(void)
{
	iniciar_leds_debug();

	//teste_filtro_de_kalman();

    //setar_parametros_PID(1500, 1000, 60, 126, 2500, 0, 0, 126);                      //Ajusta as constantes do PID para Roll e Pitch.
    setar_parametros_PID(1400, 25, 50, 188, 15, 0, 0, 188);                      //Ajusta as constantes do PID para Roll e Pitch.
    //setar_parametros_PID(900, 1200, 20, 188, 10, 0, 0, 188);                      //Ajusta as constantes do PID para Roll e Pitch.

    //Melhores parametros obtidos até o momento (05/01/2015) 5e-10 1e-45 1e-45 0.005 0.35 1e-6
    //Qang, QbiasAcel, Qbiasmag, Racel, Rmag, Rorth
    setar_parametros_Kalman(2.8e-8, 1e-15, 1e-15, 5e-15, 1e-2, 1e-1, 5e-1);             //Ajusta as covariâncias do filtro de Kalman.	//Melhores parametreos testados até o momento - 2e-9, 5e-8, 5e-12, 2.e-2, 2e-1, 1e-10, 1e-10

	uint16_t counter_recebidos = 0;												//Variável para contagem do número de mensagens recebidas.

	uint8_t status_RF = 0;														//Variável que aloca o estado do link RF.

    NVIC_SetPriorityGrouping(5);

	SysTick_Config(168e6/10000);		 										//Frequência de 100uS no systick.

    iniciar_ESC();																//Inicia PWM para controle dos ESCS.

    ajustar_velocidade(15,0);													//15 -> 0b1111 -> todos os motores -> Velocidade 0 -> Motores parados.

    //blinkDebugLeds();															//Pisca os leds
	
    delay_startup();															//Delay de inicialização dos ESCS.

	iniciar_RF();																//Inicar a placa nRF24L01p

//	configurar_I2C();															//Configurar o periférico I²C da placa.
    TM_I2C_Init(I2C3, TM_I2C_PinsPack_1, 400000);

    iniciarMPU6050Imu();

    configurar_bussola();														//Inicia o magnetômetro.
	
    iniciar_timer_controle();													//Timer responsável por checar se houve recepção de controel nos últimos 2 segundos.

	escrita_dados(SPI2, (uint8_t *)"Iniciado.", 32);							//Mensagem que informa que o procimento de inicialização foi concluído.

    modo_rx(SPI2);																//Habilita recepção de novas mensagens.

    configurar_timers_PWM_I();													//Configura os timers utilizados para PWMinput do controle.

    iniciar_estado_Kalman();

    iniciar_timer_processamento();												//Iniciar o timer responsável pelo controle do PID -> TIM6.

	while (1)																	//Processo contínuo de checagem do transmissor RF.
	{
		if (!Checar_IRQ())														//Checa eventos do transmissor. -> 0 Novo evento | 1 Não há novos eventos.
		{
			status_RF = retornar_status(SPI2);									//Registrador de Status do transmissor -> Causa da interrupção.

			if (MSG_Recebida())													//Checa o 6º bit -> Mensagem recebida
			{

	  			GPIO_ToggleBits(GPIOD, GPIO_Pin_13);							//Toggle no LED que indica a recepção de novas mensagens.

				TIM_SetCounter(TIM7,0);											//Reseta o contador do timer -> Inicia nova contagem de 2 segundos.

				/*Recupera as msgs enquanto houverem dados à serem recuperados*/

				while((status_RF & 0x0E) != 0x0E)								//Bits 1,2 e 3 -> Número do duto que recebeu mensagem no RF.
				{																//0b1110 -> Sem dados do duto. Repete o processo enquanto tiver dados.

    				counter_recebidos++;										//Contador para teste - Comparação entre número de msg enviadas / recebidas.

					limpar_buffer(buffer_dados_tx, 33);							//Limpa os buffers para troca de dados.
					limpar_buffer(buffer_dados_rx, 33);

					leitura_dados(SPI2, buffer_dados_rx, 32);

					buffer_dados_tx[0] = status_RF;								//Limpa o FLAG de msg recebida no registrador de status.
					buffer_dados_tx[0] |= RX_DR;

					escrever_registrador(SPI2, STATUS, buffer_dados_tx, 1);

					status_RF = retornar_status(SPI2);							//Checagem se há mais dados nos disponíveis para serem tratados na próxima iteração.

					switch(buffer_dados_rx[0])									//Primeiro caractér do vetor recebido determina a operação à ser realizada.
					{
                        case 't':
							GPIO_ToggleBits(GPIOD, GPIO_Pin_15);
						break;


						//Função de teste do LINK RF -> Retorna o número de payloads recebidos
						//Utilizada para checagem no número de pacotes perdidos.
						case 'C':
							numToASCII(counter_recebidos, buffer_dados_tx);
							escrita_dados(SPI2, buffer_dados_tx, 32);
						break;
						
						case 'R':
							buffer_dados_tx[0] = 'R';

							conversor.flutuante_entrada = dc_ch_1;
							copy_to(buffer_dados_tx, conversor.bytes, 1, 4);

							conversor.flutuante_entrada = dc_ch_2;
							copy_to(buffer_dados_tx, conversor.bytes, 5, 4);

							conversor.flutuante_entrada = dc_ch_3;
							copy_to(buffer_dados_tx, conversor.bytes, 9, 4);

							conversor.flutuante_entrada = dc_ch_4;
							copy_to(buffer_dados_tx, conversor.bytes, 13, 4);

							escrita_dados(SPI2, buffer_dados_tx, 32);
						break;

						case 'S':

							if(start_logging_sensores == 0)
								start_logging_sensores = 1;
							else if(start_logging_sensores == 1)
								start_logging_sensores = 0;
						break;
						case 'L':

							if(start_logging_final == 0)
								start_logging_final = 1;

							else if(start_logging_final == 1)
								start_logging_final = 0;

						break;


					    //Retorna as constantes utilizadas no PID.
						case 'Y':

							limpar_buffer(buffer_dados_tx,33);

							retornar_parametros_pid(&kp, &ki, &kd);

							buffer_dados_tx[0] = '%';

							conversor.flutuante_entrada = kp;
							copy_to(buffer_dados_tx, conversor.bytes, 1, 4);

                            conversor.flutuante_entrada = ki;
							copy_to(buffer_dados_tx, conversor.bytes, 5, 4);

                            conversor.flutuante_entrada = kd;
							copy_to(buffer_dados_tx, conversor.bytes, 9, 4);

							escrita_dados(SPI2, buffer_dados_tx, 32);

						break;


						//Retorna as convariâncias e variância utilizadas no filtro de Kalman.
						case 'J':

							limpar_buffer(buffer_dados_tx,33);

                            //FIXME: Consertar método para envio dos parâmetros do filtro de Kalman
                            //retornar_parametros_Kalman(&Q_acelerometro, &Q_magnetometro, &Q_bias, &R_acelerometro, &R_magnetometro);

							buffer_dados_tx[0] = '^';

							conversor.flutuante_entrada = Q_acelerometro;
							copy_to(buffer_dados_tx, conversor.bytes, 1, 4);

							conversor.flutuante_entrada = Q_magnetometro;
							copy_to(buffer_dados_tx, conversor.bytes, 5, 4);

							conversor.flutuante_entrada = Q_bias;
							copy_to(buffer_dados_tx, conversor.bytes, 9, 4);

							conversor.flutuante_entrada = R_acelerometro;
							copy_to(buffer_dados_tx, conversor.bytes, 13, 4);

							conversor.flutuante_entrada = R_magnetometro;
							copy_to(buffer_dados_tx, conversor.bytes, 17, 4);

							escrita_dados(SPI2, buffer_dados_tx, 32);

					    break;

						//Altera as constantes utilizadas no PID.
						case 'U':

							conversor.bytes[0] = buffer_dados_rx[1];
							conversor.bytes[1] = buffer_dados_rx[2];
							conversor.bytes[2] = buffer_dados_rx[3];
							conversor.bytes[3] = buffer_dados_rx[4];

							kp = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[5];
							conversor.bytes[1] = buffer_dados_rx[6];
							conversor.bytes[2] = buffer_dados_rx[7];
							conversor.bytes[3] = buffer_dados_rx[8];

							kd = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[9];
							conversor.bytes[1] = buffer_dados_rx[10];
							conversor.bytes[2] = buffer_dados_rx[11];
							conversor.bytes[3] = buffer_dados_rx[12];

							ki = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[13];
							conversor.bytes[1] = buffer_dados_rx[14];
							conversor.bytes[2] = buffer_dados_rx[15];
							conversor.bytes[3] = buffer_dados_rx[16];

							kp_yaw = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[17];
							conversor.bytes[1] = buffer_dados_rx[18];
							conversor.bytes[2] = buffer_dados_rx[19];
							conversor.bytes[3] = buffer_dados_rx[20];

							kd_yaw = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[21];
							conversor.bytes[1] = buffer_dados_rx[22];
							conversor.bytes[2] = buffer_dados_rx[23];
							conversor.bytes[3] = buffer_dados_rx[24];

							ki_yaw = conversor.flutuante_entrada;

                            //setar_parametros_PID(kp,ki,kd, 126, kp_yaw, ki_yaw, kd_yaw, 126); //Insere os parametros no processo de controle.
                            setar_parametros_PID(kp,ki,kd, 126, 0, 0, 0, 126); //Insere os parametros no processo de controle.

						break;


						//Altera as constantes utilizadas no filtro de Kalman.
						case 'T':

							conversor.bytes[0] = buffer_dados_rx[1];
							conversor.bytes[1] = buffer_dados_rx[2];
							conversor.bytes[2] = buffer_dados_rx[3];
							conversor.bytes[3] = buffer_dados_rx[4];

							Q_acelerometro = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[5];
							conversor.bytes[1] = buffer_dados_rx[6];
							conversor.bytes[2] = buffer_dados_rx[7];
							conversor.bytes[3] = buffer_dados_rx[8];

							Q_magnetometro = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[9];
							conversor.bytes[1] = buffer_dados_rx[10];
							conversor.bytes[2] = buffer_dados_rx[11];
							conversor.bytes[3] = buffer_dados_rx[12];

							Q_bias = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[13];
							conversor.bytes[1] = buffer_dados_rx[14];
							conversor.bytes[2] = buffer_dados_rx[15];
							conversor.bytes[3] = buffer_dados_rx[16];

							R_acelerometro = conversor.flutuante_entrada;

							conversor.bytes[0] = buffer_dados_rx[17];
							conversor.bytes[1] = buffer_dados_rx[18];
							conversor.bytes[2] = buffer_dados_rx[19];
							conversor.bytes[3] = buffer_dados_rx[20];

							R_magnetometro = conversor.flutuante_entrada;							

							//Qang, Qbias, Qbiasmag, Racel, Rmag
                            //setar_parametros_Kalman(Q_acelerometro, Q_magnetometro, R_acelerometro, R_magnetometro, 1e-10); //Insere os parametros no processo de controle.

						break;


						//Se a sequência de caracteres recebida não possui um comando reconhecido, retorna o número de caracteres
						//contidos no pacote.
						default:

							numToASCII((strlen((char *) buffer_dados_rx)), buffer_dados_tx);
							escrita_dados(SPI2, buffer_dados_tx, 32);

						break;

					}
				}

				//Retorna ao modo de recepção.

				modo_rx(SPI2);

			}
		}

		//Função para envio dos dados da telemetria : Se a telemetria estiver ativada e o tempo entre o envio se passou.

		if(variavel_delay_100ms == 0)
		{
			buffer_dados_tx[0] = 'L';

			retornar_estado(telemetria_kalman, telemetria_pid);

			conversor.flutuante_entrada = telemetria_kalman[0];
			copy_to(buffer_dados_tx, conversor.bytes, 1, 4);


			conversor.flutuante_entrada = telemetria_kalman[1];
			copy_to(buffer_dados_tx, conversor.bytes, 5, 4);


			conversor.flutuante_entrada = telemetria_kalman[2];
			copy_to(buffer_dados_tx, conversor.bytes, 9, 4);


			conversor.flutuante_entrada = telemetria_pid[0];
			copy_to(buffer_dados_tx, conversor.bytes, 13, 4);


			conversor.flutuante_entrada = telemetria_pid[1];
			copy_to(buffer_dados_tx, conversor.bytes, 17, 4);


			conversor.flutuante_entrada = telemetria_pid[2];
			copy_to(buffer_dados_tx, conversor.bytes, 21, 4);

			escrita_dados(SPI2, buffer_dados_tx, 32);
			
			//Retorna ao modo de recepção para habilitar a chegada de novos pacotes.

//			modo_rx(SPI2);

			//Variável para controle de tempo entre os envios dos dados da telemetria.

			//variavel_delay_100ms = 500; 	//500* 100 uS -> 1 Ponto a cada 50 mS

		//}else if(variavel_delay_100ms == 0 && start_logging_sensores == 1 && start_logging_final == 0)
		//{
			buffer_dados_tx[0] = 'S';

			retornar_estado_sensores(telemetria_acelerometro, telemetria_giroscopio, telemetria_magnetometro);

            conversor.flutuante_entrada = telemetria_acelerometro[0];
			copy_to(buffer_dados_tx, conversor.bytes, 1, 4);


            conversor.flutuante_entrada = telemetria_acelerometro[1];
			copy_to(buffer_dados_tx, conversor.bytes, 5, 4);


            conversor.flutuante_entrada = telemetria_acelerometro[2];
			copy_to(buffer_dados_tx, conversor.bytes, 9, 4);


            conversor.flutuante_entrada = telemetria_giroscopio[0];
			copy_to(buffer_dados_tx, conversor.bytes, 13, 4);


            conversor.flutuante_entrada = telemetria_giroscopio[1];
			copy_to(buffer_dados_tx, conversor.bytes, 17, 4);


            conversor.flutuante_entrada = telemetria_giroscopio[2];
			copy_to(buffer_dados_tx, conversor.bytes, 21, 4);


            conversor.flutuante_entrada = telemetria_magnetometro[0];
			copy_to(buffer_dados_tx, conversor.bytes, 25, 4);


			//conversor.flutuante_entrada = telemetria_giroscopio[1];
			//copy_to(buffer_dados_tx, conversor.bytes, 29, 4);
			
			escrita_dados(SPI2, buffer_dados_tx, 32);
			
			//Retorna ao modo de recepção para habilitar a chegada de novos pacotes.

			modo_rx(SPI2);
			variavel_delay_100ms = 250; 	//500* 100 uS -> 1 Ponto a cada 50 mS
		}
	}
}
示例#19
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f0xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f0xx.c file
     */

  /* GPIOC Periph clock enable */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE);

  /* Configure PC8 and PC9 in output pushpull mode */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOC, &GPIO_InitStructure);

  /* Setup SysTick Timer for 1 msec interrupts.
     ------------------------------------------
    1. The SysTick_Config() function is a CMSIS function which configure:
       - The SysTick Reload register with value passed as function parameter.
       - Configure the SysTick IRQ priority to the lowest value (0x0F).
       - Reset the SysTick Counter register.
       - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
       - Enable the SysTick Interrupt.
       - Start the SysTick Counter.

    2. You can change the SysTick Clock source to be HCLK_Div8 by calling the
       SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8) just after the
       SysTick_Config() function call. The SysTick_CLKSourceConfig() is defined
       inside the misc.c file.

    3. You can change the SysTick IRQ priority by calling the
       NVIC_SetPriority(SysTick_IRQn,...) just after the SysTick_Config() function
       call. The NVIC_SetPriority() is defined inside the core_cm0.h file.

    4. To adjust the SysTick time base, use the following formula:

         Reload Value = SysTick Counter Clock (Hz) x  Desired Time base (s)

       - Reload Value is the parameter to be passed for SysTick_Config() function
       - Reload Value should not exceed 0xFFFFFF
   */
  if (SysTick_Config(SystemCoreClock / 1000))
  {
	  /* Capture error */
	  while (1);
  }

  // ==============================================================================

  // FLASH TEST
  //uint32_t* buff = malloc(FLASH_PAGE_SIZE);
  //flash_read_page(0, &buff, FLASH_PAGE_SIZE);
  // \FLASH TEST

  // RESTORE SETTINGS TEST
  restoreSettings();
  // \RESTORE SETTINGS TEST

  // TIMER TEST
  //TIM_Config();
  // \TIMER TEST

  // DATE TIME CONVERSION TEST
  uint32_t dt4B;
  bool dtok = true;
  if( convertDateTimeTo4B( 23, 59, 59, 31, 1, 16, &dt4B ) )
	  dtok = true;
  else
	  dtok = false;

  DateTimeStr_t dtstr;
  bool dtstrok = false;
  convertDateTime4BtoString(dt4B, dtstr, HHMMSSDDMMYYYY);
  // \DATE TIME CONVERSION TEST



  /* To achieve GPIO toggling maximum frequency, the following  sequence is mandatory. 
     You can monitor PC8 and PC9 on the scope to measure the output signal. 
     If you need to fine tune this frequency, you can add more GPIO set/reset 
     cycles to minimize more the infinite loop timing.
     This code needs to be compiled with high speed optimization option.  */

  while (1)
  {
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
//
//    /* Set PC8 and PC9 */
//    GPIOC->BSRR = BSRR_VAL;
//    /* Reset PC8 and PC9 */
//    GPIOC->BRR = BSRR_VAL;
  }
}
示例#20
0
void portInitClock(void)
{
  SysTick_Config(SystemCoreClock / HZ);
  NVIC_SetPriority(SysTick_IRQn, PORT_SYSTICK_PRI);
}
示例#21
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void) {
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */
  
  /* RCC configuration */
  RCC_Configuration();
  
  /* TIM4 configuration */
  TIM4_Configuration();
  
  /* UART4 configuration */
  UART4_Configuration();
  
  /* Configure SysTick for each 1us */  
  SysTick_Config(SystemCoreClock / 1000000);
  
  /* TLCD configuration */
  TLCD_Configuration();

  /* RTC Configuration */
  RTC_Configuration();
  
  /* WIZ820io SPI2 configuration */
  WIZ820io_SPI2_Configuration();  // one that is on left one
  
  /* WIZ820io SPI3 configuration */
  //WIZ820io_SPI3_Configuration();  // one that is on right one

  /* W5200 Configuration */
  Set_network();
  
  /* EXIT4(Mode select button) configuration */
  EXTILine4_Configuration();
  
  /* EXIT5(F_SYNC : 100Hz) configuration */
  EXTILine5_Configuration();
  
  /* EXIT6(F_SCLK : 10KHz) configuration */
  EXTILine6_Configuration();
  
  /* myAccel3LV02 Configuration */
  Accel3LV02_Configuration();
  
  //myAccel3LV02 setup 1000.0111 Power on, enable all axis, self test off
  Accel_WriteReg(CTRL_REG1, 0xC7);
  // following routine setup myAccel3LV02 6g mode
  //Accel_WriteReg(CTRL_REG2, 0x80);
  
  /* GLCD configuration */
  GLCD_Configuration();
  
  /* Clear system loading string of TLCD */
  TLCD_Clear();
  
  // When everything is set, print message
  printf("\r\n - System is ready - ");
  
  while(1) {
    if(TimerCount >= 1000) {  // thousand equals one second
      TimerCount = 0;

      /*
      // retrieve axis data
      GetAccelValue(AXIS_X, &Xdata);
      GetAccelValue(AXIS_Y, &Ydata);
      GetAccelValue(AXIS_Z, &Zdata);
      
      char str[30];
      sprintf(str, "%d,%d,%d", 0xFFF&Xdata, 0xFFF&Ydata, 0xFFF&Zdata);
      TLCD_Clear();
      TLCD_Write(0, 0, str);
      */
    }
    
    if(ParseUART4) {
      ParseUART4 = false; 
      
      // print Wiz810io configuration
      printSysCfg();
    }
    
    if(flag_uart == 1) {
      tmp_start = index;
    }
    
    // On every impulse out of 100Hz do the work
    if(RbitFlag) {
      RbitFlag = false;
      
      // copy to buffer
      mAxisBuf.tmp_data_x_lcd[index] = mAxisData.data_x[index];
      mAxisBuf.tmp_data_y_lcd[index] = mAxisData.data_y[index];
      mAxisBuf.tmp_data_z_lcd[index] = mAxisData.data_z[index];
      
      // Copy to Temporary GAL array
      CopyToTmpGalArray(index);
      
      // Cut off to 1G
      CutOffTo1G(index);
      
      // Calculate GAL and copy to single temporary GAL value
      CalculateGalAndCopyToGal(index);
      
      // Determine KMA scale
      DetermineKMA(index);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {
        //PCFlag = false;
        
        char PC_Buf[20];
        sprintf(PC_Buf, "%+d,%+d,%+d\n",
                mAxisBuf.tmp_data_x_lcd[index],
                mAxisBuf.tmp_data_y_lcd[index],
                mAxisBuf.tmp_data_z_lcd[index]);
        // code for stacking algorithm which will combine data from two boards into one
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_TWO) == SOCK_ESTABLISHED) {
          /* send selected data */
          send(SOCK_TWO, (uint8_t*)PC_Buf, strlen(PC_Buf), (bool)false);
        }
      }
      
      // increase index so that we can add to next array
      index++;
    }
        
    switch(mode) {
    case SELECT_AXIS_X : break;
    case SELECT_AXIS_Y : break;
    case SELECT_AXIS_Z : break;
    }
    
    // RTC Wakeup event
    if(WUFlag) {
      WUFlag = false;
      
      // Update current Date and Time
      RTC_TimeShow();
      
      // Display on TLCD
      TLCD_Write(0, 0, Date);
      TLCD_Write(0, 1, Time);
    }
    
    /* EQ-DAQ-01 Parsing routine ------------------------------------------------- */
    /* Set E1Flag indicate that we have valid connection from EQ-DAQ-01(port 5050) */
    if(E1Flag) {
      E1Flag = false;
      
      ProcessTextStream(EQ_ONE, (char*)RX_BUF);
    }
    
    /* EQ-DAQ-02 Parsing routine ------------------------------------------------- */
    /* Set E2Flag indicate that we have valid connection from EQ-DAQ-02(port 6060) */
    if(E2Flag) {
      E2Flag = false;
      
      ProcessTextStream(EQ_TWO, (char*)RX_BUF);
    }
    
    /* Process server socket with each port */
    ProcessTcpServer(SOCK_ZERO, 5050);  // designated as for EQM-DAQ-01 with port 5050
    ProcessTcpServer(SOCK_ONE, 6060);   // designated as for EQM-DAQ-02 with port 6060
    ProcessTcpServer(SOCK_TWO, 7070);   // designated as for PC-CLIENT  with port 7070
    ProcessTcpServer(SOCK_THREE, 8080); // designated as for TOBEUSED   with port 8080
    
    /* Socket 4 to 7 reserved for future application
     * ProcessTcpServer(SOCK_FOUR, 9090);   // designated as for TOBEUSED with port 9090
     * ProcessTcpServer(SOCK_FIVE, 10010);   // designated as for TOBEUSED with port 10010
     * ProcessTcpServer(SOCK_SIX, 10020);    // designated as for TOBEUSED with port 10020
     * ProcessTcpServer(SOCK_SEVEN, 10030);  // designated as for TOBEUSED with port 10030
     */
  }
}
示例#22
0
文件: Blinky.c 项目: aomgemalmaz/tez
/**********************************************************************
***********							 Main Program						***********************
***********************************************************************
	Aim  : main program
	NOTE :
**********************************************************************/
int main (void)
{

    SystemCoreClockUpdate();
//	SysTick_Config(10000);																					//turn SysTick timer on
    SysTick_Config(SystemCoreClock/1600);															// 1ms SysTicks
    Delay(100);																												//wait for system stabilization
    SIM->SCGC5 |= SIM_SCGC5_PORTD_MASK | SIM_SCGC5_PORTB_MASK;      	//Port-D-B clock ON
    SIM->SCGC5 |= SIM_SCGC5_PORTA_MASK;
    Delay(0x500);                     																//delay
    LED_Init();           																						//Initialize the LEDs
    spi_init();																												// SPI-1 init
    Delay(0x100);																											//delay
    hede=PTD->PDIR;
    TI_Init();
//		TI_HW_Reset();
//	Delay(0x3000);													//delay for logic analyzer
    hede=PTD->PDIR;
//	SpiStart();
//	SPI_Send(0x10);
//	SpiStop();
//		test[0]=TI_ReadByte(0x0F);
//		test[1]=TI_ReadByte(0x0F);
//		test[2]=TI_ReadByte(0x0F);
//		test[3]=TI_ReadByte(0x0F);
//		test[4]=TI_ReadByte(0x0F);
//
//	TI_WriteByte(CC112X_IOCFG3,0x87);
//	test[5]=TI_ReadByte(CC112X_IOCFG3);
//	TI_Command(CC112X_SRES);				//sofware reset
//
//	test[6]=TI_ReadByte(CC112X_IOCFG3);
//	TI_WriteByte(CC112X_IOCFG3,0x87);
//	test[7]=TI_ReadByte(CC112X_IOCFG3);
//
    TI_Write_brst(CC112X_BURST_TXFIFO,toto,20);
    Delay(100);
    TI_Read_brst(CC112X_RSSI1,got,1);

//Delay(100);
//TI_Command(CC112X_SRES);				//sofware reset

    setRegisters();
    getReg_Test();
//		TI_WriteByte(CC112X_DCFILT_CFG,0x40);
//		TI_WriteByte(CC112X_IOCFG2, 0x06);
//		TI_WriteByte(CC112X_IOCFG1, 0xB0);
//		TI_WriteByte(CC112X_IOCFG0, 0x40);

    test[0] = getCelcius();	 //Read temp sensor TEST



//	Delay(0x2000);
    while(1)
    {
        // Turn on leds 1 by 1
        YELLOW_ON;
        Delay(1000);
        GREEN_ON;
        Delay(1000);
        RED_ON;
        Delay(1000);
        //Turn off leds
        YELLOW_OFF;
        GREEN_OFF;
        RED_OFF;
//		SpiStart();
//		hede=PTD->PDIR;
//		DelayUs(0x1000);
//		SPI_Send(0x10);
//		x=SPI_Send(0x00);
//		x=SPI_Send(0x00);
//		SpiStop();
//		Delay(0x50);

//		SpiStart();
//		SPI_Send(0x10);
//		x=SPI_Send(0x00);
//		SpiStop();
//		hede=PTD->PDIR;
//
//		SpiStop();
////		YELLOW_ON; Delay(1000);	GREEN_ON; Delay(1000);	RED_ON; Delay(1000);
////		TI_WriteByte(CC112X_IOCFG3,0x87);
////		test[2]=TI_ReadByte(CC112X_IOCFG3);
////		YELLOW_OFF;	GREEN_OFF;	RED_OFF;
//
//	PTD->PCOR |= (1UL<<4);                             	  // CS=0, SPI start
//
//	hede=PTD->PDIR;

////		test[0]=SPI_Send(0x10);
//	while((PTD->PDIR & 0x80)!= 0);												//Wait for CHIP_RDYn signal
//
//	SPI_Send(0x8F);																//send the adress and get the status byte
//	test[2]= SPI_Send(0x00);															//read the adress
////		test[1]=SPI_Send(0x00);
////		test[2]=SPI_Send(0x10);
////		test[3]=SPI_Send(0x00);
////		SPI_Send(0x10);
//
//	PTD->PSOR |= (1UL<<4);                             	  // CS=0, SPI stop
    }
}
示例#23
0
/*
 * Arduino Zero board initialization
 *
 * Good to know:
 *   - At reset, ResetHandler did the system clock configuration. Core is running at 48MHz.
 *   - Watchdog is disabled by default, unless someone plays with NVM User page
 *   - During reset, all PORT lines are configured as inputs with input buffers, output buffers and pull disabled.
 */
void init( void )
{
  uint32_t ul ;

  // Set Systick to 1ms interval, common to all Cortex-M variants
  if ( SysTick_Config( SystemCoreClock / 1000 ) )
  {
    // Capture error
    while ( 1 ) ;
  }

  // Clock PORT for Digital I/O
//	PM->APBBMASK.reg |= PM_APBBMASK_PORT ;
//
//  // Clock EIC for I/O interrupts
//	PM->APBAMASK.reg |= PM_APBAMASK_EIC ;

  // Clock SERCOM for Serial
  PM->APBCMASK.reg |= PM_APBCMASK_SERCOM0 | PM_APBCMASK_SERCOM1 | PM_APBCMASK_SERCOM2 | PM_APBCMASK_SERCOM3 | PM_APBCMASK_SERCOM4 | PM_APBCMASK_SERCOM5 ;

  // Clock TC/TCC for Pulse and Analog
  PM->APBCMASK.reg |= PM_APBCMASK_TCC0 | PM_APBCMASK_TCC1 | PM_APBCMASK_TCC2 | PM_APBCMASK_TC3 | PM_APBCMASK_TC4 | PM_APBCMASK_TC5 ;

#if defined (__SAMD21J18A__)
  PM->APBCMASK.reg |= PM_APBCMASK_TC6 | PM_APBCMASK_TC7;
#endif // __SAMD21J18A__

  // Clock ADC/DAC for Analog
  PM->APBCMASK.reg |= PM_APBCMASK_ADC | PM_APBCMASK_DAC ;

  // Initialize Analog Controller
  // Setting clock
  while(GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);

  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID( GCM_ADC ) | // Generic Clock ADC
                      GCLK_CLKCTRL_GEN_GCLK0     | // Generic Clock Generator 0 is source
                      GCLK_CLKCTRL_CLKEN ;

  while( ADC->STATUS.bit.SYNCBUSY == 1 );          // Wait for synchronization of registers between the clock domains

  ADC->CTRLB.reg = ADC_CTRLB_PRESCALER_DIV512 |    // Divide Clock by 512.
                   ADC_CTRLB_RESSEL_10BIT;         // 10 bits resolution as default

  ADC->SAMPCTRL.reg = 0x3f;                        // Set max Sampling Time Length

  while( ADC->STATUS.bit.SYNCBUSY == 1 );          // Wait for synchronization of registers between the clock domains

  ADC->INPUTCTRL.reg = ADC_INPUTCTRL_MUXNEG_GND;   // No Negative input (Internal Ground)

  // Averaging (see datasheet table in AVGCTRL register description)
  ADC->AVGCTRL.reg = ADC_AVGCTRL_SAMPLENUM_1 |    // 1 sample only (no oversampling nor averaging)
                     ADC_AVGCTRL_ADJRES(0x0ul);   // Adjusting result by 0

  analogReference( AR_DEFAULT ) ; // Analog Reference is AREF pin (3.3v)

  // Initialize DAC
  // Setting clock
  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY );
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID( GCM_DAC ) | // Generic Clock ADC
                      GCLK_CLKCTRL_GEN_GCLK0     | // Generic Clock Generator 0 is source
                      GCLK_CLKCTRL_CLKEN ;

  while ( DAC->STATUS.bit.SYNCBUSY == 1 ); // Wait for synchronization of registers between the clock domains
  DAC->CTRLB.reg = DAC_CTRLB_REFSEL_AVCC | // Using the 3.3V reference
                   DAC_CTRLB_EOEN ;        // External Output Enable (Vout)
}
示例#24
0
/**
* @brief  Main program.
* @param  None
* @retval None
*/
int main(void)
{   
  /*!< At this stage the microcontroller clock setting is already configured, 
  this is done through SystemInit() function which is called from startup
  file (startup_stm32f0xx.s) before to branch to application main.
  To reconfigure the default setting of SystemInit() function, refer to
  system_stm32f0xx.c file*/ 
  
    /* Setup SysTick Timer for 1 msec interrupts.*/
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* Capture error */ 
    while (1);
  }     
  
  /* Initialize LEDs, User Button on STM32F072B-DISCO board ***********/
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI); 
  
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);
  
  /* Initialize Mems Gyroscope */
  Demo_GyroConfig();
  
  /* Initialize USB Device */
  USBD_Init(&USB_Device_dev,
            &USR_desc, 
            &USBD_HID_cb, 
            &USR_cb);
  
  /* Init STMTouch driver */
  TSL_user_Init(); 
  
   /* End of Initialisation */
  
    /* Delay 1s to select Test Program or to go directly through the demo*/
  Delay (1000);
  
  if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET )
  {
    /* Wait for User button is released */
    while (STM_EVAL_PBGetState(BUTTON_USER) != Bit_RESET)
    {}
    
    /* Set ButtonPressed at 0 value  */ 
    ButtonPressed = 0;
    
    /* LED test : Blinking LEDs  */ 
    LED_Test();
    
    /* Wait for User button to be pressed to switch to USB Test
    the cursor move in square path and led On corresponding to such direction  */
    USB_Test();
    
    /* Move Discovery board to execute MEMS Test, Mems detect the angular rate
    and led On corresponding to such direction*/ 
    MEMS_Test();
    
    /* Wait for User button to be pressed to switch to Touch Sensor Test
    each TouchKey pointed correspond to specific Leds On, test can performed
    in both direction */ 
    LTS_Test();
  }
  
  /* Infinite loop */
  while (1)
  {  
    Demo();
  }
}
示例#25
0
void systemInit(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
#if 0
  gpio_config_t gpio_cfg[] = {
    { LED0_GPIO, LED0_PIN, GPIO_Mode_Out_PP },
    { LED1_GPIO, LED1_PIN, GPIO_Mode_Out_PP },
#ifdef BUZZER
    { BEEP_GPIO, BEEP_PIN, GPIO_Mode_Out_OD },
#endif
  };
  uint8_t gpio_count = sizeof(gpio_cfg) / sizeof(gpio_cfg[0]);
#endif

  // This is needed because some shit inside Keil startup f***s with SystemCoreClock, setting it back to 72MHz even on HSI.
  SystemCoreClockUpdate();

  // Turn on clocks for stuff we use
  RCC_ADCCLKConfig(RCC_PCLK2_Div4);

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 | RCC_APB1Periph_TIM3 | RCC_APB1Periph_TIM4 | RCC_APB1Periph_I2C2, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC | RCC_APB2Periph_TIM1 | RCC_APB2Periph_ADC1 | RCC_APB2Periph_USART1 | RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2, ENABLE);
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
  RCC_ClearFlag();

  // Make all GPIO in by default to save power and reduce noise
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
  GPIO_Init(GPIOB, &GPIO_InitStructure);
  GPIO_Init(GPIOC, &GPIO_InitStructure);

  // Turn off JTAG port 'cause we're using the GPIO for leds
  GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);

#if 0
  // Configure gpio
  for (uint32_t i = 0; i < gpio_count; i++) {
    GPIO_InitStructure.GPIO_Pin = gpio_cfg[i].pin;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
    GPIO_InitStructure.GPIO_Mode = gpio_cfg[i].mode;
    GPIO_Init(gpio_cfg[i].gpio, &GPIO_InitStructure);
  }

  LED0_OFF;
  LED1_OFF;
  BEEP_OFF;
#endif
  // Init cycle counter
  cycleCounterInit();

  // SysTick
  SysTick_Config(SystemCoreClock / 1000);

  // Configure the rest of the stuff
#if 0
  i2cInit(I2C2);
#endif

  // sleep for 100ms
  delay(100);
}
示例#26
0
文件: rtc.cpp 项目: tanelili/Lab2.3
int main(void) {

#if defined (__USE_LPCOPEN)
	// Read clock settings and update SystemCoreClock variable
	SystemCoreClockUpdate();
#if !defined(NO_BOARD_LIB)
	// Set up and initialize all required blocks and
	// functions related to the board hardware
	Board_Init();
	// Set the LED to the state of "On"
#endif
#endif

	Timer aika(0, 30, 0, true);
	Timer ledi(0, 10, 0, true);
	Timer skooppi(0, 0, 300, true);

	// write code here that uses two timer objects
	// one is used to print current time every 30 seconds (use semihosting for printing)
	// second to switch led colour every 10 seconds
	// third to give a pulse on PIO0_10 every 300 ms
	// make the timer tick from main program - do not call object's methods from ISR

	// Otetaan käyttöön GPION 0,10
	Chip_IOCON_PinMuxSet(LPC_IOCON, 0, 10, (IOCON_DIGMODE_EN));
	Chip_GPIO_SetPinDIROutput(LPC_GPIO, 0, 10);

	// Force the counter to be placed into memory
	volatile static int i = 0 ;

	/* The sysTick counter only has 24 bits of precision, so it will
	   overflow quickly with a fast core clock. You can alter the
	   sysTick divider to generate slower sysTick clock rates. */
	Chip_Clock_SetSysTickClockDiv(1);

	/* A SysTick divider is present that scales the sysTick rate down
	   from the core clock. Using the SystemCoreClock variable as a
	   rate reference for the SysTick_Config() function won't work,
	   so get the sysTick rate by calling Chip_Clock_GetSysTickClockRate() */
	uint32_t sysTickRate = Chip_Clock_GetSysTickClockRate();

	/* Enable and setup SysTick Timer at a periodic rate */
	SysTick_Config(sysTickRate / TICKRATE_HZ1);

	while(1){

		// Enter an infinite loop, just incrementing a counter
		while(!flag) __WFI();
		flag = false;

		if(aika.Tick()){
			// Aika on loppu tässä
			// Tulosta aika semihostingilla
			//enter_critical();
			 printf("RealTimeClock after every 30secons.: %d.%d.%d\n", h,m,s);
		}

		if(ledi.Tick()){
			//Aika on loppu tässä
			Board_LED_Set(q, false);
			q++;
			Board_LED_Set(q, true);
			if (q == 2){
				q = 0;
			}
		}

		if(skooppi.Tick()){
			//Aika on loppu tässä
			// pulssi
			if (pulssi == 0) {
				Chip_GPIO_SetPinState(LPC_GPIO, 0, 10, true);
				pulssi = 1;
			}else{
				pulssi = 0;
				Chip_GPIO_SetPinState(LPC_GPIO, 0, 10, false);
			}

		}
		i++ ;
	}
	return 0 ;
}
示例#27
0
/**
  * @brief  Execute the demo application.
  * @param  None
  * @retval None
  */
static void Demo_Exec(void)
{
  uint8_t togglecounter = 0x00;
  
  /* Initialize Accelerometer MEMS*/
  if(BSP_ACCELERO_Init() != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler(); 
  }

  while(1)
  {
    DemoEnterCondition = 0x00;
    
    /* Reset UserButton_Pressed variable */
    UserButtonPressed = 0x00;
    
    /* Initialize LEDs to be managed by GPIO */
    BSP_LED_Init(LED4);
    BSP_LED_Init(LED3);
    BSP_LED_Init(LED5);
    BSP_LED_Init(LED6);
    
    /* SysTick end of count event each 10ms */
    SystemCoreClock = HAL_RCC_GetHCLKFreq();
    SysTick_Config(SystemCoreClock / 100);  
    
    /* Turn OFF all LEDs */
    BSP_LED_Off(LED4);
    BSP_LED_Off(LED3);
    BSP_LED_Off(LED5);
    BSP_LED_Off(LED6);
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {
      /* Toggle LED4 */
      BSP_LED_Toggle(LED4);
      HAL_Delay(10);
      /* Toggle LED4 */
      BSP_LED_Toggle(LED3);
      HAL_Delay(10);
      /* Toggle LED4 */
      BSP_LED_Toggle(LED5);
      HAL_Delay(10);
      /* Toggle LED4 */
      BSP_LED_Toggle(LED6);
      HAL_Delay(10);
      togglecounter ++;
      if (togglecounter == 0x10)
      {
        togglecounter = 0x00;
        while (togglecounter < 0x10)
        {
          BSP_LED_Toggle(LED4);
          BSP_LED_Toggle(LED3);
          BSP_LED_Toggle(LED5);
          BSP_LED_Toggle(LED6);
          HAL_Delay(10);
          togglecounter ++;
        }
        togglecounter = 0x00;
      }
    }
    
    /* Waiting User Button is Released */
    while (BSP_PB_GetState(BUTTON_KEY) != KEY_NOT_PRESSED)
    {}
    UserButtonPressed = 0x00;
    
    /* TIM4 channels configuration */
    TIM4_Config();
  
    DemoEnterCondition = 0x01; 
    
    /* USB configuration */
    Demo_USBConfig();
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {}
    
    /* Waiting User Button is Released */
    while (BSP_PB_GetState(BUTTON_KEY) != KEY_NOT_PRESSED)
    {}
    
    /* Disconnect the USB device */
    USBD_Stop(&hUSBDDevice);
    USBD_DeInit(&hUSBDDevice);
  }
}
示例#28
0
/**
  * @brief  Execute the demo application.
  * @param  None
  * @retval None
  */
static void Demo_Exec(void)
{
  RCC_ClocksTypeDef RCC_Clocks;
  uint8_t togglecounter = 0x00;
  
  while(1)
  {
    DemoEnterCondition = 0x00;
    
    /* Reset UserButton_Pressed variable */
    UserButtonPressed = 0x00;
    
    /* SysTick end of count event each 10ms */
    RCC_GetClocksFreq(&RCC_Clocks);
    SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);  
    

    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {
      
    }
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    UserButtonPressed = 0x00;
    

    /* MEMS configuration */
    LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE;
    LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_100;
    LIS302DL_InitStruct.Axes_Enable = LIS302DL_XYZ_ENABLE;
    LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3;
    LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL;
    LIS302DL_Init(&LIS302DL_InitStruct);
    
    /* Required delay for the MEMS Accelerometre: Turn-on time = 3/Output data Rate 
    = 3/100 = 30ms */
    Delay(30);
    
    DemoEnterCondition = 0x01;
    /* MEMS High Pass Filter configuration */
    LIS302DL_FilterStruct.HighPassFilter_Data_Selection = LIS302DL_FILTEREDDATASELECTION_OUTPUTREGISTER;
    LIS302DL_FilterStruct.HighPassFilter_CutOff_Frequency = LIS302DL_HIGHPASSFILTER_LEVEL_1;
    LIS302DL_FilterStruct.HighPassFilter_Interrupt = LIS302DL_HIGHPASSFILTERINTERRUPT_1_2;
    LIS302DL_FilterConfig(&LIS302DL_FilterStruct);
    
    LIS302DL_Read(Buffer, LIS302DL_OUT_X_ADDR, 6);
    X_Offset = Buffer[0];
    Y_Offset = Buffer[2];
    Z_Offset = Buffer[4];
    
    /* USB configuration */
    Demo_USBConfig();
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {}
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    
    /* Disable SPI1 used to drive the MEMS accelerometre */
    SPI_Cmd(LIS302DL_SPI, DISABLE);
    
    /* Disconnect the USB device */
    DCD_DevDisconnect(&USB_OTG_dev);
    USB_OTG_StopDevice(&USB_OTG_dev);
  }
}
示例#29
0
void systick_init(uint32_t ticks_per_sec)
{
    RCC_ClocksTypeDef rcc_clocks;
	RCC_GetClocksFreq(&rcc_clocks);
	SysTick_Config(rcc_clocks.HCLK_Frequency / ticks_per_sec);
}
示例#30
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  uint8_t *buffptr;
  
  /*!< At this stage the microcontroller clock setting is already configured, 
  this is done through SystemInit() function which is called from startup
  file (startup_stm32f0xx.s) before to branch to application main.
  To reconfigure the default setting of SystemInit() function, refer to
  system_stm32f0xx.c file
  */ 
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* error */ 
    while (1);
  }
  /* Configure clock GPIO, USARTs */
  RCC_Configuration();
  
  /* Configure GPIO Pin Tx/Rx for Usart communication */
  GPIO_Configuration();
  
  /* Configure NVIC */
  NVIC_Configuration();
  
  /* 8xUSARTs configuration --------------------------------------------------*/
  /* 8xUSARTs  configured as follow:
  - BaudRate = 9600 baud  
  - Word Length = 8 Bits
  - One Stop Bit
  - No parity
  - Hardware flow control disabled (RTS and CTS signals)
  - Receive and transmit enabled
  */
  USART_InitStructure.USART_BaudRate = 9600;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  
  /* Prepare all uart to receive a data packet */
  for(UsartIndex = 0; UsartIndex < USART_MAX_INDEX; UsartIndex++)
  {
    USART_Init(UsartInstance[UsartIndex], &USART_InitStructure);
    
    /* Enable 8xUSARTs Receive interrupts */
    USART_ITConfig(UsartInstance[UsartIndex], USART_IT_RXNE, ENABLE);
    
    /* Enable the 8xUSARTs */
    USART_Cmd(UsartInstance[UsartIndex], ENABLE);
  }
  
  /* Infinite Loop */
  while(1)
  {
    /* Set aRxBuffer to 0 */
    memset(aRxBuffer, 0x0, BUFFER_SIZE * USART_MAX_INDEX);
    
    /* When data has been transferred start the next transfer */
    for(UsartIndex = 0; UsartIndex < USART_MAX_INDEX; UsartIndex++)
    { 
      /* Initialize the global variable to handle the data transfer */
      TxCounter = 0;
      ReceiveState = 0;
      
      /* Delay to let time to see counter incrementation on the screen */
      Delay(2000);
      /* Set the data buffptr to use for the transfer */
      if (UsartIndex == 0)
      {
        buffptr = aTxBuffer;
      }
      else
      {
        buffptr = aRxBuffer[UsartIndex];
      }
      
      while(TxCounter < BUFFER_SIZE)
      {   
        /* Send one byte from USART1 to USARTx */
        USART_SendData(UsartInstance[UsartIndex], buffptr[TxCounter++]);
        
        /* Loop until USART1 DR register is empty */ 
        while(USART_GetFlagStatus(UsartInstance[UsartIndex], USART_FLAG_TXE) == RESET)
        {}
      }
      
      while(ReceiveState == 0);
      /* Compares two buffers */
      if(UsartIndex == (USART_MAX_INDEX - 1))
      {
        if( Buffercmp((uint8_t*) aRxBuffer[0], (uint8_t*) aTxBuffer, BUFFER_SIZE))
        {
          /* Error */
          while(1);
        }
      }
      else
      {
        if( Buffercmp((uint8_t*) aRxBuffer[UsartIndex+1], (uint8_t*) aTxBuffer, BUFFER_SIZE))
        {
          /* Error */
          while(1);
        }
      }
      ReceiveState = 0;
    }
    /* Insert delay */
    Delay(2000);
  }
}