Example #1
1
int main(void) {

	RCC_Configuration();

	RCC_ClocksTypeDef RCC_Clocks;
	RCC_GetClocksFreq(&RCC_Clocks);

	EnableClock();

	//LCD_GLASS_Configure_GPIO();
	//LCD_GLASS_Init();

	SysTick_Config((RCC_Clocks.SYSCLK_Frequency / 2) / 1000); // Cannot exceed 16,777,215

	/* Set SysTick Preemption Priority, it's a system handler rather than a regular interrupt */
	//NVIC_SetPriority(SysTick_IRQn, 0x04);

	lcdInit();
	lcdClear();
	lcdXY( 2, 5 );
	lcdStr( "Test");
	//lcdBender();

	// init rtc
	RTC_InitTypeDef rtcInit;
	rtcInit.RTC_HourFormat = RTC_HourFormat_24;
	rtcInit.RTC_AsynchPrediv = 0x7F;
	rtcInit.RTC_SynchPrediv = 0xFF;
	RTC_Init(&rtcInit);

	RTC_TimeTypeDef RTC_TimeStructure;
	RTC_DateTypeDef RTC_DateStructure;

	usart_init();

 	SetRTCClock();

 	GPIO_InitTypeDef gpio_btn;

 	gpio_btn.GPIO_Pin = GPIO_Pin_0;
 	gpio_btn.GPIO_Mode = GPIO_Mode_IN;
 	gpio_btn.GPIO_PuPd = GPIO_PuPd_UP;

 	GPIO_Init(GPIOA, &gpio_btn);

 	int prevSecond = -1;

 	while (1) {

       	//uint8_t __status = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);

       	if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0x00 && !_sent)
       	{
       		_sent = 1;

       		mini_snprintf( strDisp, 22,  "20%02d/%02d/%02d %02d:%02d:%02d Hallo !!!", RTC_DateStructure.RTC_Year, RTC_DateStructure.RTC_Month, RTC_DateStructure.RTC_Date, RTC_TimeStructure.RTC_Hours, RTC_TimeStructure.RTC_Minutes, RTC_TimeStructure.RTC_Seconds);

       		SendSMS("0836325001",strDisp);
       	}

       	if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) != 0x00 && _sent)
       	{
       		_sent = 0;
       	}

       	RTC_GetTime(RTC_Format_BIN, &RTC_TimeStructure );
       	RTC_GetDate(RTC_Format_BIN, &RTC_DateStructure);



       	if ( RTC_TimeStructure.RTC_Seconds != prevSecond )
        {
       		lcdClear();
       		mini_snprintf( strDisp, 11,  "20%02d/%02d/%02d", RTC_DateStructure.RTC_Year, RTC_DateStructure.RTC_Month, RTC_DateStructure.RTC_Date);
       		lcdXY( 0, 0 );
       		lcdStr( strDisp);
       		mini_snprintf( strDisp, 10,  "%02d:%02d:%02d", RTC_TimeStructure.RTC_Hours, RTC_TimeStructure.RTC_Minutes, RTC_TimeStructure.RTC_Seconds );
       		lcdXY( 0, 1 );
       		lcdStr( strDisp);
        	//LCD_GLASS_Clear();
        	//LCD_GLASS_DisplayString( strDisp );
        	prevSecond = RTC_TimeStructure.RTC_Seconds;
        }

			/*if ( usart_available() ) // data available
			{
				//usart_print( "Data Available: " );
				uint8_t ch = usart_read();
				//usart_write(ch);
				//usart_print( "\r\n" );
				SendSMS("836325001","Wynand");
			}*/

  		}


        return 0;
}
Example #2
1
static void cycleCounterInit(void)
{
    RCC_ClocksTypeDef clocks;
    RCC_GetClocksFreq(&clocks);
    usTicks = clocks.SYSCLK_Frequency / 1000000;
}
Example #3
0
/**************************************************************/
//程 序 名: main()
//开 发 者: MingH
//入口参数: 无
//功能说明: 主函数
//**************************************************************/
int main(void)
{
	unsigned char err_code;
	RCC_Config();		// 时钟初始化配置
	Beep_Init();		// 蜂鸣器初始化配置
	Touch_Init();
	Pcie_Gpio_Init();
	Tim3_Init();
	
	RGB_Init();     //RGB 初始化
	RCC_GetClocksFreq(&RCC_ClockFreq);		
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);	
	USB2Serial_Init(); 	// 串口初始化配置
	Pwm_Init();
	Adc_Init();
	I2C_GPIO_Configuration();
	err_code = LIS3DH_Init();
	
	if (NO_ERROR == err_code)
	{
		printf("\r\nLIS3DH Init is succeed! \r\n");
	}
	else
	{
		printf("\r\nLIS3DH Init is failed! \r\n");
	}
	
	RTC_Init(); 		// RTC 初始化配置


	if(SD_Init() == SD_OK) {
	
		printf ("\r\n发现SD卡!\r\n");
	}
	else {
		printf("\r\n没有发现 SD 卡设备! \r\n");
	}
	printf("\r\n\r\n");
	save_sd_detect = SD_Detect(); //初始化SD卡插入状态
	
	SysTick_Delay_ms(500);
	TIM_Cmd(TIM1, DISABLE);
	TIM_CtrlPWMOutputs(TIM1, DISABLE);
	while (1)
	{
		if(read_sd_detect_flag){
			
			if (save_sd_detect != SD_Detect()){
				/* 蜂鸣器响 */
				TIM_Cmd(TIM1, ENABLE);
				TIM_CtrlPWMOutputs(TIM1, ENABLE);
				sd_detect_change = 1; //SD卡插入状态有变
				buzzer_delay = 0;
				if (SD_Detect() != SD_NOT_PRESENT){
						if(SD_Init() == SD_OK) {
							printf ("\r\n发现SD卡!\r\n");
						}
						else {
							printf("\r\n没有发现 SD 卡设备! \r\n");
						}
						printf("\r\n\r\n");
				}
			}
			save_sd_detect = SD_Detect();
			read_sd_detect_flag = 0;
		}
		
		
		Time_Show();	
		Test_Pcie_Gpio();
		Touch_Key_Proc();
		
		if (read_lis3dh_flag){
			Collect_Data(ACCdata);
			for (i=0; i<3; i++){
				if (oldACCdata[i] < ACCdata[i]){
					ACCdiff[i] = ACCdata[i] - oldACCdata[i];
				}
				else{
					ACCdiff[i] = oldACCdata[i] - ACCdata[i];
				}
			}
			RGB_Control(ACCdiff[0]<<1, ACCdiff[1]<<1, ACCdiff[2]<<1);
			for (i=0; i<3; i++){
				oldACCdata[i] = ACCdata[i];
			}
			read_lis3dh_flag = 0;
		}
		if (one_second_flag){
			printf("X=%d, Y=%d, Z=%d\r\n\r\n", ACCdata[1], ACCdata[0], ACCdata[2]);
			Adc_Proc();
			one_second_flag = 0;
		}
	}
}
Example #4
0
int main(void)
{
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  	
  /* Add your application code here
     */
	//SysTick_Type SysTick1;
	//SysTick1.LOAD = 48000;
	//SysTick1.VAL = 0;

	USART1Init();
	USART1print((int32_t)RCC_Clocks.HCLK_Frequency);
	
	SysTick_Config(RCC_Clocks.HCLK_Frequency/10000);
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
  
  /* Configure ADC Channel11 as analog input */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  
  /* ADCs DeInit */  
  ADC_DeInit(ADC1);
  
  /* Initialize ADC structure */
  
	
	

	

	
	
	
	
	ADC_InitTypeDef ADCInit;
	ADC_StructInit(&ADCInit);
	
	ADCInit.ADC_ContinuousConvMode = ENABLE;
	ADCInit.ADC_DataAlign = ADC_DataAlign_Right;
	ADCInit.ADC_ExternalTrigConv = ADC_ExternalTrigConvEdge_None;
	ADCInit.ADC_Resolution = ADC_Resolution_12b;
	ADCInit.ADC_ScanDirection = ADC_ScanDirection_Upward;
	ADC_Init(ADC1, &ADCInit);
		
  /* Convert the ADC1 Channel 11 with 239.5 Cycles as sampling time */ 
  ADC_ChannelConfig(ADC1, ADC_Channel_10 , ADC_SampleTime_1_5Cycles);   

  /* ADC Calibration */
  ADC_GetCalibrationFactor(ADC1);
  
  /* Enable ADCperipheral[PerIdx] */
  ADC_Cmd(ADC1, ENABLE);     
  
  /* Wait the ADCEN falg */
  while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADEN)); 
  
  /* ADC1 regular Software Start Conv */ 
  ADC_StartOfConversion(ADC1);


	USART1println("INIT!");
	
	/* Infinite loop */
	
  while (1)
  {
		++x;
		//while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
    
    //USART1println(ADC_GetConversionValue(ADC1));
  }
}
/**
  * @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;
    
    /* Initialize LEDs to be managed by GPIO */
    STM_EVAL_LEDInit(LED4);
    STM_EVAL_LEDInit(LED3);
    STM_EVAL_LEDInit(LED5);
    STM_EVAL_LEDInit(LED6);
    
    /* SysTick end of count event each 10ms */
    RCC_GetClocksFreq(&RCC_Clocks);
    SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);  
    
    /* Turn OFF all LEDs */
    STM_EVAL_LEDOff(LED4);
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED5);
    STM_EVAL_LEDOff(LED6);
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED4);
      Delay(10);
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED3);
      Delay(10);
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED5);
      Delay(10);
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED6);
      Delay(10);
      togglecounter ++;
      if (togglecounter == 0x10)
      {
        togglecounter = 0x00;
        while (togglecounter < 0x10)
        {
          STM_EVAL_LEDToggle(LED4);
          STM_EVAL_LEDToggle(LED3);
          STM_EVAL_LEDToggle(LED5);
          STM_EVAL_LEDToggle(LED6);
          Delay(10);
          togglecounter ++;
        }
       togglecounter = 0x00;
      }
    }
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    UserButtonPressed = 0x00;
    
    /* TIM4 channels configuration */
    TIM4_Config();
    
    /* Disable all Timer4 channels */
    TIM_CCxCmd(TIM4, TIM_Channel_1, DISABLE);
    TIM_CCxCmd(TIM4, TIM_Channel_2, DISABLE);
    TIM_CCxCmd(TIM4, TIM_Channel_3, DISABLE);
    TIM_CCxCmd(TIM4, TIM_Channel_4, DISABLE);

    /* 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);
  }
}
Example #6
0
OSStatus MicoPwmInitialize( mico_pwm_t pwm_peripheral, uint32_t frequency, float duty_cycle )
{
  TIM_TimeBaseInitTypeDef tim_time_base_structure;
  TIM_OCInitTypeDef       tim_oc_init_structure;
  GPIO_InitTypeDef        gpio_init_structure;
  RCC_ClocksTypeDef       rcc_clock_frequencies;
  const platform_pwm_mapping_t* pwm                 = &pwm_mappings[pwm_peripheral];
  uint16_t                      period              = 0;
  float                         adjusted_duty_cycle = ( ( duty_cycle > 100.0f ) ? 100.0f : duty_cycle );
  
  MicoMcuPowerSaveConfig(false);
  
  RCC_GetClocksFreq( &rcc_clock_frequencies );
  
  if ( pwm->tim == TIM1 || pwm->tim == TIM8 || pwm->tim == TIM9 || pwm->tim == TIM10 || pwm->tim == TIM11 )
  {
    RCC_APB2PeriphClockCmd( pwm->tim_peripheral_clock, ENABLE );
    period = (uint16_t)( rcc_clock_frequencies.PCLK2_Frequency / frequency - 1 ); /* Auto-reload value counts from 0; hence the minus 1 */
  }
  else
  {
    RCC_APB1PeriphClockCmd( pwm->tim_peripheral_clock, ENABLE );
    period = (uint16_t)( 2*rcc_clock_frequencies.PCLK1_Frequency / frequency - 1 ); /* Auto-reload value counts from 0; hence the minus 1 */
  }
  
  RCC_AHB1PeriphClockCmd( pwm->pin->peripheral_clock, ENABLE );
  
  GPIO_PinAFConfig( pwm->pin->bank, pwm->pin->number, pwm->gpio_af );
  gpio_init_structure.GPIO_Pin   = (uint32_t) ( 1 << pwm->pin->number );
  gpio_init_structure.GPIO_Mode  = GPIO_Mode_AF;
  gpio_init_structure.GPIO_Speed = GPIO_Speed_100MHz;
  gpio_init_structure.GPIO_OType = GPIO_OType_PP;
  gpio_init_structure.GPIO_PuPd  = GPIO_PuPd_UP;
  GPIO_Init( pwm->pin->bank, &gpio_init_structure );
  
  
  /* Time base configuration */
  tim_time_base_structure.TIM_Period            = (uint32_t) period;
  tim_time_base_structure.TIM_Prescaler         = (uint16_t) 0;  
  tim_time_base_structure.TIM_ClockDivision     = 0;
  tim_time_base_structure.TIM_CounterMode       = TIM_CounterMode_Up;
  tim_time_base_structure.TIM_RepetitionCounter = 0;
  TIM_TimeBaseInit( pwm->tim, &tim_time_base_structure );
  
  /* PWM1 Mode configuration */
  tim_oc_init_structure.TIM_OCMode       = TIM_OCMode_PWM1;
  tim_oc_init_structure.TIM_OutputState  = TIM_OutputState_Enable;
  tim_oc_init_structure.TIM_OutputNState = TIM_OutputNState_Enable;
  tim_oc_init_structure.TIM_Pulse        = (uint16_t) ( adjusted_duty_cycle * (float) period / 100.0f );
  tim_oc_init_structure.TIM_OCPolarity   = TIM_OCPolarity_High;
  tim_oc_init_structure.TIM_OCNPolarity  = TIM_OCNPolarity_High;
  tim_oc_init_structure.TIM_OCIdleState  = TIM_OCIdleState_Reset;
  tim_oc_init_structure.TIM_OCNIdleState = TIM_OCIdleState_Set;
  
  switch ( pwm->channel )
  {
  case 1:
    {
      TIM_OC1Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC1PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  case 2:
    {
      TIM_OC2Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC2PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  case 3:
    {
      TIM_OC3Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC3PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  case 4:
    {
      TIM_OC4Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC4PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  default:
    {
      break;
    }
  }
  
  MicoMcuPowerSaveConfig(true);
  
  return kNoErr;
}
Example #7
0
/**
 * @brief  Configures TIM10 to measure the LSI oscillator frequency.
 * @param  None
 * @retval LSI Frequency
 */
uint32_t GetLSIFrequency(void) {
	NVIC_InitTypeDef NVIC_InitStructure;
	TIM_ICInitTypeDef TIM_ICInitStructure;
	RCC_ClocksTypeDef RCC_ClockFreq;

	/* Enable the LSI oscillator ************************************************/
	RCC_LSICmd(ENABLE);

	/* Wait till LSI is ready */
	while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET) {
	}

	/* TIM10 configuration *******************************************************/
	/* Enable TIM10 clocks */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM10, ENABLE);

	/* Connect internally the TIM10_CH1 Input Capture to the LSI clock output */
	TIM_RemapConfig(TIM10, TIM10_LSI);

	/* Configure TIM10 presclaer */
	TIM_PrescalerConfig(TIM10, 0, TIM_PSCReloadMode_Immediate);

	/* TIM10 configuration: Input Capture mode ---------------------
	 The LSI oscillator is connected to TIM10 CH1
	 The Rising edge is used as active edge,
	 The TIM10 CCR1 is used to compute the frequency value
	 ------------------------------------------------------------ */
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV8;
	TIM_ICInitStructure.TIM_ICFilter = 0;
	TIM_ICInit(TIM10, &TIM_ICInitStructure);

	/* Enable TIM10 Interrupt channel */
	NVIC_InitStructure.NVIC_IRQChannel = TIM10_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);

	/* Enable TIM10 counter */
	TIM_Cmd(TIM10, ENABLE);

	/* Reset the flags */TIM10->SR = 0;

	/* Enable the CC1 Interrupt Request */
	TIM_ITConfig(TIM10, TIM_IT_CC1, ENABLE);

	/* Wait until the TIM10 get 2 LSI edges (refer to TIM10_IRQHandler() in
	 stm32l1xx_it.c file) ******************************************************/
	while (CaptureNumber != 2) {
	}
	/* Deinitialize the TIM10 peripheral registers to their default reset values */
	TIM_DeInit(TIM10);

	/* Compute the LSI frequency, depending on TIM10 input clock frequency (PCLK1)*/
	/* Get SYSCLK, HCLK and PCLKx frequency */
	RCC_GetClocksFreq(&RCC_ClockFreq);

	/* Get PCLK1 prescaler */
	if ((RCC->CFGR & RCC_CFGR_PPRE1) == 0) {
		/* PCLK1 prescaler equal to 1 => TIMCLK = PCLK1 */
		return ((RCC_ClockFreq.PCLK1_Frequency / PeriodValue) * 8);
	} else { /* PCLK1 prescaler different from 1 => TIMCLK = 2 * PCLK1 */
		return (((2 * RCC_ClockFreq.PCLK1_Frequency) / PeriodValue) * 8);
	}
}
Example #8
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
 GPIO_InitTypeDef GPIO_InitStructure;
 NVIC_InitTypeDef NVIC_InitStructure;
 RCC_ClocksTypeDef RCC_ClockFreq;

  /*!< 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
     */     

  /* Initialize Leds mounted on STM32072B-EVAL*/
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* Turn on LED3 and LED4 */
  STM_EVAL_LEDOn(LED3);
  STM_EVAL_LEDOn(LED4);

  /* This function fills the RCC_ClockFreq structure with the current
     frequencies of different on chip clocks (for debug purpose) **************/
  RCC_GetClocksFreq(&RCC_ClockFreq);

  /* Enable Clock Security System(CSS): this will generate an NMI exception
  when HSE clock fails *****************************************************/
  RCC_ClockSecuritySystemCmd(ENABLE);

  /* Enable and configure RCC global IRQ channel, will be used to manage HSE ready 
     and PLL ready interrupts. 
     These interrupts are enabled in stm32f0xx_it.c file **********************/
#ifdef USE_STM320518_EVAL
  NVIC_InitStructure.NVIC_IRQChannel = RCC_IRQn;
#else 
  NVIC_InitStructure.NVIC_IRQChannel = RCC_CRS_IRQn; 
#endif /* USE_STM320518_EVAL */
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Output HSE clock on MCO1 pin(PA8) ****************************************/     
  /* Enable the GPIOA Clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

  /* MCO pin configuration: PA8 */
  GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
  GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_8;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_0);

  /* Output System Clock on MCO pin */
#ifdef USE_STM320518_EVAL
  RCC_MCOConfig(RCC_MCOSource_SYSCLK); 
#else 
  RCC_MCOConfig(RCC_MCOSource_SYSCLK, RCC_MCOPrescaler_1);  
#endif /* USE_STM320518_EVAL */   

  while (1)
  {
    /* Toggle LED4 */
    STM_EVAL_LEDToggle(LED4);

    /* Insert a delay */
    Delay(0x4FFFF);

    /* Toggle LED3 */
    STM_EVAL_LEDToggle(LED3);

    /* Insert a delay */
    Delay(0x3FFFF);
  }
}
Example #9
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
 
	SPI_InitTypeDef SPI_InitStructure;
	
	
	uint8_t recieved_val = 0;
	
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       files before to branch to application main.
       To reconfigure the default setting of SystemInit() function, 
       refer to system_stm32f4xx.c file */

  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
  
  /* Add your application code here */
  /* Insert 50 ms delay */
  Delay(5);
	
	
	
	
  /* Output HSE clock on MCO1 pin(PA8) ****************************************/ 
  /* Enable the GPIOA peripheral */ 
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
  
  /* Configure MCO1 pin(PA8) in alternate function */
//  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
//  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);
    
//  /* HSE clock selected to output on MCO1 pin(PA8)*/
//  RCC_MCO1Config(RCC_MCO1Source_HSE, RCC_MCO1Div_1);
  
  
  /* Output SYSCLK/4 clock on MCO2 pin(PC9) ***********************************/ 
  /* Enable the GPIOACperipheral */ 
//  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
//  
//  /* Configure MCO2 pin(PC9) in alternate function */
//  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
//  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(GPIOC, &GPIO_InitStructure);
//    
//  /* SYSCLK/4 clock selected to output on MCO2 pin(PC9)*/
//  RCC_MCO2Config(RCC_MCO2Source_SYSCLK, RCC_MCO2Div_4);
  
	
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_4;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType =GPIO_OType_PP;
	
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType =GPIO_OType_PP;
	
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_3;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType =GPIO_OType_PP;
	
	GPIO_Init(GPIOI, &GPIO_InitStructure);
	
	GPIO_PinAFConfig(GPIOI, GPIO_PinSource1, GPIO_AF_SPI2);
	GPIO_PinAFConfig(GPIOI, GPIO_PinSource3, GPIO_AF_SPI2);
	
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4 ;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
//	SPI1_InitStructure.SPI_CRCPolynomial = 
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft | SPI_NSSInternalSoft_Set;
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
	

  
	SPI_Init(SPI1, &SPI_InitStructure);
	SPI_Init(SPI2, &SPI_InitStructure);
	
	SPI_Cmd(SPI2, ENABLE);

		 
	PWM_Pin_Config();
  Timer3_PWM_Output_Config(Period, Prescaler);	 
  /* Infinite loop */
  while (1)
  {
//		SPI2_Send(0XAA);
  }
}
Example #10
0
int main(void)
{
	int scope1dt,scope1t,scope1s,scope1d,scope1j;
	int scope2dt,scope2t,scope2s,scope2d,scope2j;
	char znakr;
	char znak;
	GPIO_InitTypeDef GPIO_str;
	uint8_t ii;
	uint8_t i = 0;
  /* SysTick end of count event each 0,01ms 0,00001*/// 0,01ms -100000
	  RCC_GetClocksFreq(&RCC_Clocks);
	  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100000);

  /* Accelerometer Configuration */
  Acc_Config();
  Demo_GyroConfig();
  ii = SystemCoreClock;   /* This is a way to read the System core clock */

  CONF_TIMERS();
  CONF_PWMIN();

   confI2C();
   while(1)
   I2C_start();
/////////// Przyciski
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
GPIO_str.GPIO_Pin= GPIO_Pin_4 | GPIO_Pin_5;
GPIO_str.GPIO_Mode=GPIO_Mode_IN;
GPIO_str.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_str.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_str);

ii = 0;
USART2_Init(115200);



 GPIO_SetBits(GPIOD, GPIO_Pin_0);


 	LEFT =3400;
 	RIGHT=3400;
 	FRONT=3400;
 	REAR=3400;
 	//delay_ms(4000);



 while (1)
 {

	esf=SystemCoreClock/360/(TIM2->CCR2);

	esd = (TIM2->CCR1*100);///(TIM2->CCR2);
	throttle=(int)(esd*32.0/156.0-1236.0);
	esf3=SystemCoreClock/360/(TIM3->CCR2);
	if(throttle>6600)
		throttle=3400;
	esd3 = (TIM3->CCR1*100);///(TIM3->CCR2);
	pitch_zadany=(float)(-6.0*esd3/1800.0+100.0)+0.0;
	if(pitch_zadany>40 || pitch_zadany<-40)
		pitch_zadany=0;

	esd4 = (TIM4->CCR1*100);
	roll_zadany=(float)(-6.0*esd4/1800.0+100.0);

	if(roll_zadany>40 || roll_zadany<-40)
		roll_zadany=0;

	//esd5 =(TIM8->CCR2*100)/TIM8->CCR1;
	//yaw_zadany=(float)(-6.0*esd5/1800.0+100.0);





	//if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_5)==0)
	//flaga=0;









	//IMU///////////////////////////////////////////////////////
	Acc_ReadData(AccBuffer);
	for(i=0;i<3;i++)
	AccBuffer[i] /= 100.0f;
	acc_x=AccBuffer[0];
	acc_y=AccBuffer[1];
	acc_z=AccBuffer[2];
	Demo_GyroReadAngRate(Buffer);
	gyr_x=Buffer[0];
	gyr_y=Buffer[1];
	gyr_z=Buffer[2];
	MadgwickAHRSupdateIMU( -gyr_y*0.01745,  gyr_x*0.01745,  gyr_z*0.01745,  acc_x,  acc_y,  acc_z);
	roll=180/PI*atan2(2*(q2*q3+q0*q1),1-2*(q1*q1+q2*q2));//(q0*q0-q1*q1-q2*q2+q3*q3));
	pitch=180/PI*asin(-2*(q1*q3-q0*q2));
	yaw=180/PI*atan2(2*(q1*q2+q0*q3),(1-2*(q3*q3+q2*q2)));


	scope1=PIDY*1000;//niebieski
	scope2=yaw*1000;//czerwony
	if(scope1>0)
		znak='+';
	else
		znak='-';
	if(scope2>0)
		znakr='+';
		else
		znakr='-';
	scope1=abs(scope1);
	scope2=abs(scope2);
	CZAS_S=(float)CZAS/100000.0;
	CZAS=0;
	scope1dt=scope1/10000;
	scope1t=scope1/1000-scope1dt*10;
	scope1s=scope1/100-scope1dt*100-scope1t*10;
	scope1d=scope1/10-scope1dt*1000-scope1t*100-scope1s*10;
	scope1j=scope1-scope1dt*10000-scope1t*1000-scope1s*100-scope1d*10;

	scope2dt=scope2/10000;
	scope2t=scope2/1000-scope2dt*10;
	scope2s=scope2/100-scope2dt*100-scope2t*10;
	scope2d=scope2/10-scope2dt*1000-scope2t*100-scope2s*10;
	scope2j=scope2-scope2dt*10000-scope2t*1000-scope2s*100-scope2d*10;
	printf("%c%d%d%d%d%d %c%d%d%d%d%d\r\n",znak,scope1dt,scope1t,scope1s,scope1d,scope1j,znakr,scope2dt,scope2t,scope2s,scope2d,scope2j);




	/*PIDY=-PIDyawrate(yaw_zadany, yaw);
	rollratezadane=PIDroll(roll_zadany, roll);
	PIDR=PIDrollrate(rollratezadane, -gyr_y);
	speedLeft=(int)((float)throttle+PIDR-PIDY);//throttle+PIDR;
	speedRight=(int)((float)throttle-PIDR-PIDY);
	pitchratezadane=PIDpitch(pitch_zadany, pitch);
	PIDP=PIDpitchrate(pitchratezadane, gyr_x);//float PIDpitchrollrate(float zadana, float aktualna)
	speedFront=(int)((float)throttle-PIDP+PIDY);
	speedRear=(int)((float)throttle+PIDP+PIDY);
*/
	if(speedFront>speedmax)
		speedFront=speedmax;
	else if(speedFront<speedmin)
		speedFront=speedmin;
	else
		;
	if(speedRear>speedmax)
		speedRear=speedmax;
	else if(speedRear<speedmin)
		speedRear=speedmin;
	else
		;
	if(speedLeft>speedmax)
		speedLeft=speedmax;
	else if(speedLeft<speedmin)
		speedLeft=speedmin;
	else
		;
	if(speedRight>speedmax)
		speedRight=speedmax;
	else if(speedRight<speedmin)
		speedRight=speedmin;
	else
		;

	if(throttle>3450)
	{
	LEFT =(int)speedLeft;
	RIGHT=(int)speedRight;
	FRONT=3400;//(int)speedFront;
	REAR=3400;//(int)speedRear;
	}
	else
	{
		LEFT =3400;
		RIGHT=3400;
		FRONT=3400;
		REAR=3400;
	}






 }

  return 0;
}
Example #11
0
/**
 * systickTimerConfig
 * @note SysTick_Config : SYSCLK_Frequency / 1000
 */
void systickTimerConfig() {
  RCC_ClocksTypeDef RCC_CLOCKS;
  RCC_GetClocksFreq(&RCC_CLOCKS);
  while(SysTick_Config(RCC_CLOCKS.SYSCLK_Frequency / 1000)); // set period 1/1000s(1ms)
  usTicks = RCC_CLOCKS.SYSCLK_Frequency / 1000000;
}
Example #12
0
File: main.c Project: ADTL/ARMWork
int main(void) {
	uint16_t bits;
	uint32_t intval = 40;
	uint32_t tnow;
	char tmp[92];
	RCC_ClocksTypeDef RCC_Clocks;
	uint16_t i;
	
	TIM2_timer_start();

	usart_begin(&USerial3, USART3, PC11, PC10, 19200);

	usart_print(&USerial3, 
			"Happy are those who know they are spiritually poor; \n"
			"The kingdom of heaven belongs to them!\n");
	usart_flush(&USerial3);
	
	RCC_GetClocksFreq(&RCC_Clocks);

	sprintf(tmp, "SYSCLK = %ul\n", RCC_Clocks.SYSCLK_Frequency);
	usart_print(&USerial3, tmp);
	sprintf(tmp, "PCLK1 = %ul\n", RCC_Clocks.PCLK1_Frequency);
	usart_flush(&USerial3);

	GPIOMode(PinPort(PD12),
			(PinBit(PD12) | PinBit(PD13) | PinBit(PD14) | PinBit(PD15)), OUTPUT,
			FASTSPEED, PUSHPULL, NOPULL);
			/*
	spi_begin(SPI2, PB13, PB14, PB15, PB12);
	digitalWrite(PB12, HIGH);
*/
	I2C1_Init();
/*
	i2c_begin(&Wire1, PB9, PB8, 100000);
	lcd.init(&Wire1);
	lcd.begin();
	lcd.setContrast(46);
	lcd.print("Yappee!");       // Classic Hello World!
*/
	bits = GPIO_ReadOutputData(GPIOD );
	GPIOWrite(GPIOD, PinBit(PD13) | (bits & 0x0fff));
	delay_ms(intval);
	tnow = millis() / 1000;
	while (tnow == millis() / 1000)
		;
	tnow = millis() / 1000;

	while (1) {
		bits = GPIO_ReadOutputData(GPIOD );

		GPIOWrite(GPIOD, PinBit(PD13) | (bits & 0x0fff));
		delay_ms(intval);
		GPIOWrite(GPIOD, PinBit(PD14) | (bits & 0x0fff));
		delay_ms(intval);
		GPIOWrite(GPIOD, PinBit(PD15) | (bits & 0x0fff));
		delay_ms(intval);
		GPIOWrite(GPIOD, PinBit(PD12) | (bits & 0x0fff));
		delay_ms(intval);
		//
		bits &= 0x0fff;
		switch ((tnow % 60) / 15) {
		case 3:
			bits |= PinBit(PD12);
		case 2:
			bits |= PinBit(PD15);
		case 1:
			bits |= PinBit(PD14);
		case 0:
		default:
			bits |= PinBit(PD13);
			break;
		}
		GPIOWrite(GPIOD, bits);

		while (tnow == millis() / 1000);
		tnow = millis() / 1000;

		//Serial3.print(tmp);
		sprintf(tmp, "%04ld\n", millis());
		usart_print(&USerial3, tmp);

		/*
		digitalWrite(PB12, LOW);
		spi_transfer(SPI2, (uint8_t *) tmp, 8);
		digitalWrite(PB12, HIGH);
*/
		i = 0;
		if (usart_available(&USerial3) > 0) {
			while (usart_available(&USerial3) > 0 && i < 92) {
				tmp[i++] = (char) usart_read(&USerial3);
			}
			tmp[i] = 0;
			usart_print(&USerial3, "> ");
			usart_print(&USerial3, tmp);
			usart_print(&USerial3, "\n");
		}

	}
	return 0;
}
Example #13
0
// todo - perhaps there should be some global resource management for gpio
// this function would fail if the i2c pins have already been defined for
// use by another python object
// as it is, this always returns true (unless i2c_port is invalid)
static bool _i2c_init(pyb_i2c_t i2c_port) {
    GPIO_InitTypeDef GPIO_InitStructure;

    I2C_TypeDef *i2c = _i2c_port_addr(i2c_port);
    if (i2c == NULL)
        return false;

    if (i2c_port == PYB_I2C_1) {
        if (i2c1_port_initialized == true) {
            return true;
        }
        RCC->APB1ENR |= RCC_APB1ENR_I2C1EN; // enable I2C1

        // PB6=SCL, PB7=SDA
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
        GPIO_Init(GPIOB, &GPIO_InitStructure);

        // alternate functions for SCL and SDA
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_I2C1);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_I2C1);


        i2c1_port_initialized = true;
    }

    if (i2c_port == PYB_I2C_2) {
        if (i2c2_port_initialized == true) {
            return true;
        }
        RCC->APB1ENR |= RCC_APB1ENR_I2C2EN; // enable I2C2

        // PB10=SCL, PB11=SDA
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
        GPIO_Init(GPIOB, &GPIO_InitStructure);

        // alternate functions for SCL and SDA
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_I2C2);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_I2C2);

        i2c2_port_initialized = true;
    }

    // get clock speeds
    RCC_ClocksTypeDef rcc_clocks;
    RCC_GetClocksFreq(&rcc_clocks);

    // disable the I2C peripheral before we configure it
    i2c->CR1 &= ~I2C_CR1_PE;

    // program peripheral input clock
    i2c->CR2 = 4; // no interrupts; 4 MHz (hopefully!) (could go up to 42MHz)

    // configure clock control reg
    uint32_t freq = rcc_clocks.PCLK1_Frequency / (100000 << 1); // want 100kHz, this is the formula for freq
    i2c->CCR = freq; // standard mode (speed), freq calculated as above

    // configure rise time reg
    i2c->TRISE = (rcc_clocks.PCLK1_Frequency / 1000000) + 1; // formula for trise, gives maximum rise time

    // enable the I2C peripheral
    i2c->CR1 |= I2C_CR1_PE;

    return true;
}
Example #14
0
/**
 * @brief Early initialization before heap and global initializations.
 */
void early_init()
{
	RCC_ClocksTypeDef SYS_Clocks;
	/* Enable HSE */   
	RCC_HSEConfig(RCC_HSE_ON);
	/* Wait till HSE is ready and if Time out is reached exit */
	while(RCC_WaitForHSEStartUp()!=SUCCESS);
	RCC_SYSCLKConfig(RCC_SYSCLKSource_HSE);
	//RCC_GetClocksFreq(&SYS_Clocks);

	SystemInit();
	SystemCoreClockUpdate();
	RCC_GetClocksFreq(&SYS_Clocks);

	/* Enable Peripheral Clocks... */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

	/* Enable Peripheral Clocks... */
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOH,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOI,ENABLE);
	
	//RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	//RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
	//RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
	//RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4,ENABLE);
	//RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5,ENABLE);
	//RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);

	/* PORT A */
	GPIOA->MODER = CARIBOU_PORTA_MODE;
	GPIOA->OTYPER = CARIBOU_PORTA_OTYPER;
	GPIOA->OSPEEDR = CARIBOU_PORTA_OSPEEDR;
	GPIOA->PUPDR = CARIBOU_PORTA_PUPDR;
	GPIOA->AFR[0] = CARIBOU_PORTA_AFRL;
	GPIOA->AFR[1] = CARIBOU_PORTA_AFRH;
	/* POST B */
	GPIOB->MODER = CARIBOU_PORTB_MODE;
	GPIOB->OTYPER = CARIBOU_PORTB_OTYPER;
	GPIOB->OSPEEDR = CARIBOU_PORTB_OSPEEDR;
	GPIOB->PUPDR = CARIBOU_PORTB_PUPDR;
	GPIOB->AFR[0] = CARIBOU_PORTB_AFRL;
	GPIOB->AFR[1] = CARIBOU_PORTB_AFRH;
	/* POST C */
	GPIOC->MODER = CARIBOU_PORTC_MODE;
	GPIOC->OTYPER = CARIBOU_PORTC_OTYPER;
	GPIOC->OSPEEDR = CARIBOU_PORTC_OSPEEDR;
	GPIOC->PUPDR = CARIBOU_PORTC_PUPDR;
	GPIOC->AFR[0] = CARIBOU_PORTC_AFRL;
	GPIOC->AFR[1] = CARIBOU_PORTC_AFRH;
	/* POST D */
	GPIOD->MODER = CARIBOU_PORTD_MODE;
	GPIOD->OTYPER = CARIBOU_PORTD_OTYPER;
	GPIOD->OSPEEDR = CARIBOU_PORTD_OSPEEDR;
	GPIOD->PUPDR = CARIBOU_PORTD_PUPDR;
	GPIOD->AFR[0] = CARIBOU_PORTD_AFRL;
	GPIOD->AFR[1] = CARIBOU_PORTD_AFRH;
	/* POST E */
	GPIOE->MODER = CARIBOU_PORTE_MODE;
	GPIOE->OTYPER = CARIBOU_PORTE_OTYPER;
	GPIOE->OSPEEDR = CARIBOU_PORTE_OSPEEDR;
	GPIOE->PUPDR = CARIBOU_PORTE_PUPDR;
	GPIOE->AFR[0] = CARIBOU_PORTE_AFRL;
	GPIOE->AFR[1] = CARIBOU_PORTE_AFRH;
	/* POST F */
	GPIOF->MODER = CARIBOU_PORTF_MODE;
	GPIOF->OTYPER = CARIBOU_PORTF_OTYPER;
	GPIOF->OSPEEDR = CARIBOU_PORTF_OSPEEDR;
	GPIOF->PUPDR = CARIBOU_PORTF_PUPDR;
	GPIOF->AFR[0] = CARIBOU_PORTF_AFRL;
	GPIOF->AFR[1] = CARIBOU_PORTF_AFRH;
	/* POST G */
	GPIOG->MODER = CARIBOU_PORTG_MODE;
	GPIOG->OTYPER = CARIBOU_PORTG_OTYPER;
	GPIOG->OSPEEDR = CARIBOU_PORTG_OSPEEDR;
	GPIOG->PUPDR = CARIBOU_PORTG_PUPDR;
	GPIOG->AFR[0] = CARIBOU_PORTG_AFRL;
	GPIOG->AFR[1] = CARIBOU_PORTG_AFRH;
	/* POST H */
	GPIOH->MODER = CARIBOU_PORTH_MODE;
	GPIOH->OTYPER = CARIBOU_PORTH_OTYPER;
	GPIOH->OSPEEDR = CARIBOU_PORTH_OSPEEDR;
	GPIOH->PUPDR = CARIBOU_PORTH_PUPDR;
	GPIOH->AFR[0] = CARIBOU_PORTH_AFRL;
	GPIOH->AFR[1] = CARIBOU_PORTH_AFRH;
	/* POST I */
	GPIOI->MODER = CARIBOU_PORTI_MODE;
	GPIOI->OTYPER = CARIBOU_PORTI_OTYPER;
	GPIOI->OSPEEDR = CARIBOU_PORTI_OSPEEDR;
	GPIOI->PUPDR = CARIBOU_PORTI_PUPDR;
	GPIOI->AFR[0] = CARIBOU_PORTI_AFRL;
	GPIOI->AFR[1] = CARIBOU_PORTI_AFRH;
}
Example #15
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  RCC_ClocksTypeDef RCC_Clocks;

  /*!< 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
     */  

  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);

  /* Initialize LEDs and LCD available on STM324xG-EVAL board *****************/
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* Initialize the LCD */
  STM324xG_LCD_Init();

  /* Display message on STM324xG-EVAL LCD *************************************/
  /* Clear the LCD */ 
  LCD_Clear(White);

  /* Set the LCD Back Color */
  LCD_SetBackColor(Blue);
  /* Set the LCD Text Color */
  LCD_SetTextColor(White);
  LCD_DisplayStringLine(LINE(0), (uint8_t *)MESSAGE1);
  LCD_DisplayStringLine(LINE(1), (uint8_t *)MESSAGE2);
  LCD_DisplayStringLine(LINE(2), (uint8_t *)MESSAGE3);

  /* Turn on LEDs available on STM324xG-EVAL **********************************/
  STM_EVAL_LEDOn(LED1);
  STM_EVAL_LEDOn(LED2);
  STM_EVAL_LEDOn(LED3);
  STM_EVAL_LEDOn(LED4);

  /* Add your application code here
     */

  /* Infinite loop */
  while (1)
  {
    /* Toggle LD4 */
    STM_EVAL_LEDToggle(LED4);

    /* Insert 50 ms delay */
    Delay(5);

    /* Toggle LD2 */
    STM_EVAL_LEDToggle(LED2);

    /* Insert 50 ms delay */
    Delay(5);
  }
}
Example #16
0
OSStatus platform_pwm_init( const platform_pwm_t* pwm, uint32_t frequency, float duty_cycle )
{
  TIM_TimeBaseInitTypeDef tim_time_base_structure;
  TIM_OCInitTypeDef       tim_oc_init_structure;
  RCC_ClocksTypeDef       rcc_clock_frequencies;
  uint16_t                period              = 0;
  float                   adjusted_duty_cycle = ( ( duty_cycle > 100.0f ) ? 100.0f : duty_cycle );
  OSStatus                err                 = kNoErr;
  
  require_action_quiet( pwm != NULL, exit, err = kParamErr);

  platform_mcu_powersave_disable();

  RCC_GetClocksFreq( &rcc_clock_frequencies );
  
  if ( pwm->tim == TIM1 || pwm->tim == TIM8 || pwm->tim == TIM9 || pwm->tim == TIM10 || pwm->tim == TIM11 )
  {
    RCC_APB2PeriphClockCmd( pwm->tim_peripheral_clock, ENABLE );
    period = (uint16_t)( rcc_clock_frequencies.PCLK2_Frequency / frequency - 1 ); /* Auto-reload value counts from 0; hence the minus 1 */
  }
  else
  {
    RCC_APB1PeriphClockCmd( pwm->tim_peripheral_clock, ENABLE );
    period = (uint16_t)( rcc_clock_frequencies.PCLK1_Frequency / frequency - 1 ); /* Auto-reload value counts from 0; hence the minus 1 */
  }
    
  /* Set alternate function */
  platform_gpio_set_alternate_function( pwm->pin->port, pwm->pin->pin_number, GPIO_OType_PP, GPIO_PuPd_UP, pwm->gpio_af );
  
  /* Time base configuration */
  tim_time_base_structure.TIM_Period            = (uint32_t) period;
  tim_time_base_structure.TIM_Prescaler         = (uint16_t) 1;  /* Divide clock by 1+1 to enable a count of high cycle + low cycle = 1 PWM cycle */
  tim_time_base_structure.TIM_ClockDivision     = 0;
  tim_time_base_structure.TIM_CounterMode       = TIM_CounterMode_Up;
  tim_time_base_structure.TIM_RepetitionCounter = 0;
  TIM_TimeBaseInit( pwm->tim, &tim_time_base_structure );
  
  /* PWM1 Mode configuration */
  tim_oc_init_structure.TIM_OCMode       = TIM_OCMode_PWM1;
  tim_oc_init_structure.TIM_OutputState  = TIM_OutputState_Enable;
  tim_oc_init_structure.TIM_OutputNState = TIM_OutputNState_Enable;
  tim_oc_init_structure.TIM_Pulse        = (uint16_t) ( adjusted_duty_cycle * (float) period / 100.0f );
  tim_oc_init_structure.TIM_OCPolarity   = TIM_OCPolarity_High;
  tim_oc_init_structure.TIM_OCNPolarity  = TIM_OCNPolarity_High;
  tim_oc_init_structure.TIM_OCIdleState  = TIM_OCIdleState_Reset;
  tim_oc_init_structure.TIM_OCNIdleState = TIM_OCIdleState_Set;
  
  switch ( pwm->channel )
  {
  case 1:
    {
      TIM_OC1Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC1PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  case 2:
    {
      TIM_OC2Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC2PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  case 3:
    {
      TIM_OC3Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC3PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  case 4:
    {
      TIM_OC4Init( pwm->tim, &tim_oc_init_structure );
      TIM_OC4PreloadConfig( pwm->tim, TIM_OCPreload_Enable );
      break;
    }
  default:
    {
      break;
    }
  }

exit:  
  platform_mcu_powersave_enable();
  return err;
}
TM_TIMER_PROPERTIES_Result_t TM_TIMER_PROPERTIES_GetTimerProperties(TIM_TypeDef* TIMx, TM_TIMER_PROPERTIES_t* Timer_Data) {
	RCC_ClocksTypeDef RCC_ClocksStruct;

	/* Get clocks */
	RCC_GetClocksFreq(&RCC_ClocksStruct);
	
	/* All timers have 16-bit prescaler */
	Timer_Data->MaxPrescaler = 0xFFFF;
	
	if (0 /* 32bit timers with PCLK2 max frequency */
#ifdef TIM2
		|| TIMx == TIM2
#endif
#ifdef TIM5
		|| TIMx == TIM5
#endif
	) {
		Timer_Data->TimerFrequency = RCC_ClocksStruct.PCLK2_Frequency;	/* Clock */
		Timer_Data->MaxPeriod = 0xFFFFFFFF;								/* Max period */
		
		/* Timer valid */
		return TM_TIMER_PROPERTIES_Result_Ok;
	} else if (0	/* 16bit timers with HCLK clock frequency */
#ifdef TIM1
		|| TIMx == TIM1
#endif
#ifdef TIM8
		|| TIMx == TIM8
#endif
#ifdef TIM9
		|| TIMx == TIM9
#endif
#ifdef TIM10
		|| TIMx == TIM10
#endif
#ifdef TIM11
		|| TIMx == TIM11
#endif
	) {
		Timer_Data->TimerFrequency = RCC_ClocksStruct.HCLK_Frequency;	/* Clock */
		Timer_Data->MaxPeriod = 0xFFFF;									/* Max period */
		
		/* Timer valid */
		return TM_TIMER_PROPERTIES_Result_Ok;
	} else if (0	/* 16bit timers with PCLK2 clock frequency */
#ifdef TIM3
		|| TIMx == TIM3
#endif
#ifdef TIM4
		|| TIMx == TIM4
#endif
#ifdef TIM6
		|| TIMx == TIM6
#endif
#ifdef TIM7
		|| TIMx == TIM7
#endif
#ifdef TIM12
		|| TIMx == TIM12
#endif
#ifdef TIM13
		|| TIMx == TIM13
#endif
#ifdef TIM14
		|| TIMx == TIM14
#endif
	) {
		Timer_Data->TimerFrequency = RCC_ClocksStruct.PCLK2_Frequency;	/* Clock */
		Timer_Data->MaxPeriod = 0xFFFF;									/* Max period */
		
		/* Timer valid */
		return TM_TIMER_PROPERTIES_Result_Ok;
	}
	
	/* Timer is not valid */
	return TM_TIMER_PROPERTIES_Result_TimerNotValid;
}
Example #18
0
int main(void)
{
	RCC_ClocksTypeDef RCC_Clocks;
	RCC_GetClocksFreq(&RCC_Clocks);
	/* SysTick event each 1ms */
	SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000);

	DELAY_Init();
	USB_Init(0);
	
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_OUT;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_13;       
	GPIO_Init(GPIOB, &GPIO_InitStructure);  
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_12;       
	GPIO_Init(GPIOB, &GPIO_InitStructure);  
	
	//buttons
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IN;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_4;       
	GPIO_Init(GPIOC, &GPIO_InitStructure);  
	
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_6;       
	GPIO_Init(GPIOC, &GPIO_InitStructure);  
	buttonsInitialized=1;
	
	int loopcount = 0;
	while(1)
	{
		midi_package_t rpack;

		int recv = USB_MIDI_PackageReceive(&rpack);

		if(recv != -1)
		{
			if(rpack.velocity > 50)
			{
				GPIOB->ODR           |=       1<<13;
			}
			else
			{
				GPIOB->ODR           &=       ~(1<<13);
			}
		}

		loopcount++;
		if((loopcount == 50)||(loopcount == 150))
		{
			if(USB_MIDI_CheckAvailable(0))
			{
				GPIOB->ODR           &=       ~(1<<12);
			}
		}
		if((loopcount == 100)||(loopcount == 200))
		{
			if(USB_MIDI_CheckAvailable(0))
			{
				GPIOB->ODR           |=       1<<12;
			}

			if(loopcount==200)
				loopcount = 0;
  		
		}
		
		if(get_key_press(KEY_A))
		{
		
			midi_package_t package;

			package.type     = CC;
			package.event    = CC;
			package.note     = 7;
			package.velocity = 100;

	
			USB_MIDI_PackageSend_NonBlocking(package);
		}

		if(get_key_press(KEY_B))
		{
		
			midi_package_t package;

			package.type     = CC;
			package.event    = CC;
			package.note     = 7;
			package.velocity = 50;

	
			USB_MIDI_PackageSend_NonBlocking(package);
		}
			
		DELAY_Wait_uS(1000);
	}


}
Example #19
0
/**
  * @brief  Configures TIM5 to measure the LSI oscillator frequency. 
  * @param  None
  * @retval LSI Frequency
  */
uint32_t GetLSIFrequency(void)
{
  NVIC_InitTypeDef   NVIC_InitStructure;
  TIM_ICInitTypeDef  TIM_ICInitStructure;
  RCC_ClocksTypeDef  RCC_ClockFreq;

#ifndef NO_MICO_RTOS
  mico_rtos_init_semaphore(&_measureLSIComplete_SEM, 1);
#else
  _measureLSIComplete_SEM = false;
#endif


  /* Enable the LSI oscillator ************************************************/
  RCC_LSICmd(ENABLE);
  
  /* Wait till LSI is ready */
  while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)
  {}
  
  /* TIM5 configuration *******************************************************/ 
  /* Enable TIM5 clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
  
  /* Connect internally the TIM5_CH4 Input Capture to the LSI clock output */
  TIM_RemapConfig(TIM5, TIM5_LSI);

  /* Configure TIM5 presclaer */
  TIM_PrescalerConfig(TIM5, 0, TIM_PSCReloadMode_Immediate);
  
  /* TIM5 configuration: Input Capture mode ---------------------
     The LSI oscillator is connected to TIM5 CH4
     The Rising edge is used as active edge,
     The TIM5 CCR4 is used to compute the frequency value 
  ------------------------------------------------------------ */
  TIM_ICInitStructure.TIM_Channel = TIM_Channel_4;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV8;
  TIM_ICInitStructure.TIM_ICFilter = 0;
  TIM_ICInit(TIM5, &TIM_ICInitStructure);
  
  /* Enable TIM5 Interrupt channel */
  NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable TIM5 counter */
  TIM_Cmd(TIM5, ENABLE);

  /* Reset the flags */
  TIM5->SR = 0;
    
  /* Enable the CC4 Interrupt Request */  
  TIM_ITConfig(TIM5, TIM_IT_CC4, ENABLE);

  /* Wait until the TIM5 get 2 LSI edges (refer to TIM5_IRQHandler()) *********/
#ifndef NO_MICO_RTOS
  mico_rtos_get_semaphore(&_measureLSIComplete_SEM, MICO_WAIT_FOREVER);
  mico_rtos_deinit_semaphore( &_measureLSIComplete_SEM );
  _measureLSIComplete_SEM = NULL;
#else
  while( _measureLSIComplete_SEM == false);
#endif

  /* Deinitialize the TIM5 peripheral registers to their default reset values */
  TIM_ITConfig(TIM5, TIM_IT_CC4, DISABLE);
  TIM_DeInit(TIM5);
  NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 8;
  NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Compute the LSI frequency, depending on TIM5 input clock frequency (PCLK1)*/
  /* Get SYSCLK, HCLK and PCLKx frequency */
  RCC_GetClocksFreq(&RCC_ClockFreq);

  /* Get PCLK1 prescaler */
  if ((RCC->CFGR & RCC_CFGR_PPRE1) == 0)
  { 
    /* PCLK1 prescaler equal to 1 => TIMCLK = PCLK1 */
    return ((RCC_ClockFreq.PCLK1_Frequency / PeriodValue) * 8);
  }
  else
  { /* PCLK1 prescaler different from 1 => TIMCLK = 2 * PCLK1 */
    return (((2 * RCC_ClockFreq.PCLK1_Frequency) / PeriodValue) * 8) ;
  }
}
Example #20
0
RES_CODE HAL_ETH_Init(ETH_TypeDef* mac, const eth_mac_cfg_t* cfg)
{
	uint32_t tmpreg;
	uint32_t res;
	RCC_ClocksTypeDef  clocks;


	TRACELN("ETH Init");
	/* Select MII or RMII Mode*/
	if(cfg->mac_cfg_flags & MAC_CFG_FLG_IFCE_MII_RMII)
	{
		tmpreg = 0;
		do
		{
			mac->ETH_DMABMR |= ETH_DMABMR_SR;
			SYSCFG->SYSCFG_PMC |= SYSCFG_PMC_MII_RMII;
			if(++tmpreg > PHY_CONFIG_DELAY)
			{
				TRACEPHY(mac, cfg, "ETH NO PHY CLK!!");
				break;
			}
			tsk_sleep(1);
		} while (!(SYSCFG->SYSCFG_PMC & SYSCFG_PMC_MII_RMII));
	}
	else
		SYSCFG->SYSCFG_PMC &= ~SYSCFG_PMC_MII_RMII;

	/* Ethernet Software reset */
	/* Set the SWR bit: resets all MAC subsystem internal registers and logic */
	/* After reset all the registers holds their respective reset values */
	mac->ETH_DMABMR |= ETH_DMABMR_SR;

	/* Wait for software reset */
	tmpreg = 0;
	while (mac->ETH_DMABMR & ETH_DMABMR_SR)
	{
		tsk_sleep(1);
		if(++tmpreg > PHY_CONFIG_DELAY)
		{
			TRACEPHY(mac, cfg, "ETH MAC RST!!");
			break;
		}
	}

	/*-------------------------------- MAC Initialization ----------------------*/

	TRACEPHY(mac, cfg, "ETH PHY:");

	/* Get the ETHERNET MACMIIAR value */
	tmpreg = mac->ETH_MACMIIAR;
	/* Clear CSR Clock Range CR[2:0] bits */
	tmpreg &= ~ETH_MACMIIAR_CR;

	/* Get hclk frequency value */
	RCC_GetClocksFreq (&clocks);

	/* Set CR bits depending on hclk value */
	if ((clocks.HCLK_Frequency >= 20000000) && (clocks.HCLK_Frequency < 35000000))
	{
		/* CSR Clock Range between 20-35 MHz */
		tmpreg |= ETH_MACMIIAR_CR_Div16;
	}
	else if ((clocks.HCLK_Frequency >= 35000000) && (clocks.HCLK_Frequency < 60000000))
	{
		/* CSR Clock Range between 35-60 MHz */
		tmpreg |= ETH_MACMIIAR_CR_Div26;
	}
	else if ((clocks.HCLK_Frequency >= 60000000) && (clocks.HCLK_Frequency < 100000000))
	{
		/* CSR Clock Range between 60-100 MHz */
		tmpreg |= ETH_MACMIIAR_CR_Div42;
	}
	else /* ((hclk >= 100000000)&&(hclk < 120000000)) */
	{
		/* CSR Clock Range between 100-120 MHz */
		tmpreg |= ETH_MACMIIAR_CR_Div62;
	}

	/* Write to ETHERNET MAC MIIAR: Configure the ETHERNET CSR Clock Range */
	mac->ETH_MACMIIAR = tmpreg;

	/*-------------------- PHY initialization and configuration ----------------*/
	res = HAL_ETH_Init_PHY(mac, cfg);

	/* Config MAC and DMA */
	ETH_MACDMAConfig(mac, cfg);

	return res;
}
Example #21
0
File: i2c.c Project: 9zigen/stm32
// Initialize specified I2C peripheral
// input:
//   I2Cx - I2C port
//   Clock - I2C speed (Hz)
// return:
//   I2C_ERROR if there was a timeout during I2C initialization, I2C_SUCCESS otherwise
// note: minimum APB1 frequency for I2C work is 2MHz
I2C_Status I2Cx_Init(I2C_TypeDef* I2Cx, uint32_t Clock) {
	GPIO_InitTypeDef PORT;
	RCC_ClocksTypeDef RCC_Clocks; // To compute I2C speed depending on current MCU clocking
	uint16_t reg, spd, freq;

	PORT.GPIO_Speed = GPIO_Speed_40MHz;
	PORT.GPIO_OType = GPIO_OType_OD;
	PORT.GPIO_Mode  = GPIO_Mode_AF;
	PORT.GPIO_PuPd  = GPIO_PuPd_UP;

	if (I2Cx == I2C1) {
		// Enable the I2C1 peripheral clock
		RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
		// Reset the I2C1 peripheral to initial state
		RCC->APB1RSTR |=  RCC_APB1RSTR_I2C1RST;
		RCC->APB1RSTR &= ~RCC_APB1RSTR_I2C1RST;
		// Enable the I2Cx GPIO peripheral clock
		RCC->AHBENR |= I2C1_GPIO_AHB;
		// Initialize the I2C1 GPIO peripheral
		PORT.GPIO_Pin = I2C1_GPIO_SCL | I2C1_GPIO_SDA;
		GPIO_Init(I2C1_GPIO_PORT,&PORT);
		GPIO_PinAFConfig(I2C1_GPIO_PORT,I2C1_GPIO_SCL_SRC,GPIO_AF_I2C1);
		GPIO_PinAFConfig(I2C1_GPIO_PORT,I2C1_GPIO_SDA_SRC,GPIO_AF_I2C1);
	} else {
		// Enable the I2C2 peripheral clock
		RCC->APB1ENR |= RCC_APB1ENR_I2C2EN;
		// Reset the I2C2 peripheral to initial state
		RCC->APB1RSTR |=  RCC_APB1RSTR_I2C2RST;
		RCC->APB1RSTR &= ~RCC_APB1RSTR_I2C2RST;
		// Enable the I2Cx GPIO peripheral clock
		RCC->AHBENR |= I2C2_GPIO_AHB;
		// Initialize the I2C2 GPIO peripheral
		PORT.GPIO_Pin = I2C2_GPIO_SCL | I2C2_GPIO_SDA;
		GPIO_Init(I2C2_GPIO_PORT,&PORT);
		GPIO_PinAFConfig(I2C2_GPIO_PORT,I2C2_GPIO_SCL_SRC,GPIO_AF_I2C2);
		GPIO_PinAFConfig(I2C2_GPIO_PORT,I2C2_GPIO_SDA_SRC,GPIO_AF_I2C2);
	}

	// Configure the I2C peripheral

	// Get CR2 register value and clear FREQ[5:0] bits
	reg = I2Cx->CR2 & ~I2C_CR2_FREQ;
	// Get current RCC clocks
	RCC_GetClocksFreq(&RCC_Clocks);
	// Set FREQ bits depending on PCLK1 value
	freq = (uint16_t)(RCC_Clocks.PCLK1_Frequency / 1000000);
	I2Cx->CR2 |= freq;

	// TRISE can be configured only when I2C peripheral disabled
	I2Cx->CR1 &= ~I2C_CR1_PE;

	// Configure I2C speed
	if (Clock <= 100000) {
		// I2C standard speed (Clock <= 100kHz)
		spd = (uint16_t)(RCC_Clocks.PCLK1_Frequency / (Clock << 1)); // Duty cycle 50%/50%
		// I2C CCR value: Standard mode
		reg = (spd < 0x04) ? 0x04 : spd;
		// Maximum rise time for standard mode
		I2Cx->TRISE = freq + 1;
	} else {
		// I2C fast speed (100kHz > Clock <= 400kHz)
		// PCLK1 frequency must be a multiple of 10MHz
		spd = (uint16_t)(RCC_Clocks.PCLK1_Frequency / (Clock * 3)); // Duty cycle 66%/33% (Tlow/Thigh = 2)
//		spd = (uint16_t)(RCC_Clocks.PCLK1_Frequency / (Clock * 25)); // Duty cycle 64%/33% (Tlow/Thigh = 16/9)
//		reg |= I2C_CCR_DUTY; // I2C fast mode mode duty cycle = 16/9
		// I2C CCR value: Fast mode
		reg = (spd == 0) ? 1 : spd;
		reg |= I2C_CCR_FS;
		// Maximum rise time for fast mode
	    I2Cx->TRISE = (uint16_t)(((freq * 300) / 1000) + 1);
	}
	// Write to I2C CCR register
	I2Cx->CCR = reg;

	// Enable acknowledge, I2C mode, peripheral enabled
	I2Cx->CR1 = I2C_CR1_ACK | I2C_CR1_PE;

	// Set I2C own address: 0x00, 7-bit
	I2Cx->OAR1 = (1 << 14); // Bit 14 should be kept as 1

	// Wait until I2C bus is free
	if (I2Cx_WaitFlagReset(I2Cx,I2C_F_BUSY) == I2C_ERROR) return I2C_ERROR;

	return I2C_SUCCESS;
}
Example #22
0
void initTick(void){
    /* SysTick end of count event each 1ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000);
}
Example #23
0
int main(void)
{
	GPIO_InitTypeDef        GPIO_InitStructure;								//structure for GPIO setup
	//TouchInitStr touch_init;
	
	I2C_InitTypeDef					I2C_InitStructure; 		 	
	

  /* SysTick end of count event each 1ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000);	
	
 
	touch_coords.processed=1;
	
	

  /* Initialize LEDs, Key Button, LCD and COM port(USART) available on
     STM32303C-EVAL board *****************************************************/
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
	
	STM_EVAL_LEDInit(LED9);
	

	//init now the TW88 chip on I2C 1
	
	//I2C init ...on PB6 And PB7
	
	/* Configure the I2C clock source. The clock is derived from the SYSCLK */
  RCC_I2CCLKConfig(RCC_I2C1CLK_HSI);													

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB , ENABLE);
	

	
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_4);  // SCL
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_4);	// SDA


  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;																
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;							
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;	
	GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;


  GPIO_InitStructure.GPIO_Pin = (GPIO_Pin_6);	
  GPIO_Init(GPIOB, &GPIO_InitStructure);		

	GPIO_InitStructure.GPIO_Pin = (GPIO_Pin_7);
	GPIO_Init(GPIOB, &GPIO_InitStructure);	
	
	//init our serial port on UART2
	SerialPort_Init(115200,1);
	
	
	printf("\n\r ***** COEN490/ELEC490 Capstone Project Team 14 Welcome! ***** \n\r");
	
	
	I2C_DeInit(I2C1);
	I2C_StructInit(&I2C_InitStructure);
	I2C_InitStructure.I2C_Mode=I2C_Mode_I2C;
	I2C_InitStructure.I2C_AnalogFilter = I2C_AnalogFilter_Enable;
	I2C_InitStructure.I2C_DigitalFilter = 0x00;
	I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
	I2C_InitStructure.I2C_OwnAddress1 = 0x00;
	I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
	//I2C_InitStructure.I2C_Timing = 0x50330309; //0xB0420F13;    ///0x00902025; // 0xc062121f
	I2C_InitStructure.I2C_Timing = 0x00310309; 
	I2C_Init(I2C1,&I2C_InitStructure);
	I2C_Cmd(I2C1,ENABLE);



	
	Delay(1);	
	
  //init TW88
	TW88_Init();
	
	
	//add the osd
	TW88_AddOSD_Win(0,0,0x3F,1);
	
	
	//touch_init.onTouchEvent = onTouchScreenEvent;
	AR1100Init();
	
	
	
  /* Infinite loop */
  while (1)
  {
	
		if (rx_counter>0) {
			printf("Recv: %d",rx_buffer[0]);
			memset(rx_buffer, 0, RX_BUFFER_LENGTH);
			rx_counter=0;
		}
		
		
		if (touch_coords.processed==0) {
			 touch_coords.processed=1;
			 onTouchScreenEvent(touch_coords);
		}
		
		
    /* Toggle LD1 */
    STM_EVAL_LEDToggle(LED1);

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

    /* Toggle LD2 */
    STM_EVAL_LEDToggle(LED2);

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

    /* Toggle LD3 */
    STM_EVAL_LEDToggle(LED3);

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

    /* Toggle LD4 */
    //STM_EVAL_LEDToggle(LED4);

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

		
		
  }
}
/**
  * @brief  Initializes the SPIx peripheral according to the specified
  *         parameters in the I2S_InitStruct.
  * @param  SPIx: where x can be 1 to select the SPI peripheral (configured in I2S mode).
  * @param  I2S_InitStruct: pointer to an I2S_InitTypeDef structure that
  *         contains the configuration information for the specified SPI peripheral
  *         configured in I2S mode.
  * @note   This function calculates the optimal prescaler needed to obtain the most
  *         accurate audio frequency (depending on the I2S clock source, the PLL values
  *         and the product configuration). But in case the prescaler value is greater
  *         than 511, the default value (0x02) will be configured instead.
  * @retval None
  */
void I2S_Init(SPI_TypeDef* SPIx, I2S_InitTypeDef* I2S_InitStruct)
{
  uint16_t tmpreg = 0, i2sdiv = 2, i2sodd = 0, packetlength = 1;
  uint32_t tmp = 0;
  RCC_ClocksTypeDef RCC_Clocks;
  uint32_t sourceclock = 0;

  /* Check the I2S parameters */
  assert_param(IS_SPI_1_PERIPH(SPIx));
  assert_param(IS_I2S_MODE(I2S_InitStruct->I2S_Mode));
  assert_param(IS_I2S_STANDARD(I2S_InitStruct->I2S_Standard));
  assert_param(IS_I2S_DATA_FORMAT(I2S_InitStruct->I2S_DataFormat));
  assert_param(IS_I2S_MCLK_OUTPUT(I2S_InitStruct->I2S_MCLKOutput));
  assert_param(IS_I2S_AUDIO_FREQ(I2S_InitStruct->I2S_AudioFreq));
  assert_param(IS_I2S_CPOL(I2S_InitStruct->I2S_CPOL));

/*----------------------- SPIx I2SCFGR & I2SPR Configuration -----------------*/
  /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */
  SPIx->I2SCFGR &= I2SCFGR_CLEAR_Mask;
  SPIx->I2SPR = 0x0002;

  /* Get the I2SCFGR register value */
  tmpreg = SPIx->I2SCFGR;

  /* If the default value has to be written, reinitialize i2sdiv and i2sodd*/
  if(I2S_InitStruct->I2S_AudioFreq == I2S_AudioFreq_Default)
  {
    i2sodd = (uint16_t)0;
    i2sdiv = (uint16_t)2;
  }
  /* If the requested audio frequency is not the default, compute the prescaler */
  else
  {
    /* Check the frame length (For the Prescaler computing) */
    if(I2S_InitStruct->I2S_DataFormat == I2S_DataFormat_16b)
    {
      /* Packet length is 16 bits */
      packetlength = 1;
    }
    else
    {
      /* Packet length is 32 bits */
      packetlength = 2;
    }

    /* I2S Clock source is System clock: Get System Clock frequency */
    RCC_GetClocksFreq(&RCC_Clocks);

    /* Get the source clock value: based on System Clock value */
    sourceclock = RCC_Clocks.SYSCLK_Frequency;

    /* Compute the Real divider depending on the MCLK output state with a floating point */
    if(I2S_InitStruct->I2S_MCLKOutput == I2S_MCLKOutput_Enable)
    {
      /* MCLK output is enabled */
      tmp = (uint16_t)(((((sourceclock / 256) * 10) / I2S_InitStruct->I2S_AudioFreq)) + 5);
    }
    else
    {
      /* MCLK output is disabled */
      tmp = (uint16_t)(((((sourceclock / (32 * packetlength)) *10 ) / I2S_InitStruct->I2S_AudioFreq)) + 5);
    }

    /* Remove the floating point */
    tmp = tmp / 10;

    /* Check the parity of the divider */
    i2sodd = (uint16_t)(tmp & (uint16_t)0x0001);

    /* Compute the i2sdiv prescaler */
    i2sdiv = (uint16_t)((tmp - i2sodd) / 2);

    /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */
    i2sodd = (uint16_t) (i2sodd << 8);
  }

  /* Test if the divider is 1 or 0 or greater than 0xFF */
  if ((i2sdiv < 2) || (i2sdiv > 0xFF))
  {
    /* Set the default values */
    i2sdiv = 2;
    i2sodd = 0;
  }

  /* Write to SPIx I2SPR register the computed value */
  SPIx->I2SPR = (uint16_t)(i2sdiv | (uint16_t)(i2sodd | (uint16_t)I2S_InitStruct->I2S_MCLKOutput));

  /* Configure the I2S with the SPI_InitStruct values */
  tmpreg |= (uint16_t)(SPI_I2SCFGR_I2SMOD | (uint16_t)(I2S_InitStruct->I2S_Mode | \
                  (uint16_t)(I2S_InitStruct->I2S_Standard | (uint16_t)(I2S_InitStruct->I2S_DataFormat | \
                  (uint16_t)I2S_InitStruct->I2S_CPOL))));

  /* Write to SPIx I2SCFGR */
  SPIx->I2SCFGR = tmpreg;
}
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  RCC_ClocksTypeDef RCC_Clocks;
  
  /* Initialize LEDs and User_Button on STM32F4-Discovery --------------------*/
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI); 
  
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);
  
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
  
  if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
  {
    /* Turn on LEDs available on STM32F4-Discovery ---------------------------*/
    STM_EVAL_LEDOn(LED4);
    STM_EVAL_LEDOn(LED3);
    STM_EVAL_LEDOn(LED5);
    STM_EVAL_LEDOn(LED6); 

    if ((*(__IO uint32_t*) TESTRESULT_ADDRESS) == ALLTEST_PASS)
    {
      TimingDelay = 300;
      /* Waiting User Button is pressed or Test Program condition verified */
      while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)&&(TimingDelay != 0x00))
      {}
    }
    else
    {
      /* Waiting User Button is Released  or TimeOut*/
      TimingDelay = 300;
      while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)&&(TimingDelay != 0x00))
      {}
      if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_RESET)
      {
        TimingDelay = 0x00;
      }
    }
    if (TimingDelay == 0x00)
    {
      /* Turn off LEDs available on STM32F4-Discovery ------------------------*/
      STM_EVAL_LEDOff(LED4);
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOff(LED5);
      STM_EVAL_LEDOff(LED6); 
      
      /* Waiting User Button is released */
      while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
      {}
      
      /* Unlocks the FLASH control register access */
      FLASH_Unlock();
      
      /* Move discovery kit to detect negative and positive acceleration values 
      on X, Y and Z axis */
      Accelerometer_MEMS_Test();
      
      /* USB Hardware connection */
      USB_Test();
      
      /* Audio Hardware connection */
      Audio_Test();
      
      /* Microphone MEMS Hardware connection */
      Microphone_MEMS_Test();
      
      /* Write PASS code at last word in the flash memory */
      FLASH_ProgramWord(TESTRESULT_ADDRESS, ALLTEST_PASS);
      
      while(1)
      {
        /* Toggle Green LED: signaling the End of the Test program */
        STM_EVAL_LEDToggle(LED4);
        Delay(10);
      }
    }
    else
    {
      Demo_Exec();
    }
  }
  else
  {    
    Demo_Exec();
  }
  return 0;
}
Example #26
0
int main(void) {
	// Initialize the MCU clock system
	SystemInit();
	SetSysClock();
	SystemCoreClockUpdate();


	// Initialize debug output port (USART2)
	//   clock source: SYSCLK
	//   mode: transmit only
	USART2_HandleInit();
	RCC_SetClockUSART(RCC_USART2_CLK_SRC,RCC_PERIPH_CLK_SYSCLK);
	USART_Init(&hUSART2,USART_MODE_TX);

	// Configure USART:
	//   oversampling by 16
	//   115200, 8-N-1
	//   no hardware flow control
	USART_SetOversampling(&hUSART2,USART_OVERS16);
	USART_SetBaudRate(&hUSART2,115200);
	USART_SetDataMode(&hUSART2,USART_DATAWIDTH_8B,USART_PARITY_NONE,USART_STOPBITS_1);
	USART_SetHWFlow(&hUSART2,USART_HWCTL_NONE);
	USART_Enable(&hUSART2);
	USART_CheckIdleState(&hUSART2,0xC5C10); // Timeout of about 100ms at 80MHz CPU


	// Say "hello world"
	RCC_ClocksTypeDef Clocks;
	RCC_GetClocksFreq(&Clocks);
	printf("\r\n---STM32L476RG---\r\n");
	printf("CRC peripheral (%s @ %s)\r\n",__DATE__,__TIME__);
	printf("CPU: %.3uMHz\r\n",SystemCoreClock / 1000);
	printf("SYSCLK=%.3uMHz, HCLK=%.3uMHz\r\n",Clocks.SYSCLK_Frequency / 1000,Clocks.HCLK_Frequency / 1000);
	printf("APB1=%.3uMHz, APB2=%.3uMHz\r\n",Clocks.PCLK1_Frequency / 1000,Clocks.PCLK2_Frequency / 1000);
	printf("System clock: %s\r\n",_sysclk_src_str[RCC_GetSysClockSource()]);


	// Enable the CRC peripheral
	CRC_Enable();

	// Disable reverse for input and output data
	CRC_SetInRevMode(CRC_IN_NORMAL);
	CRC_SetOutRevMode(CRC_OUT_NORMAL);


	// First column in output is the calculated CRC, second - reference value

	// 8-bit CRC tests
	CRC_SetPolynomialSize(CRC_PSIZE_8B);
	printf("CRC-8 tests:\r\n");

	// CCITT CRC-8 (Poly=0x07, Init=0x00, RefIn=false, RefOut=false)
	CRC_SetPolynomial(0x07);
	CRC_SetInitValue(0x00);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("CCITT    : 0x%02X . 0x%02X\r\n", CRC_GetData8(), 0x34);

	// CDMA2000 CRC-8 (Poly=0x9B, Init=0xFF, RefIn=false, RefOut=false)
	CRC_SetPolynomial(0x9B);
	CRC_SetInitValue(0xFF);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("CDMA2000 : 0x%02X . 0x%02X\r\n", CRC_GetData8(), 0xCE);

	// WCDMA CRC-8 (Poly=0x9B, Init=0x00, RefIn=true, RefOut=true)
	CRC_SetInitValue(0x00);
	CRC_SetInRevMode(CRC_IN_REV_BYTE);
	CRC_SetOutRevMode(CRC_OUT_REVERSED);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("WCDMA    : 0x%02X . 0x%02X\r\n", CRC_GetData8(), 0xEA);

	// I-CODE CRC-8 (Poly=0x1D, Init=0xFD, RefIn=false, RefOut=false)
	CRC_SetPolynomial(0x1D);
	CRC_SetInitValue(0xFD);
	CRC_SetInRevMode(CRC_IN_NORMAL);
	CRC_SetOutRevMode(CRC_OUT_NORMAL);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("I-CODE   : 0x%02X . 0x%02X\r\n", CRC_GetData8(), 0x87);

	// ROHC CRC-8 (Poly=0x07, Init=0xFF, RefIn=true, RefOut=true)
	CRC_SetPolynomial(0x07);
	CRC_SetInitValue(0xFF);
	CRC_SetInRevMode(CRC_IN_REV_BYTE);
	CRC_SetOutRevMode(CRC_OUT_REVERSED);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("ROHC     : 0x%02X . 0x%02X\r\n", CRC_GetData8(), 0x1A);


	// 16-bit CRC tests
	CRC_SetPolynomialSize(CRC_PSIZE_16B);
	printf("CRC-16 tests:\r\n");

	// MODBUS (Poly=0x8005, Init=0xFFFF, RefIn=true, RefOut=true)
	CRC_SetPolynomial(0x8005);
	CRC_SetInitValue(0xFFFF);
	CRC_SetInRevMode(CRC_IN_REV_BYTE);
	CRC_SetOutRevMode(CRC_OUT_REVERSED);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("MODBUS   : 0x%04X . 0x%04X\r\n", CRC_GetData16(), 0x3BD1);

	// CDMA2000 (Poly=0xC867, Init=0xFFFF, RefIn=false, RefOut=false)
	CRC_SetPolynomial(0xC867);
	CRC_SetInRevMode(CRC_IN_NORMAL);
	CRC_SetOutRevMode(CRC_OUT_NORMAL);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("CDMA2000 : 0x%04X . 0x%04X\r\n", CRC_GetData16(), 0x52F7);

	// XMODEM (Poly=0x1021, Init=0x0000, RefIn=false, RefOut=false)
	CRC_SetPolynomial(0x1021);
	CRC_SetInitValue(0x0000);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("XMODEM   : 0x%04X . 0x%04X\r\n", CRC_GetData16(), 0x047B);

	// USB (Poly=0x8005, Init=0xFFFF, RefIn=true, RefOut=true, XorOut=0xFFFF)
	CRC_SetPolynomial(0x8005);
	CRC_SetInitValue(0xFFFF);
	CRC_SetInRevMode(CRC_IN_REV_BYTE);
	CRC_SetOutRevMode(CRC_OUT_REVERSED);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("USB      : 0x%04X . 0x%04X\r\n", CRC_GetData16() ^ 0xFFFF, 0xC42E);


	// 32-bit CRC tests
	CRC_SetPolynomialSize(CRC_PSIZE_32B);
	printf("CRC-32 tests:\r\n");

	// MPEG-2 (Poly=0x04C11DB7, Init=0xFFFFFFFF, RefIn=true, RefOut=true)
	CRC_SetPolynomial(0x04C11DB7);
	CRC_SetInitValue(0xFFFFFFFF);
	CRC_SetInRevMode(CRC_IN_NORMAL);
	CRC_SetOutRevMode(CRC_OUT_NORMAL);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("MPEG-2   : 0x%08X . 0x%08X\r\n", CRC_GetData32(), 0xF5C62CB4);

	// POSIX (Poly=0x04C11DB7, Init=0x00000000, RefIn=false, RefOut=false, XorOut=0xFFFFFFFF)
	CRC_SetPolynomial(0x04C11DB7);
	CRC_SetInitValue(0x00000000);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("POSIX    : 0x%08X . 0x%08X\r\n", CRC_GetData32() ^ 0xFFFFFFFF, 0xD338A790);

	// CRC-32D (Poly=0xA833982B, Init=0xFFFFFFFF, RefIn=true, RefOut=true, XorOut=0xFFFFFFFF)
	CRC_SetPolynomial(0xA833982B);
	CRC_SetInitValue(0xFFFFFFFF);
	CRC_SetInRevMode(CRC_IN_REV_BYTE);
	CRC_SetOutRevMode(CRC_OUT_REVERSED);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("CRC-32D  : 0x%08X . 0x%08X\r\n", CRC_GetData32() ^ 0xFFFFFFFF, 0xD2178F40);

	// XFER (Poly=0x000000AF, Init=0x00000000, RefIn=false, RefOut=false)
	CRC_SetPolynomial(0x000000AF);
	CRC_SetInitValue(0x00000000);
	CRC_SetInRevMode(CRC_IN_NORMAL);
	CRC_SetOutRevMode(CRC_OUT_NORMAL);
	CRC_Reset();
	CRC_CalcBuffer((uint32_t *)data_buf, buf_size);
	printf("XFER     : 0x%08X . 0x%08X\r\n", CRC_GetData32(), 0x5D4143CF);


	// The main loop
	while (1) {
	}
}
Example #27
0
int main()
{
  RCC_ClocksTypeDef RCC_Clocks;
  GPIO_InitTypeDef GPIO_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
  
	int rf_len = 0;
  int rs485_len = 0;
#if DEBUG
//  int usart_len = 0;
//	char buff_usart[BUFFER_SIZE];
#endif
	char buff_rf[BUFFER_SIZE];
	char buff_rs485[BUFFER_SIZE];
  
  unsigned int sensors_time_poll = 0;
//  int temp_time_poll = 0;
//  int sms_test_time = 0;
  
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
  GPIO_Init(GPIOB, &GPIO_InitStructure);
  GPIO_WriteBit(GPIOB, GPIO_Pin_9, Bit_SET); // off
  
	Delay_Init();
  
  Enrf24_init(CE_PIN, CSN_PIN, IRQ_PIN);
	Enrf24_begin(1000000, 0);  // Defaults 1Mbps, channel 0, max TX power
  
  Enrf24_setTXaddress((void*)enrf24_addr);
  Enrf24_setRXaddress((void*)enrf24_addr);
  
  Enrf24_enableRX();  // Start listening
	
#if DEBUG
	USART1_Init(115200);
#endif
	DS1307_Init();
  Sensors_Init();
  RS485_Init(115200);
	sim_hal_init(115200);
  OutputInit();
  
  if (ThesisInit() == THESIS_FLASH_ERROR)
	{
#if DEBUG
		USART1_SendStr("\nFlash write error.\n");
#endif
		TurnBuzzerOn();
		Delay(1000);
	}
  
#if DEBUG
	RCC_GetClocksFreq(&RCC_Clocks);
  USART1_SendStr("System Clock: ");
  USART1_SendNum(RCC_Clocks.SYSCLK_Frequency);
  USART1_SendStr("\r\n");
  
  
  USART1_SendStr("Device ID: ");
  USART1_SendByte(__flash_data.id, HEX);
  USART1_SendStr("\r\n");
  USART1_SendStr("Device Unique Number: ");
  USART1_SendByte(__flash_data.unique_number[0], HEX);
  USART1_SendByte(__flash_data.unique_number[1], HEX);
  USART1_SendByte(__flash_data.unique_number[2], HEX);
  USART1_SendByte(__flash_data.unique_number[3], HEX);
  USART1_SendStr("\r\n");
#endif
  
  
	OneWire_Init();
	for EVER
	{
    if (millis() - sensors_time_poll > 100)
    {
      led_toggle();
      Sensors_Poll();
      sensors_time_poll = millis();
      //      buzzer_toggle();
      //      output_toggle();
      if (millis() > 10000)
      {
        if (sensors.Gas >= GAS_LIMIT)
        {
#if DEBUG
          USART1_SendStr("Gas detected.\r\n");
          USART1_SendStr("Current Gas: ");
          USART1_SendFloat(sensors.Gas);
          USART1_SendStr("Limited Gas: ");
          USART1_SendFloat(GAS_LIMIT);
          USART1_SendStr("\r\n");
#endif
          TurnBuzzerOn();
          TurnSpeakerOn();
          TurnRelayOn();
        }
        else if (sensors.Lighting >= LIGHT_LIMIT)
        {
#if DEBUG
          USART1_SendStr("Light detected.\r\n");
          USART1_SendStr("Current Light: ");
          USART1_SendFloat(sensors.Lighting);
          USART1_SendStr("Limited Light: ");
          USART1_SendFloat(LIGHT_LIMIT);
          USART1_SendStr("\r\n");
#endif
          TurnBuzzerOn();
          TurnSpeakerOn();
          TurnRelayOn();
        }
        else if (sensors.TempC >= TEMPC_LIMIT)
        {
#if DEBUG
          USART1_SendStr("Tempc detected.\r\n");
          USART1_SendStr("Current Tempc: ");
          USART1_SendFloat(sensors.TempC);
          USART1_SendStr("Limited Tempc: ");
          USART1_SendFloat(TEMPC_LIMIT);
          USART1_SendStr("\r\n");
#endif
          TurnBuzzerOn();
          TurnSpeakerOn();
          TurnRelayOn();
        }
        else
        {
          TurnBuzzerOff();
          TurnSpeakerOff();
          TurnRelayOff();
        }
      }
      
      //      Sim900_Process();
    }
    
    //    if (millis() - sms_test_time > 10000)
    //    {
    //      Sim900_SendSMS("Hi kieu", "01677880531");
    //      sms_test_time = millis();
    //    }
    
    //		usart_len = USART1_Available();
    //		
    //		// usart: for test
    //		if (usart_len > 4)
    //		{
    //			int i;
    //			USART1_SendStr("\nUSART1 received packet: \n");
    //			USART1_GetData(buff_usart, usart_len);
    //			for (i = 0; i < usart_len; i++)
    //				USART1_SendByte(buff_usart[i], HEX);
    //			USART1_SendChar('\n');
    //			if (ThesisProcess(buff_usart, usart_len) == THESIS_OK)
    //			{
    //				memset(buff_usart, 0, usart_len);
    //				USART1_Flush();
    //				if (thesis_need_to_send)
    //				{
    //					int i;
    //					USART1_SendStr("\nNeed to send packet: ");
    //					for (i = 0; i < thesis_msg_len; i++)
    //					{
    //						USART1_SendByte(thesis_sent_msg[i], HEX);
    //					}
    //					USART1_SendStr("\nNeed to send packet length: ");
    //					USART1_SendNum(thesis_msg_len);
    //					USART1_SendStr("\n");
    //					thesis_msg_len = 0;
    //					thesis_need_to_send = 0;
    //				}
    //				USART1_SendStr("\nPacket processed.\n"); 
    //			}
    //			else if (thesis_errn == THESIS_FLASH_ERROR)
    //			{
    //				USART1_SendStr("\n");
    //				USART1_SendStr(thesis_err_msg);
    //				USART1_SendStr("\n");
    //				led_toggle();
    //				for(;;);
    //			}
    //			else if (thesis_errn != THESIS_PACKET_NOT_ENOUGH_LENGTH)
    //			{
    //				memset(buff_usart, 0, usart_len);
    //				USART1_Flush();
    //				USART1_SendStr("Packet processing fail.\n");
    //			}
    //			
    //			USART1_SendStr("\n");
    //			USART1_SendStr(thesis_err_msg);
    //			USART1_SendStr("\n");
    //		}
		
    // rf
		if (Enrf24_available(1))
		{
			int i;
			rf_len = Enrf24_read(buff_rf + rf_len, BUFFER_SIZE - 1 - rf_len);
#if DEBUG
			USART1_SendStr("\nRF received packet.\n");
			for (i = 0; i < rf_len; i++)
				USART1_SendByte(buff_rf[i], HEX);
			USART1_SendChar('\n');
#endif
			
			if (ThesisProcess(buff_rf, rf_len) == THESIS_OK)
			{
				memset(buff_rf, 0, rf_len);
        rf_len = 0;
				if (thesis_need_to_send)
				{
					int i;
#if DEBUG
					USART1_SendStr("\nNeed to send packet: ");
					for (i = 0; i < thesis_msg_len; i++)
					{
            //						Enrf24_write(thesis_sent_msg[i]);
						USART1_SendByte(thesis_sent_msg[i], HEX);
					}
#endif
          Enrf24_write_buff(thesis_sent_msg, thesis_msg_len);
          Enrf24_flush();
#if DEBUG
					USART1_SendStr("\nNeed to send packet length: ");
					USART1_SendNum(thesis_msg_len);
					USART1_SendStr("\n");
#endif
					thesis_msg_len = 0;
					thesis_need_to_send = 0;
				}
#if DEBUG
				USART1_SendStr("\nPacket processed.\n");
#endif
			}
			else if (thesis_errn == THESIS_FLASH_ERROR)
			{
#if DEBUG
				USART1_SendStr("\n");
				USART1_SendStr(thesis_err_msg);
				USART1_SendStr("\n");
#endif
				led_toggle();
				for(;;);
			}
			else if (thesis_errn != THESIS_PACKET_NOT_ENOUGH_LENGTH)
			{
				memset(buff_rf, 0, rf_len);
        //				RF_Flush();
        rf_len = 0;
#if DEBUG
				USART1_SendStr("Packet processing fail.\n");
#endif
			}
			
#if DEBUG
			USART1_SendStr("\n");
			USART1_SendStr(thesis_err_msg);
			USART1_SendStr("\n");
#endif
		}
    
    // rs485
		rs485_len = RS485_Available();
		if (rs485_len > 4)
		{
			int i;
			RS485_GetData(buff_rs485, rs485_len);
#if DEBUG
			USART1_SendStr("\nUSART1 received packet: \n");
			for (i = 0; i < rs485_len; i++)
				USART1_SendByte(buff_rs485[i], HEX);
			USART1_SendChar('\n');
#endif
			if (ThesisProcess(buff_rs485, rs485_len) == THESIS_OK)
			{
				memset(buff_rs485, 0, rs485_len);
				RS485_Flush();
				if (thesis_need_to_send)
				{
					int i;
#if DEBUG
					USART1_SendStr("\nNeed to send packet: ");
#endif
          RS485_DIR_Output();
					for (i = 0; i < thesis_msg_len; i++)
					{
						RS485_SendChar(thesis_sent_msg[i]);
#if DEBUG
						USART1_SendByte(thesis_sent_msg[i], HEX);
#endif
					}
          RS485_DIR_Input();
#if DEBUG
					USART1_SendStr("\nNeed to send packet length: ");
					USART1_SendNum(thesis_msg_len);
					USART1_SendStr("\n");
#endif
					thesis_msg_len = 0;
					thesis_need_to_send = 0;
				}
#if DEBUG
				USART1_SendStr("\nPacket processed.\n"); 
#endif
			}
			else if (thesis_errn == THESIS_FLASH_ERROR)
			{
#if DEBUG
				USART1_SendStr("\n");
				USART1_SendStr(thesis_err_msg);
				USART1_SendStr("\n");
#endif
				led_toggle();
				for(;;);
			}
			else if (thesis_errn != THESIS_PACKET_NOT_ENOUGH_LENGTH)
			{
				memset(buff_rs485, 0, rs485_len);
				RS485_Flush();
#if DEBUG
				USART1_SendStr("Packet processing fail.\n");
#endif
			}
			
#if DEBUG
			USART1_SendStr("\n");
			USART1_SendStr(thesis_err_msg);
			USART1_SendStr("\n");
#endif
		}
    
	}
	
}
Example #28
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
  TIM_OCInitTypeDef  TIM_OCInitStructure;
  
  BufferInit(&TxRingBuf);
  BufferInit(&RxRingBuf);


  /*!< At this stage the microcontroller clock setting is already configured, 
  this is done through SystemInit() function which is called from startup
  file (startup_stm32f401xx.s) before to branch to application main.
  To reconfigure the default setting of SystemInit() function, refer to
  system_stm32f4xx.c file
  */
  
  /* TIM Configuration */
  //TIM_Config();
  
  /* -----------------------------------------------------------------------
  TIM3 Configuration: generate 4 PWM signals with 4 different duty cycles.
  
  In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), 
  since APB1 prescaler is different from 1.   
  TIM3CLK = 2 * PCLK1  
  PCLK1 = HCLK / 4 
  => TIM3CLK = HCLK / 2 = SystemCoreClock /2
  
  To get TIM3 counter clock at 14 MHz, the prescaler is computed as follows:
  Prescaler = (TIM3CLK / TIM3 counter clock) - 1
  Prescaler = ((SystemCoreClock /2) /14 MHz) - 1
  
  To get TIM3 output clock at 21 KHz, the period (ARR)) is computed as follows:
  ARR = (TIM3 counter clock / TIM3 output clock) - 1
  = 665
  
  TIM3 Channel1 duty cycle = (TIM3_CCR1/ TIM3_ARR)* 100 = 50%
  TIM3 Channel2 duty cycle = (TIM3_CCR2/ TIM3_ARR)* 100 = 37.5%
  TIM3 Channel3 duty cycle = (TIM3_CCR3/ TIM3_ARR)* 100 = 25%
  TIM3 Channel4 duty cycle = (TIM3_CCR4/ TIM3_ARR)* 100 = 12.5%
  
  Note: 
  SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
  Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
  function to update SystemCoreClock variable value. Otherwise, any configuration
  based on this variable will be incorrect.    
  ----------------------------------------------------------------------- */  
  //===========================================================
  //UART config
  //===========================================================

  USART_InitTypeDef UartHandle;
  GPIO_InitTypeDef GPIO_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  USART_ClockInitTypeDef USART_ClockInitStruct;
  RCC_ClocksTypeDef RCC_Clocks;
  
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);

  USART_StructInit(&UartHandle);
  USART_ClockStructInit(&USART_ClockInitStruct);

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

  GPIO_PinAFConfig(GPIOD, GPIO_PinSource5, GPIO_AF_USART2);
  GPIO_PinAFConfig(GPIOD, GPIO_PinSource6, GPIO_AF_USART2);



  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(GPIOD, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(GPIOD, &GPIO_InitStructure);

  USART_Init(USART2,&UartHandle);

  USART_ClockInit(USART2,&USART_ClockInitStruct);
  USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);
  USART_ITConfig(USART2, USART_IT_TC,ENABLE);


  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

  NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  USART_Cmd(USART2, ENABLE);
  Delay(40);




  Sevenseg_Setup();
  Delay(40);



  USART_SendData(USART2,0xaaaa);
  //GPIO_SetBits(GPIOB,GPIO_Pin_0 | GPIO_Pin_1);
  GPIO_SetBits(GPIOD,GPIO_Pin_0);
  //======================================================
  //----------------------------------------------------
  //========================================================






//  /* Compute the prescaler value */
//  PrescalerValue = (uint16_t) (SystemCoreClock / 1000000) - 1;
//
//  /* Time base configuration */
//  TIM_TimeBaseStructure.TIM_Period = 5000;
//  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
//  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
//  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
//
//  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
//
//  /* PWM1 Mode configuration: Channel1 */
//  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
//  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
//
//  TIM_OC1Init(TIM3, &TIM_OCInitStructure);
//
//  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
//
//
//  /* PWM1 Mode configuration: Channel2 */
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;
//
//  TIM_OC2Init(TIM3, &TIM_OCInitStructure);
//
//  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
//
//  /* PWM1 Mode configuration: Channel3 */
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;
//
//  TIM_OC3Init(TIM3, &TIM_OCInitStructure);
//
//  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
//
//  /* PWM1 Mode configuration: Channel4 */
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;
//
//  TIM_OC4Init(TIM3, &TIM_OCInitStructure);
//
//  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
//
//  TIM_ARRPreloadConfig(TIM3, ENABLE);
//
//  /* TIM3 enable counter */
//  TIM_Cmd(TIM3, ENABLE);
  int bts = 0;



  Sevenseg_Send(0x33);

  while (1)
  {

	if(RxRingBuf.length > 10) {
		int i;
		int ntosend = RxRingBuf.length;
		for(i = 0; i < ntosend;i++)
		{
			bts = BufferRead(&RxRingBuf);
			//if(bts == -1) break;
			USART2_SendByte(bts);
		}
		/*
		while(TxRingBuf.length > 0)
		{
			if((TxRingBuf.length > 0) && (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == SET)) {
				BufferSend(&TxRingBuf);
			}
		}
		*/
	}
	  /*
	  GPIO_ResetBits(GPIOB,GPIO_Pin_0 | GPIO_Pin_1);
	  GPIO_ResetBits(GPIOA,GPIO_Pin_0);


	  //GPIO_ToggleBits(GPIOB, GPIO_Pin_0);
	  GPIO_SetBits(GPIOB,GPIO_Pin_0 | GPIO_Pin_1);
	  GPIO_SetBits(GPIOA,GPIO_Pin_0);
	  */
	  //USART_SendData(USART2,0x0051);
	  //USART_SendData(USART2,0x003b);
  }
}
Example #29
0
/**
  * @brief  Initializes the I2Cx peripheral according to the specified 
  *   parameters in the I2C_InitStruct.
  * @param  I2Cx: where x can be 1 or 2 to select the I2C peripheral.
  * @param  I2C_InitStruct: pointer to a I2C_InitTypeDef structure that
  *   contains the configuration information for the specified I2C peripheral.
  * @retval None
  */
void I2C_Init(I2C_TypeDef* I2Cx, I2C_InitTypeDef* I2C_InitStruct)
{
  uint16_t tmpreg = 0, freqrange = 0;
  uint16_t result = 0x04;
  uint32_t pclk1 = 8000000;
  RCC_ClocksTypeDef  rcc_clocks;
  /* Check the parameters */
  assert_param(IS_I2C_ALL_PERIPH(I2Cx));
  assert_param(IS_I2C_CLOCK_SPEED(I2C_InitStruct->I2C_ClockSpeed));
  assert_param(IS_I2C_MODE(I2C_InitStruct->I2C_Mode));
  assert_param(IS_I2C_DUTY_CYCLE(I2C_InitStruct->I2C_DutyCycle));
  assert_param(IS_I2C_OWN_ADDRESS1(I2C_InitStruct->I2C_OwnAddress1));
  assert_param(IS_I2C_ACK_STATE(I2C_InitStruct->I2C_Ack));
  assert_param(IS_I2C_ACKNOWLEDGE_ADDRESS(I2C_InitStruct->I2C_AcknowledgedAddress));

/*---------------------------- I2Cx CR2 Configuration ------------------------*/
  /* Get the I2Cx CR2 value */
  tmpreg = I2Cx->CR2;
  /* Clear frequency FREQ[5:0] bits */
  tmpreg &= CR2_FREQ_Reset;
  /* Get pclk1 frequency value */
  RCC_GetClocksFreq(&rcc_clocks);
  pclk1 = rcc_clocks.PCLK1_Frequency;
  /* Set frequency bits depending on pclk1 value */
  freqrange = (uint16_t)(pclk1 / 1000000);
  tmpreg |= freqrange;
  /* Write to I2Cx CR2 */
  I2Cx->CR2 = tmpreg;

/*---------------------------- I2Cx CCR Configuration ------------------------*/
  /* Disable the selected I2C peripheral to configure TRISE */
  I2Cx->CR1 &= CR1_PE_Reset;
  /* Reset tmpreg value */
  /* Clear F/S, DUTY and CCR[11:0] bits */
  tmpreg = 0;

  /* Configure speed in standard mode */
  if (I2C_InitStruct->I2C_ClockSpeed <= 100000)
  {
    /* Standard mode speed calculate */
    result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed << 1));
    /* Test if CCR value is under 0x4*/
    if (result < 0x04)
    {
      /* Set minimum allowed value */
      result = 0x04;  
    }
    /* Set speed value for standard mode */
    tmpreg |= result;	  
    /* Set Maximum Rise Time for standard mode */
    I2Cx->TRISE = freqrange + 1; 
  }
  /* Configure speed in fast mode */
  else /*(I2C_InitStruct->I2C_ClockSpeed <= 400000)*/
  {
    if (I2C_InitStruct->I2C_DutyCycle == I2C_DutyCycle_2)
    {
      /* Fast mode speed calculate: Tlow/Thigh = 2 */
      result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed * 3));
    }
    else /*I2C_InitStruct->I2C_DutyCycle == I2C_DutyCycle_16_9*/
    {
      /* Fast mode speed calculate: Tlow/Thigh = 16/9 */
      result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed * 25));
      /* Set DUTY bit */
      result |= I2C_DutyCycle_16_9;
    }

    /* Test if CCR value is under 0x1*/
    if ((result & CCR_CCR_Set) == 0)
    {
      /* Set minimum allowed value */
      result |= (uint16_t)0x0001;  
    }
    /* Set speed value and set F/S bit for fast mode */
    tmpreg |= (uint16_t)(result | CCR_FS_Set);
    /* Set Maximum Rise Time for fast mode */
    I2Cx->TRISE = (uint16_t)(((freqrange * (uint16_t)300) / (uint16_t)1000) + (uint16_t)1);  
  }

  /* Write to I2Cx CCR */
  I2Cx->CCR = tmpreg;
  /* Enable the selected I2C peripheral */
  I2Cx->CR1 |= CR1_PE_Set;

/*---------------------------- I2Cx CR1 Configuration ------------------------*/
  /* Get the I2Cx CR1 value */
  tmpreg = I2Cx->CR1;
  /* Clear ACK, SMBTYPE and  SMBUS bits */
  tmpreg &= CR1_CLEAR_Mask;
  /* Configure I2Cx: mode and acknowledgement */
  /* Set SMBTYPE and SMBUS bits according to I2C_Mode value */
  /* Set ACK bit according to I2C_Ack value */
  tmpreg |= (uint16_t)((uint32_t)I2C_InitStruct->I2C_Mode | I2C_InitStruct->I2C_Ack);
  /* Write to I2Cx CR1 */
  I2Cx->CR1 = tmpreg;

/*---------------------------- I2Cx OAR1 Configuration -----------------------*/
  /* Set I2Cx Own Address1 and acknowledged address */
  I2Cx->OAR1 = (I2C_InitStruct->I2C_AcknowledgedAddress | I2C_InitStruct->I2C_OwnAddress1);
}
Example #30
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_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);

  LIS302DL_Reset();

  /* SET USER Key */
  /* Configure EXTI Line0 (connected to PA0 pin) in interrupt mode */
  EXTILine0_Config();

  /* Initialize the LCD */
  STM32f4_Discovery_LCD_Init();
  LCD_Clear(LCD_COLOR_WHITE);
  LCD_SetTextColor(LCD_COLOR_BLUE);

  DCMI_Control_IO_Init();

  LCD_DisplayStringLine(LINE(2), "   Camera Init..");
		   
  /* OV9655 Camera Module configuration */
  if (DCMI_OV9655Config() == 0x00)
  {
    LCD_DisplayStringLine(LINE(2), "                ");
    LCD_SetDisplayWindow(0, 0, 320, 240);
    LCD_WriteRAM_Prepare();

    /* Start Image capture and Display on the LCD *****************************/
    /* Enable DMA transfer */
    DMA_Cmd(DMA2_Stream1, ENABLE);

    /* Enable DCMI interface */
    DCMI_Cmd(ENABLE); 

    /* Start Image capture */ 
    DCMI_CaptureCmd(ENABLE);   

    /*init the picture count*/
    init_picture_count();

    KeyPressFlg = 0;
    while (1)
    {
      /* Insert 100ms delay */
      Delay(100);

      if (KeyPressFlg) {
        KeyPressFlg = 0;
        /* press user KEY take a photo */
        if (capture_Flag == ENABLE) {
          DCMI_CaptureCmd(DISABLE);
          capture_Flag = DISABLE;
          Capture_Image_TO_Bmp();
          LCD_SetDisplayWindow(0, 0, 320, 240);
          LCD_WriteRAM_Prepare();
          DCMI_CaptureCmd(ENABLE);
          capture_Flag = ENABLE;
        }			
      }
    }  
  } else {
    LCD_SetTextColor(LCD_COLOR_RED);

    LCD_DisplayStringLine(LINE(2), "Camera Init.. fails");    
    LCD_DisplayStringLine(LINE(4), "Check the Camera HW ");    
    LCD_DisplayStringLine(LINE(5), "  and try again ");

    /* Go to infinite loop */
    while (1);      
  }
}