Esempio n. 1
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* System Clocks Configuration */
  RCC_Configuration();

  /* NVIC Configuration */
  NVIC_Configuration();

  /* GPIO Configuration */
  GPIO_Configuration();

  /* ---------------------------------------------------------------
    TIM2 Configuration: Output Compare Timing Mode:
    TIM2CLK = 36 MHz, Prescaler = 4, TIM2 counter clock = 7.2 MHz
    CC1 update rate = TIM2 counter clock / CCR1_Val = 146.48 Hz
    CC2 update rate = TIM2 counter clock / CCR2_Val = 219.7 Hz
    CC3 update rate = TIM2 counter clock / CCR3_Val = 439.4 Hz
    CC4 update rate = TIM2 counter clock / CCR4_Val =  878.9 Hz
  --------------------------------------------------------------- */

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  /* Prescaler configuration */
  TIM_PrescalerConfig(TIM2, 4, TIM_PSCReloadMode_Immediate);

  /* Output Compare Timing Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM2, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM2, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM2, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* TIM IT enable */
  TIM_ITConfig(TIM2, TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE);

  /* TIM2 enable counter */
  TIM_Cmd(TIM2, ENABLE);

  while (1);
}
Esempio n. 2
0
int main(void)
{
  FIL log_file;
  int i, j, result;
  int file_number = 0;
  u8 configNumber = 1;
  u8 maxConfig;
  u8 *p;
  time_t rawtime;
  u8 debugState = 0; //debug off

#ifdef DEBUG
  debug();
#endif

  RCC_Configuration();
  GPIO_Configuration();
  NVIC_Configuration();
  SystickConfigure();
  Timer3Init();
#ifdef UART1_DEBUG
  (void)USART1_Init(115200);
#endif
  LedConfigureGPIO();
  ButtonConfigureGPIO();
  BuzzerConfigureGPIO();

#ifdef CAN_FEATURE_ENABLED
  GPIO_InitTypeDef GPIO_InitStructure;

  // Configure CAN pin: RX
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  // Configure CAN pin: TX
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
#endif

  MMC_PowerOff();
  timer2=1000;
  while(timer2);
  MMC_PowerOn();

#ifdef UART1_DEBUG
  printf("\n\n%s %s\n", HW_VERSION, SW_VERSION);
#endif

  ConfigureClock();
  timer2=1000;
  while(timer2);

  buttonState = 0;

  CardInserted();
  
  if (FR_OK != f_mount(0, &Fatfs[0]))
  {
    LedSetColor(amber, fast);
    BuzzerSetMode(0x83);
#ifdef UART1_DEBUG
    printf("error mounting fat device\n");
#endif
    while(buttonState != 2);
    NVIC_GenerateSystemReset();
  }

  if (ReadTimeDateFile())
  {
#ifdef UART1_DEBUG
    rawtime = RTC_GetCounter();
    printf("Time set: %s\n", ctime (&rawtime) );
#endif
  }

#ifdef DEBUG_LOG
  if (ReadDebugFile())
  {
    debugState = 1;
  }
#endif

#ifdef CAN_FEATURE_ENABLED
  if (ReadCanFile())
  {
    canDiag = 1;
    CAN_Open();
  }
#endif

  i = ReadSpeedFile();
  if (i > 0)
  {
    KW1281_SPEED = i;
    autobaud = 0;
  }

  if (ReadDelayFile())
  {
    user_defined_timings = 1;
  }
  
  if (!ReadConfig())
  {
    LedSetColor(amber, fast); 
    BuzzerSetMode(0x83);
#ifdef UART1_DEBUG
    printf("error reading config\n");
#endif
    MMC_PowerOff();
    while(buttonState != 2);
    NVIC_GenerateSystemReset(); 
  }
  
  if (config[0][0] > 0)
  {
    maxConfig = 1;
    if (config[1][0] > 0)
    {
      maxConfig = 2;
      if (config[2][0] > 0)
      {
        maxConfig = 3;
      }
    }
  }
  else
  {
    LedSetColor(amber, fast); 
    BuzzerSetMode(0x83);
#ifdef UART1_DEBUG
    printf("error reading config\n");
#endif
    MMC_PowerOff();
    while(buttonState != 2);
    NVIC_GenerateSystemReset(); 
  }

  file_number = GetNextFileNumber();
#ifdef UART1_DEBUG
  printf("file number %d\n", file_number);
#endif
  if (!file_number)
  {
    LedSetColor(amber, fast); 
    BuzzerSetMode(0x83);
#ifdef UART1_DEBUG
    printf("can't get number of next file\n");
#endif
    MMC_PowerOff();
    while(buttonState != 2);
    NVIC_GenerateSystemReset(); 
  }
  
  while(1)
  {
    i = USART2_GetData();
    buttonState = 0;
    LedSetColor(configNumber, continous);
    BuzzerSetMode(configNumber);
    do
    {
      if (2 == buttonState)
      {
        configNumber = (configNumber < maxConfig)?configNumber+1:1;
        LedSetColor(configNumber, continous);
        BuzzerSetMode(configNumber);
        buttonState = 0;
      }
    } while (1 != buttonState);
    
    buttonState = 0;
    LedSetColor(green, fast);
    BuzzerSetMode(0x81);

    i = CreateLogFile(file_number, &log_file);

    i = f_printf(&log_file, "%s, sw_ver: %s\n", HW_VERSION, SW_VERSION);

    rawtime = RTC_GetCounter();
    i = f_printf(&log_file, "Current time: %s\n", ctime (&rawtime));
    
    timeSec = 0;
    time10MSec = 0;
    
    if (canDiag)
    {
      i = f_printf(&log_file, "CAN 500kbit\n\n");
      LedSetColor(configNumber, slow);
      BuzzerSetMode(configNumber);
      result = vwtp(&config[configNumber-1], &log_file, debugState);
      
      switch (result)
      {
        case 0:
          timer2 = 500;
          i = f_printf(&log_file, "\n\nLogging terminated by user\n");
          break;
        
        case 1:
          LedSetColor(red, fast);
          BuzzerSetMode(0x82); //communication error
          timer2 = 2000;
          i = f_printf(&log_file, "\n\nConnection lost\n");
          break;
          
        case 2:
          i = CloseLogFile(&log_file);
          LedSetColor(amber, fast);
          BuzzerSetMode(0x83); //filesystem error
          MMC_PowerOff();
          while(buttonState != 2);
          NVIC_GenerateSystemReset();  
          break;
        
        case 11:
          LedSetColor(red, fast);
          BuzzerSetMode(0x82); //communication error
          timer2 = 2000;
          i = f_printf(&log_file, "\n\nCannot connect with ECU\n", result);
          break;

        default:
          LedSetColor(red, fast);
          BuzzerSetMode(0x82); //communication error
          timer2 = 2000;
          i = f_printf(&log_file, "\n\nCommunication error, error code = %d\n", result);
          break;
      }
    } 
    else //KW1281 diag
    {
      i = kw1281_max_init_attempts;
      do
      {
        result = ISO9141Init(&KW1281_SPEED);

        --i;
        if ((result>0) && (i>0))
        {
          timer2=1000;
          while(timer2);
        }
      } while (result && i);

      if (0 == result) //connected with ECU
      {
        i = f_printf(&log_file, "Connected @ %d baud %s%s\n\n", KW1281_SPEED, autobaud?"(autodetected)":"(set by user)", user_defined_timings?", user defined timings":"");
        LedSetColor(configNumber, slow);
        BuzzerSetMode(configNumber);
    
        buttonState = 0;
        i = kw1281_diag(&config[configNumber-1], &log_file, debugState);
      
        switch (i)
        {
          case 0:
            timer2 = 500;
            i = f_printf(&log_file, "\n\nLogging terminated by user\n");
            break;
        
          case 1:
            LedSetColor(red, fast);
            BuzzerSetMode(0x82); //communication error
            timer2 = 2000;
            i = f_printf(&log_file, "\n\nConnection lost\n");
            break;
          
          case 2:
          default:
            i = CloseLogFile(&log_file);
            LedSetColor(amber, fast);
            BuzzerSetMode(0x83); //filesystem error
            MMC_PowerOff();
            while(buttonState != 2);
            NVIC_GenerateSystemReset();  
        }
      }
      if (0 != result)
      {
        i = f_printf(&log_file, "Cannot connect with ECU: ");
        if (0xff == result)
        {
          i = f_printf(&log_file, "no response\n");
        }
        else if (0x7f == result)
        {
          i = f_printf(&log_file, "sync error - wrong speed (set to %d baud)?!\n", KW1281_SPEED);
        }
        else if (0x10 == result)
        {
          i = f_printf(&log_file, "not a KW1281 protocol\n");
        }
        else
        {
          i = f_printf(&log_file, "error code %d\n", result);
        }
        LedSetColor(red, fast); 
        BuzzerSetMode(0x82);
        timer2 = 2000;
      }
    } // end of KW1281 diag

    i = CloseLogFile(&log_file);
    file_number++;
    while (timer2>0);
  }
}
Esempio n. 3
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
     */     

  /* Initialize LEDs and Key Button mounted on STM3210X-EVAL board */       
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_EXTI);

  /* Enable PWR and BKP clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Configure EXTI Line to generate an interrupt on falling edge */
  EXTI_Configuration();

  /* Configure RTC clock source and prescaler */
  RTC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the SysTick to generate an interrupt each 1 millisecond */
  SysTick_Configuration();

  /* Turn on LED1 */
  STM_EVAL_LEDOn(LED1);
  
  while (1)
  {
    /* Insert 1.5 second delay */
    Delay(1500);

    /* Wait till RTC Second event occurs */
    RTC_ClearFlag(RTC_FLAG_SEC);
    while(RTC_GetFlagStatus(RTC_FLAG_SEC) == RESET);

    /* Alarm in 3 second */
    RTC_SetAlarm(RTC_GetCounter()+ 3);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();

    /* Turn off LED1 */
    STM_EVAL_LEDOff(LED1);

    /* Request to enter STOP mode with regulator in low power mode*/
    PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
    
    /* At this stage the system has resumed from STOP mode -------------------*/
    /* Turn on LED1 */
    STM_EVAL_LEDOn(LED1);

    /* Configures system clock after wake-up from STOP: enable HSE, PLL and select 
       PLL as system clock source (HSE and PLL are disabled in STOP mode) */
    SYSCLKConfig_STOP();
  }
}
Esempio n. 4
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System Clocks Configuration */
  RCC_Configuration();   

  /* NVIC Configuration */
  NVIC_Configuration();

  /* PF.06 and PF.07 config to drive LD1 and LD2 ******************************/
  /* Enable GPIOF clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE);
  
  /* Configure PF.06 and PF.07 as Output push-pull */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOF, &GPIO_InitStructure);
  
  /* Write/read to/from FSMC SRAM memory  *************************************/
  /* Enable the FSMC Clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE);
  
  /* Configure FSMC Bank1 NOR/SRAM3 */
  FSMC_SRAM_Init();

  /* Write data to FSMC SRAM memory */
  /* Fill the buffer to send */
  Fill_Buffer(TxBuffer, BUFFER_SIZE, 0x3212);
  FSMC_SRAM_WriteBuffer(TxBuffer, WRITE_READ_ADDR, BUFFER_SIZE);


  /* Read data from FSMC SRAM memory */
  FSMC_SRAM_ReadBuffer(RxBuffer, WRITE_READ_ADDR, BUFFER_SIZE);  

  /* Read back SRAM memory and check content correctness */   
  for (Index = 0x00; (Index < BUFFER_SIZE) && (WriteReadStatus == 0); Index++)
  {
    if (RxBuffer[Index] != TxBuffer[Index])
    {
      WriteReadStatus = Index + 1;
    }
  }	

  if (WriteReadStatus == 0)
  {	/* OK */
    /* Turn on LD1 */
    GPIO_SetBits(GPIOF, GPIO_Pin_6);
  }
  else
  { /* KO */
    /* Turn off LD2 */
    GPIO_SetBits(GPIOF, GPIO_Pin_7);     
  }

  while (1)
  {
  }
}
Esempio n. 5
0
void rt_hw_board_init(void)
{
    //NAND_IDTypeDef NAND_ID;

    /* Configure the system clocks */
    SystemInit();

    all_device_reset();

    /* NVIC Configuration */
    NVIC_Configuration();

    /* Configure the SysTick */
    SysTick_Config( SystemCoreClock / RT_TICK_PER_SECOND );

    /* Console Initialization*/
    rt_hw_usart_init();
#if STM32_CONSOLE_USART == 1
    rt_console_set_device("uart1");
#elif STM32_CONSOLE_USART == 2
    rt_console_set_device("uart2");
#elif STM32_CONSOLE_USART == 3
    rt_console_set_device("uart3");
#endif

    rt_kprintf("\r\n\r\nSystemInit......\r\n");

    /* SRAM init */
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE);
    FSMC_SRAM_Init();

    /* memtest */
    {
        unsigned char * p_extram = (unsigned char *)STM32_EXT_SRAM_BEGIN;
        unsigned int temp;

        rt_kprintf("\r\nmem testing....");
        for(temp=0; temp<(STM32_EXT_SRAM_END-STM32_EXT_SRAM_BEGIN); temp++)
        {
            *p_extram++ = (unsigned char)temp;
        }

        p_extram = (unsigned char *)STM32_EXT_SRAM_BEGIN;
        for(temp=0; temp<(STM32_EXT_SRAM_END-STM32_EXT_SRAM_BEGIN); temp++)
        {
            if( *p_extram++ != (unsigned char)temp )
            {
                rt_kprintf("\rmemtest fail @ %08X\r\nsystem halt!!!!!",(unsigned int)p_extram);
                while(1);
            }
        }
        rt_kprintf("\rmem test pass!!\r\n");
    }/* memtest */

    /* SPI1 config */
    {
        GPIO_InitTypeDef GPIO_InitStructure;
        SPI_InitTypeDef SPI_InitStructure;

        /* Enable SPI1 Periph clock */
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA
                               | RCC_APB2Periph_AFIO | RCC_APB2Periph_SPI1,
                               ENABLE);

        /* Configure SPI1 pins: PA5-SCK, PA6-MISO and PA7-MOSI */
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

        /*------------------------ SPI1 configuration ------------------------*/
        SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//SPI_Direction_1Line_Tx;
        SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
        SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
        SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
        SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
        SPI_InitStructure.SPI_NSS  = SPI_NSS_Soft;
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64;/* 72M/64=1.125M */
        SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
        SPI_InitStructure.SPI_CRCPolynomial = 7;

        SPI_I2S_DeInit(SPI1);
        SPI_Init(SPI1, &SPI_InitStructure);

        /* Enable SPI_MASTER */
        SPI_Cmd(SPI1, ENABLE);
        SPI_CalculateCRC(SPI1, DISABLE);

        if (rt_sem_init(&spi1_lock, "spi1lock", 1, RT_IPC_FLAG_FIFO) != RT_EOK)
        {
            rt_kprintf("init spi1 lock semaphore failed\n");
        }
    }

}/* rt_hw_board_init */
int main(void){
	u8 keyFlag = 0x0;
	char temp_str[20];
	//USART_InitTypeDef USART_InitStructure;
	//NVIC_InitTypeDef NVIC_InitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

  //����AFIOʱ��
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

   //����USARTx_Tx������������
  GPIO_InitStructure.GPIO_Pin = GPIO_TxPin;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  //���� USARTx_Rx ��������
  GPIO_InitStructure.GPIO_Pin = GPIO_RxPin;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

		 //�������ã� ������ 115200 ����λ 8 ֹͣλ 1  ��żλ NONE
  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_Rx | USART_Mode_Tx;
    //��ʼ������
  USART_Init(USART1, &USART_InitStructure);

	//Usart1 NVIC ����
  NVIC_InitStructure.NVIC_IRQChannel |= USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//��ռ���ȼ�3
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		//�����ȼ�3
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQͨ��ʹ��

	NVIC_Init(&NVIC_InitStructure);	//����ָ���IJ�����ʼ��VIC�Ĵ���

	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//�������ڽ����ж�

	//��������
  USART_Cmd(USART1, ENABLE);

	//SystemInit();  //ϵͳinit����ʹ����������configuration�������������г�ʼ���е�����
	RCC_Configuration();
  NVIC_Configuration();

	//ʹ��APB2��������ʱ��, ��������û�����䣬ǰ�����õ�ȫ��ʧЧ�����������趨��IO��
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
	
	

  //����AFIOʱ��
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

   //����USARTx_Tx������������
  GPIO_InitStructure.GPIO_Pin = GPIO_TxPin;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  //���� USARTx_Rx ��������
  GPIO_InitStructure.GPIO_Pin = GPIO_RxPin;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

		 //�������ã� ������ 115200 ����λ 8 ֹͣλ 1  ��żλ NONE
  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_Rx | USART_Mode_Tx;
    //��ʼ������
  USART_Init(USART1, &USART_InitStructure);

	//Usart1 NVIC ����
  NVIC_InitStructure.NVIC_IRQChannel |= USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//��ռ���ȼ�3
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		//�����ȼ�3
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQͨ��ʹ��

	NVIC_Init(&NVIC_InitStructure);	//����ָ���IJ�����ʼ��VIC�Ĵ���

	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//�������ڽ����ж�

	//��������
  USART_Cmd(USART1, ENABLE);
	
	//usart1_init();
	led_init();
	key_init();

	
	TIM2_init();

	tcp_state = 0x00;
	while(1){
		/*
		if(tcp_state > 0)
		{
			sprintf(temp_str, "%d", rx_total);
			strcat((char *)temp_str, "-");
			Uart1_PutString(temp_str, strlen(temp_str));
			Uart1_PutString("pealse press key1 to update", 28);

			tcp_state = 0;
		}

		if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0){//����
			Delay(0xAA200);
			if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0){
				Uart1_PutString("updating....", 13);
				iap_write_appbin(appxaddr,USART_RX_BUF ,rx_total);
				Uart1_PutString("updated. please press key2 to start new app", 44);
				Uart1_PutString("pealse press key1 to update", 28);
			}
		}

		if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == 0){//����
			Delay(0xAA200);
			if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == 0){
				Uart1_PutString("starting ....", 14);
				iap_load_app(appxaddr);
				Uart1_PutString("start up ....", 14);
			}
		}
		*/
		/**/
		if(tcp_state > 0)
		{
				//total += count;
				sprintf(temp_str, "%d", rx_total);
				strcat((char *)temp_str, "-");
				Uart1_PutString(temp_str, strlen(temp_str));
				//Uart1_PutString(USART_RX_BUF,  count);
				Uart1_PutString("over---",  8);

				tcp_state = 0;
				rx_total = 0;
		}
		/**/

/**
		if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0){
			Delay(0xAA200);
			if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0){
				if(keyFlag > 0){
					GPIO_Write(GPIOB, 0x0000);
					keyFlag = 0;
				}else{
					GPIO_Write(GPIOB, 0xffff);
					keyFlag = 1;
				}
			}
		}
**/
	}
}
Esempio n. 7
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
     */

  /* Configure the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers */
  SetSysClock();

  /* 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);

  /* NVIC configuration ------------------------------------------------------*/
  NVIC_Configuration();

  /* Initialize Leds mounted on STM3210X-EVAL board --------------------------*/
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* Output HSE clock on MCO pin ---------------------------------------------*/
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
  RCC_MCOConfig(RCC_MCO_HSE);

  while (1)
  {
    /* Toggle LED1 */
    STM_EVAL_LEDToggle(LED1);
    /* Insert delay */
    Delay(DELAY_COUNT);

    /* Toggle LED2 */
    STM_EVAL_LEDToggle(LED2);
    /* Insert delay */
    Delay(DELAY_COUNT);

    /* Toggle LED3 */
    STM_EVAL_LEDToggle(LED3);
    /* Insert delay */
    Delay(DELAY_COUNT);

    /* Toggle LED4 */
    STM_EVAL_LEDToggle(LED4);
    /* Insert a delay */
    Delay(DELAY_COUNT);
  }
}
Esempio n. 8
0
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
       */

    //================= Initialisation pin et interruptions =============================

    GPIO_Configuration();
    NVIC_Configuration(); 	/* Interrupt Config SDIO*/
    EXTILine0_Config();		// Interrupt PA0
    Timer2_Config();		//Configure timer2 1[s]
    Init_Uart2(4800);
    Init_Uart3(4800);
    Init_SDCard();			//Mount sd card and use fat32 format

    fileUart2 = initialiserFile();	//Init fifo pile
    fileUart3 = initialiserFile();	//Init fifo pile


    while(1) 	/* Infinite loop */
    {
        switch(etatBtBleu)
        {
        case START:
            enableUsartIt();
            GPIO_SetBits(GPIOD, GPIO_Pin_12); 			//Turn on green led
            led_gr_blink = 1;							//Activate the blink mod in an interruption

            writeHeader(head_txt2, file2_path);		//header for the usart2 file
            writeHeader(head_txt3, file3_path);		//header for the usart3 file

            etatBtBleu = RUN;
            break;

        case STOP:
            disableUsartIt();							//we will read the fifo pile so it's better to inibit usart interrupt
            led_gr_blink = 0;
            GPIO_ResetBits(GPIOD, GPIO_Pin_12); 		//green led	off
            GPIO_SetBits(GPIOD, GPIO_Pin_15);			//blue led on

            writeDynamicTabData(pullN(fileUart2, nbCaractUart2), nbCaractUart2, file2_path);			//write all the fifo's uart2 data
            writeDynamicTabData(pullN(fileUart3, nbCaractUart3), nbCaractUart3, file3_path);			//write all the fifo's uart3 data

            GPIO_ResetBits(GPIOD, GPIO_Pin_15);			//blue led off

            nbCaractUart2 = 0;
            nbCaractUart3 = 0;
            etatBtBleu=WAIT;

            break;

        case RUN:
            //=========== write data when we have NB_CARACT_STOCK into the usart2 fifo pile =============
            if(flag_fileUart2Ready)
            {
                flag_fileUart2Ready=0;
                writeDynamicTabData(pullN(fileUart2, NB_CARACT_STOCK), NB_CARACT_STOCK, file2_path);	//write NB_CARACT_STOCK of uart2 data
                GPIO_ResetBits(GPIOD, GPIO_Pin_15);		//blue led off
            }

            //=========== write data when we have NB_CARACT_STOCK into the usart3 fifo pile =============
            if(flag_fileUart3Ready)
            {
                flag_fileUart3Ready = 0;
                writeDynamicTabData(pullN(fileUart3, NB_CARACT_STOCK), NB_CARACT_STOCK, file3_path);	//write NB_CARACT_STOCK of uart3 data
                GPIO_ResetBits(GPIOD, GPIO_Pin_15);		//blue led off
            }
            break;
        }
    }
}
Esempio n. 9
0
int main(void)
{
    Delay_ms(100);
    Periph_clock_enable();
    GPIO_Config();
    Usart4Init();
    I2C_Config();
    ADC_Config();
    MPU6050_Init();
    Timer1_Config();
    Timer8_Config();
    Timer2_Config();
    Timer5_Config();
    Timer4_Config();
    Timer3_Config();//RC control timer
    NVIC_Configuration();
    EXTI_Config();

    TIM_Cmd(TIM5, ENABLE);
    TIM_CtrlPWMOutputs(TIM5, ENABLE);

    for (i = 1 ; i < 1 ; i++) ; //small delay before starting Timer4

    TIM_Cmd(TIM4, ENABLE);
    TIM_CtrlPWMOutputs(TIM4, ENABLE);



    Delay_ms(100);

    for (i = 0; i < configDataSize; i++) //reads configuration from eeprom
    {
        ReadFromEEPROM(i);
        configData[i] = EepromData;
        Delay_ms(5);
    }

    I2C_AcknowledgeConfig(I2C2, ENABLE);

    Delay_ms(100);



    while (1)
    {
        LEDon;
        DEBUG_LEDon;

        while (ConfigMode == 1)
        {
            TimerOff();   //Configuration loop
        }

        MPU6050_ACC_get();//Getting Accelerometer data

        acc_roll_angle = -(atan2(accADC_x, accADC_z)) + (configData[11] - 50.00) * 0.0035; //Calculating pitch ACC angle+callibration
        acc_pitch_angle  = +(atan2(accADC_y, accADC_z));   //Calculating roll ACC angle

        MPU6050_Gyro_get();//Getting Gyroscope data

        acc_roll_angle_vid = ((acc_roll_angle_vid * 99.00) + acc_roll_angle) / 100.00; //Averaging pitch ACC values
        acc_pitch_angle_vid = ((acc_pitch_angle_vid * 99.00) + acc_pitch_angle) / 100.00; //Averaging roll  ACC values

        sinus   = sinusas[(int)(rc4)];      //Calculating sinus
        cosinus = sinusas[90 - (int)(rc4)]; //Calculating cosinus

        ROLL = -gyroADC_z * sinus + gyroADC_y * cosinus;
        roll_angle = (roll_angle + ROLL * dt)    + 0.0002 * (acc_roll_angle_vid - roll_angle); //Roll Horizon

        //ROLL=-gyroADC_z*sinus+gyroADC_y*cosinus;
        yaw_angle = (yaw_angle + gyroADC_z * dt); //Yaw

        pitch_angle_true = ((pitch_angle_true  + gyroADC_x * dt) + 0.0002 * (acc_pitch_angle_vid - pitch_angle_true)); //Pitch Horizon

        ADC1Ch1_vid = ((ADC1Ch1_vid * 99.00) + (readADC1(1) / 4000.00)) / 100.00; //Averaging ADC values
        ADC1Ch1_vid = 0.00;

        rc4_avg = ((rc4_avg * 499.00) + (rc4)) / 500.00; //Averaging RC4 values
        pitch_angle = pitch_angle_true - rc4_avg / 57.3; //Adding angle

        pitch_angle_correction = pitch_angle * 150.0;

        if (pitch_angle_correction > 2.0)
        {
            pitch_angle_correction = 2.0;
        }

        if (pitch_angle_correction < -2.0)
        {
            pitch_angle_correction = -2.0;
        }

        pitch_setpoint = pitch_setpoint + pitch_angle_correction; //Pitch return to zero after collision

        roll_angle_correction = roll_angle * 200.0;

        if (roll_angle_correction > 2.0)
        {
            roll_angle_correction = 2.0;
        }

        if (roll_angle_correction < -2.0)
        {
            roll_angle_correction = -2.0;
        }

        roll_setpoint = roll_setpoint + roll_angle_correction; //Roll return to zero after collision



        ADC1Ch13_vid = ((ADC1Ch13_vid * 99.00) + ((readADC1(13) - 2000) / 4000.00)) / 100.00; //Averaging ADC values

        if (configData[10] == '0')
        {
            yaw_angle = (yaw_angle + gyroADC_z * dt) + 0.01 * (ADC1Ch13_vid - yaw_angle);   //Yaw AutoPan
        }

        if (configData[10] == '1')
        {
            yaw_angle = (yaw_angle + gyroADC_z * dt);   //Yaw RCPan
        }

        yaw_angle_correction = yaw_angle * 50.0;

        if (yaw_angle_correction > 1.0)
        {
            yaw_angle_correction = 1.0;
        }

        if (yaw_angle_correction < -1.0)
        {
            yaw_angle_correction = -1.0;
        }

        yaw_setpoint = yaw_setpoint + yaw_angle_correction; //Yaw return to zero after collision

        pitch_PID();//Pitch axis pid
        roll_PID(); //Roll axis pid
        yaw_PID(); //Yaw axis pid


        printcounter++; //Print data to UART

        if (printcounter >= 100)
        {
            //sprintf (buff, " %d %d %c Labas\n\r", ACCread[0], ACCread[1], ACCread[2]);
            //sprintf (buff, " %x %x %x %x %x %x Labas\n\r", ACCread[0], ACCread[1], ACCread[2], ACCread[3], ACCread[4], ACCread[5]);
            //sprintf (buff, "Labas %d %d\n\r", ACCread[0], ACCread[1]);
            //sprintf (buff, "%3.1f %f\n\r", ADC1Ch1_vid*57.3, sinus);
            //sprintf (buff, "Labas %f %f %f \n\r", accADC_x, accADC_y, accADC_z);
            //sprintf (buff, "%3.1f %3.1f \n\r", acc_roll_angle_vid*57.3,  acc_pitch_angle_vid *57.3);
            //sprintf (buff, "%3.1f %3.1f \n\r", pitch_angle*57.3,  roll_angle*57.3);
            //sprintf (buff, "%d\n\r", rc4);
            //USART_PutString(buff);
            printcounter = 0;
        }

        stop = 0;
        LEDoff;
        watchcounter = 0;

        while (stop == 0) {} //Closed loop waits for interrupt


    }
}
Esempio n. 10
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{  
	uint16 i; 
        RCC_Configuration(); // Configure the system clocks
	NVIC_Configuration(); // NVIC Configuration
	GPIO_Configuration();
	USART1_Init(115200);
	Timer_Configuration();
        
        printf("============================================\r\n");
	printf("   HTTP client for W5200 \r\n");
	printf("============================================\r\n");
       
	WIZ_SPI_Init();	
        Reset_W5200();
        wizInit();
        InitNetInfo();
        DisplayNetInfo();
	              
        // LED3 and LED4 On!
	LED3_onoff(ON);
	LED4_onoff(ON);
     
       
        uint8  url[MAX_URL_SIZE];			//full url
	uint8  url_dn[MAX_URL_SIZE];			//domain name url
	uint8  url_path[MAX_URL_SIZE];		//local path in html server
	char * split;				//string split pointer 
	
	
	uint16 done_http = 0;
	uint16 start_idx = 0 ;
	uint16 end_idx = 0;
	uint16 tmp_start;
	uint16 tmp_end;
	uint8 BR [4]= "<BR>";
	uint8 rBR [4]= "\r\n";
	uint8 TITLE [7]= "<TITLE>";
	uint8 bTITLE [8]= "</TITLE>";
	

	uint16 tmp_idx;
	uint8 no_pr = 0;
	uint8 str[17];
       
	
            while (1)
            {
                          
              sprintf((char*)str,"%.3d.%.3d.%.3d.%.3d ",
				IINCHIP_READ (SIPR0+0), IINCHIP_READ (SIPR0+1), 
				IINCHIP_READ (SIPR0+2), IINCHIP_READ (SIPR0+3));
                            
                           
                            /* Get Http Address  */
                            printf("\r\n Please enter a HTTP Address without 'http://' \n\r"); 
                            printf("http://");
                            memset(url,0,sizeof(url));	
                            //Modified by Gang 2011-10-04
                            zScanf_s(1, url);
                            printf("\r\n Your HTTP address is: %s \r\n",url);		
                            
                            /* Parse URL Path  */
                            split = strchr((char const*)url,'/');			
                            strcpy((char*)url_path,split); 			
                            printf("Domain path: %s \r\n",url_path);
                    
                            /* Parse URL Domain  */
                            split = strtok((char*)url,"/");			
                            strcpy((char*)url_dn,split);				
                            printf("Domain name: %s \r\n",url_dn);
                            
               
                            /* Do DNS Client */
                            memset(httpclient_NetInfo.HTTPs_IP,0,sizeof(httpclient_NetInfo.HTTPs_IP));
                            //Delay_ms(10);
                            done_dns = dns_query(DNS_SOCK, url_dn, httpclient_NetInfo.HTTPs_IP);
                            printf("\r\n HTTPs_IP= %d.%d.%d.%d",httpclient_NetInfo.HTTPs_IP[0],httpclient_NetInfo.HTTPs_IP[1],httpclient_NetInfo.HTTPs_IP[2],httpclient_NetInfo.HTTPs_IP[3]);
                          
                            while(done_dns) {
                            
                            /* Do HTTP Client */
                            done_http = http_client(HTTPC_SOCK, httpclient_NetInfo.HTTPs_IP, url_path, url_dn,data_buf);
                           
                            if(done_http) { // on success, done_dns is not  '0'
                                            
    #define Recieved_DATA
    #ifdef Recieved_DATA
                                            printf("\r\n<< Recieved Data -- START>> \r\n");
                                           
                                            for(i=0; i<done_http; i++){
                                                  
                                                  printf("%c",(uint8)data_buf[i]);
                                              }   
                                            printf("\r\n");
                                            printf("<< Recieved Data -- END>> \r\n");
                                           
    #endif
                                        /* parsed index */
                                            //All other HTML elements are nested between the opening <html> and </html> tags.
                                            start_idx = pased_idx((uint8 *)str_start , sizeof(str_start), done_http );
                                            end_idx   = pased_idx((uint8 *)str_end , sizeof(str_end), done_http );			
    
                                            /* printf get <html> ...</html> */							
                                            for(i=start_idx; i<(end_idx+7); i++){						
                                                    /* remove header */
                                                    data_buf[i-start_idx] = data_buf[i];
                                             }   
                                            printf("\r\n");
                                            
    
                                            /* replace <br> tag to \r\n */
                                            //The br tag is used for specifying a line break.
                                            do{
                                                    tmp_idx = pased_idx((uint8*)BR, sizeof(BR) , end_idx-start_idx) ;
                                                    if(tmp_idx == 0 ) 
                                                            break;
                                                 
                                                    memcpy((uint8 *)data_buf+tmp_idx, (uint8*)rBR, sizeof(rBR)) ;
                                            }while(tmp_idx!=end_idx-start_idx);
    
    #define Parsed_DATA
    #ifdef Parsed_DATA
                                            /* parsed DATA */
                                            printf("\r\n<< Parsed Data -- START >>");
                                            printf("\r\nTITLE : \r\n");
                                            /* parse <TITLE> and </TITLE> tags */
                                            tmp_start = pased_idx((uint8 *)TITLE , sizeof(TITLE),(end_idx-start_idx) ) + sizeof(TITLE);
                                            tmp_end   = pased_idx((uint8 *)bTITLE , sizeof(bTITLE),(end_idx-start_idx) );												
                                            for(i=tmp_start; i<tmp_end; i++){
                                                   
                                                    printf("%c",(uint8)data_buf[i]); // printf title
                                            }   
    
                                            printf("\r\n BODY : \r\n");
                                            /*DO NOT PRINT TAG COMMAND: between '<' with '>' */
                                            for(i=tmp_end; i<(end_idx-start_idx); i++){
                                                    //Tag command - ex.)<PRE>
                                                    //'<' is a start point of tag command.
                                                    if((uint8)data_buf[i]=='<'){ 
                                                            no_pr = 0;
                                                    }
                                                    //'>' is a end point of Tag command.
                                                    //To avoid in row tags -> ex.) <PRE><H1>						
                                                    if((uint8)data_buf[i]=='>' && (uint8)data_buf[i+1] !='<' ) {
                                                            no_pr = 1;
                                                            i++;
                                                    }					
                                                    if(no_pr){
                                                        Delay_ms(1);    
                                                        printf("%c",(uint8)data_buf[i]);
                                                    }
                                            }   
                                            printf("\r\n<< Parsed Data -- END >>\r\n");
    #endif
                                            /* Init. parameter */
                                            start_idx= 0;
                                            end_idx= 0;				
                                    done_dns = 0;  
                                    break;
    
                            }
                           //done_http
                            //done_dns=0;
                    }//while : done_dns == 1		
            }
}
Esempio n. 11
0
void Init_CAN(int can_num,uint8_t CAN_Mode,GPIO_TypeDef *tx_port,uint16_t tx_pin,GPIO_TypeDef *rx_port,uint16_t rx_pin){

	/* Define InitTypeDef ---------------------------------------------------*/
	CAN_InitTypeDef 		CAN_InitStructure;

	/* initialize InitTypeDef -----------------------------------------------*/
	CAN_StructInit(&CAN_InitStructure);
	/* Supply clock source --------------------------------------------------*/
	if(can_num == 1){
		CAN_DeInit(CAN1);
		RCC_APB1PeriphClockCmd( RCC_APB1Periph_CAN1, ENABLE);
	}else if(can_num == 2){
		CAN_DeInit(CAN2);
		RCC_APB1PeriphClockCmd( RCC_APB1Periph_CAN2, ENABLE);
	}
	/* Define gpio_config ---------------------------------------------------*/
	
	Init_port(GPIO_Mode_AF,tx_port,tx_pin,GPIO_PuPd_UP,GPIO_OType_PP);
	Init_port(GPIO_Mode_AF,rx_port,rx_pin,GPIO_PuPd_UP,GPIO_OType_PP);

	if(can_num == 1){
		GPIO_PinAFConfig(tx_port, Pin_select_source(tx_pin), GPIO_AF_CAN1);//Tx
		GPIO_PinAFConfig(rx_port, Pin_select_source(rx_pin), GPIO_AF_CAN1);//Rx
	}else if(can_num == 2){
		GPIO_PinAFConfig(tx_port, Pin_select_source(tx_pin), GPIO_AF_CAN2);//Tx
		GPIO_PinAFConfig(rx_port, Pin_select_source(rx_pin), GPIO_AF_CAN2);//Rx
	}
	/* Set up CAN function -------------------------------------------------*/
	/* タイムトリガ通信モードの有効化・無効化を設定する */
	CAN_InitStructure.CAN_TTCM 		= ENABLE;

	/* 自動バスオフ管理(Automatic Bus-Off Management)の有効化・無効化を設定する */
	CAN_InitStructure.CAN_ABOM 		= DISABLE;

	/* 自動再起動モードの有効化・無効化を設定する  */
	CAN_InitStructure.CAN_AWUM 		= DISABLE;

	/* 自動再送信禁止を有効化・無効化する DISABLE: 自動再送信禁止を無効化(つまり再送信は有効) ENABLE: 自動再送信禁止。正常に送信されなくても送信は1回だけ行われる */
	CAN_InitStructure.CAN_NART 		= DISABLE;

	/* 受信FIFOロックモードの有効化・無効化を設定する */
	CAN_InitStructure.CAN_RFLM 		= DISABLE;

	/* 送信FIFOの送信順序を指定する。DISABLE:メッセージIDで送信順序が決定される  ENABLE:ソフトウェアで送信要求が発生された順番で送信される */
	CAN_InitStructure.CAN_TXFP 		= DISABLE;

	/* CANのModeを設定する */
//	CAN_InitStructure.CAN_Mode 		= CAN_Mode_Normal;
	CAN_InitStructure.CAN_Mode 		= CAN_Mode;

	/* 再同期ジャンプ幅(CANハードウェアが再同期を行う際のビット幅)を時間単位の数で設定する */
	CAN_InitStructure.CAN_SJW 		= CAN_SJW_1tq;

	/* CANビットタイミングレジスタ(CAN_BTR)のTS1[3:0]を設定する。 */
	CAN_InitStructure.CAN_BS1 		= CAN_BS1_6tq;

	/* CANビットタイミングレジスタ(CAN_BTR)のTS2[2:0]を設定する */
	CAN_InitStructure.CAN_BS2 		= CAN_BS2_7tq;

	/* ボーレートプリスケーラ設定する 1〜1024 APB1=42MHz*/
	CAN_InitStructure.CAN_Prescaler	= 3;
	//1Mbps

	if(can_num == 1){
		CAN_Init(CAN1, &CAN_InitStructure);
	}else if(can_num == 2){
		CAN_Init(CAN2, &CAN_InitStructure);
	}



#ifdef USE_INTERRUPT_CAN_RX
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);

	if(can_num == 1){
		NVIC_Configuration(CAN1_RX0_IRQn);
		CAN_ITConfig(CAN1, CAN_IT_FMP0,ENABLE);//message pending Interrupt
		/*
		CAN_ITConfig(CAN1, CAN_IT_EWG, ENABLE);//Error passive Interrupt
		CAN_ITConfig(CAN1, CAN_IT_EPV, ENABLE);//Error passive Interrupt
		CAN_ITConfig(CAN1, CAN_IT_BOF, ENABLE);//Bus-off Interrupt
		CAN_ITConfig(CAN1, CAN_IT_LEC, ENABLE);//tLast error code Interrupt
		CAN_ITConfig(CAN1, CAN_IT_ERR, ENABLE);//Error Interrupt
		*/
	}else if(can_num == 2){
		NVIC_Configuration(CAN2_RX0_IRQn);
		CAN_ITConfig(CAN2, CAN_IT_FMP0,ENABLE);//message pending Interrupt
		/*
		CAN_ITConfig(CAN2, CAN_IT_EWG, ENABLE);//Error passive Interrupt
		CAN_ITConfig(CAN2, CAN_IT_EPV, ENABLE);//Error passive Interrupt
		CAN_ITConfig(CAN2, CAN_IT_BOF, ENABLE);//Bus-off Interrupt
		CAN_ITConfig(CAN2, CAN_IT_LEC, ENABLE);//tLast error code Interrupt
		CAN_ITConfig(CAN2, CAN_IT_ERR, ENABLE);//Error Interrupt
		*/
	}
#endif

#ifdef USE_INTERRUPT_CAN_TX
	if(can_num == 1){
		CAN_ITConfig(CAN1, CAN_IT_TME, ENABLE);//Transmit mailbox empty Interrupt
	}else if(can_num == 2){
		CAN_ITConfig(CAN2, CAN_IT_TME, ENABLE);//Transmit mailbox empty Interrupt
	}
#endif

}
Esempio n. 12
0
void rt_hw_usart_init(void)
{
    struct stm32_uart* uart;
    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;

    RCC_Configuration();
    GPIO_Configuration();

#if defined(RT_USING_UART1)
    uart = &uart1;
    config.baud_rate = BAUD_RATE_115200;

    serial1.ops    = &stm32_uart_ops;
    serial1.config = config;

    NVIC_Configuration(&uart1);

    /* register UART1 device */
    rt_hw_serial_register(&serial1, "uart1",
                          RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX ,
                          uart);
#endif /* RT_USING_UART1 */

#if defined(RT_USING_UART2)
    uart = &uart2;

    config.baud_rate = BAUD_RATE_115200;
    serial2.ops    = &stm32_uart_ops;
    serial2.config = config;

    NVIC_Configuration(&uart2);

    /* register UART1 device */
    rt_hw_serial_register(&serial2, "uart2",
                          RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                          uart);
#endif /* RT_USING_UART2 */

#if defined(RT_USING_UART3)
    uart = &uart3;

    config.baud_rate = BAUD_RATE_115200;

    serial3.ops    = &stm32_uart_ops;
    serial3.config = config;

    NVIC_Configuration(&uart3);

    /* register UART1 device */
    rt_hw_serial_register(&serial3, "uart3",
                          RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                          uart);
#endif /* RT_USING_UART3 */

#if defined(RT_USING_UART4)
    uart = &uart4;

    config.baud_rate = BAUD_RATE_115200;

    serial4.ops    = &stm32_uart_ops;
    serial4.config = config;

    NVIC_Configuration(&uart4);

    /* register UART4 device */
    rt_hw_serial_register(&serial4, "uart4",
                          RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                          uart);
#endif /* RT_USING_UART4 */

}
Esempio n. 13
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
     */     

  /* Interrupt Config */
  NVIC_Configuration();

  /*-------------------------- SD Init ----------------------------- */
  Status = SD_Init();

  /*------------------- Block Erase -------------------------------*/
  if (Status == SD_OK)
  {
    /* Erase NumberOfBlocks Blocks of WRITE_BL_LEN(512 Bytes) */
    Status = SD_Erase(0x00, (BLOCK_SIZE * NUMBER_OF_BLOCKS));
  }

  if (Status == SD_OK)
  {
    Status = SD_ReadMultiBlocks(Buffer_MultiBlock_Rx, 0x00, BLOCK_SIZE, NUMBER_OF_BLOCKS);
  }

  if (Status == SD_OK)
  {
    EraseStatus = eBuffercmp(Buffer_MultiBlock_Rx, MULTI_BUFFER_SIZE);
  }
  
  /*------------------- Block Read/Write --------------------------*/
  /* Fill the buffer to send */
  Fill_Buffer(Buffer_Block_Tx, BLOCK_SIZE, 0xFFFF);


  if (Status == SD_OK)
  {
    /* Write block of 512 bytes on address 0 */
    Status = SD_WriteBlock(Buffer_Block_Tx, 0x00, BLOCK_SIZE);
  }

  if (Status == SD_OK)
  {
    /* Read block of 512 bytes from address 0 */
    Status = SD_ReadBlock(Buffer_Block_Rx, 0x00, BLOCK_SIZE);
  }

  if (Status == SD_OK)
  {
    /* Check the corectness of written dada */
    TransferStatus1 = Buffercmp(Buffer_Block_Tx, Buffer_Block_Rx, BLOCK_SIZE);
  }

  /*--------------- Multiple Block Read/Write ---------------------*/
  /* Fill the buffer to send */
  Fill_Buffer(Buffer_MultiBlock_Tx, MULTI_BUFFER_SIZE, 0x0);

  if (Status == SD_OK)
  {
    /* Write multiple block of many bytes on address 0 */
    Status = SD_WriteMultiBlocks(Buffer_MultiBlock_Tx, 0x00, BLOCK_SIZE, NUMBER_OF_BLOCKS);
  }

  if (Status == SD_OK)
  {
    /* Read block of many bytes from address 0 */
    Status = SD_ReadMultiBlocks(Buffer_MultiBlock_Rx, 0x00, BLOCK_SIZE, NUMBER_OF_BLOCKS);
  }

  if (Status == SD_OK)
  {
    /* Check the corectness of written dada */
    TransferStatus2 = Buffercmp(Buffer_MultiBlock_Tx, Buffer_MultiBlock_Rx, MULTI_BUFFER_SIZE);
  }

  /* Infinite loop */
  while (1)
  {}
}
Esempio n. 14
0
/*
 * Init all related hardware in here
 * rt_hw_serial_init() will register all supported USART device
 */
void rt_hw_usart_init()
{
	struct stm32_uart* uart;
    struct serial_configure config;
	

	RCC_Configuration();

	GPIO_Configuration();

	DMA_Configuration();

	/* uart init */
#ifdef RT_USING_UART1
	uart = &uart1;
    config.baud_rate = BAUD_RATE_115200;
    config.bit_order = BIT_ORDER_LSB;
    config.data_bits = DATA_BITS_8;
    config.parity    = PARITY_NONE;
    config.stop_bits = STOP_BITS_1;
    config.invert    = NRZ_NORMAL;

    serial1.ops    = &stm32_uart_ops;
    serial1.int_rx = &uart1_int_rx;
    serial1.config = config;

    NVIC_Configuration(&uart1);

    /* register UART1 device */
    rt_hw_serial_register(&serial1, "uart1",
                          RT_DEVICE_FLAG_RDWR | 
                          RT_DEVICE_FLAG_INT_RX | 
                          RT_DEVICE_FLAG_STREAM,
                          uart);
#endif

#ifdef RT_USING_UART2
	uart = &uart2;

    config.baud_rate = BAUD_RATE_115200;
    config.bit_order = BIT_ORDER_LSB;
    config.data_bits = DATA_BITS_8;
    config.parity    = PARITY_NONE;
    config.stop_bits = STOP_BITS_1;
    config.invert    = NRZ_NORMAL;

    serial2.ops    = &stm32_uart_ops;
    serial2.int_rx = &uart2_int_rx;
    serial2.config = config;

    NVIC_Configuration(&uart2);

    /* register UART2 device */
    rt_hw_serial_register(&serial2, "uart2",
                          RT_DEVICE_FLAG_RDWR | 
                          RT_DEVICE_FLAG_INT_RX | 
                          RT_DEVICE_FLAG_STREAM,
                          uart);
#endif

#ifdef RT_USING_UART3
	uart = &uart3;

    config.baud_rate = BAUD_RATE_115200;
    config.bit_order = BIT_ORDER_LSB;
    config.data_bits = DATA_BITS_8;
    config.parity    = PARITY_NONE;
    config.stop_bits = STOP_BITS_1;
    config.invert    = NRZ_NORMAL;

    serial3.ops    = &stm32_uart_ops;
    serial3.int_rx = &uart3_int_rx;
    serial3.config = config;

    NVIC_Configuration(&uart3);

    /* register UART3 device */
    rt_hw_serial_register(&serial3, "uart3",
                          RT_DEVICE_FLAG_RDWR | 
                          RT_DEVICE_FLAG_INT_RX | 
                          RT_DEVICE_FLAG_STREAM,
                          uart);
#endif
}
Esempio n. 15
0
// *****************************************************************************
// Function Name  : main
// Description    : Main program.
// Input          : None
// Output         : None
// Return         : None
// *****************************************************************************
int main(void)
{
#ifdef DEBUG
	debug();
#endif
	int i,j;
		WINDOW * wnd;
		BUTTON * btn;
		GOL_SCHEME *pScheme;


    //  System clock configuration
    RCC_Configuration();  
		  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE);  
    // Nested Vector Interrupt Controller configuration
    NVIC_Configuration();   

		LCD_GPIO_Configuration();
		FSMC_LCD_Init();
		USART1_Init();
		ILI9325_Init();
		ILI9325_VerticalScreen();
		ILI9325_GRAMOperation();  //Tell ILI9325 that I'm now starting to write GRAM.
    for(i=0;i<240;i++)
    {
       for(j=0;j<320;j++)
       {
          unsigned int n=i*320+j;
          if(n<25600)
          { 
            ILI9325_WriteWDR(n);
          }   
    
          else if(n<51200)
          { 
            ILI9325_WriteWDR(n);
          }
    
          else if(n<76800)
          { 
            ILI9325_WriteWDR(0xf800);
          }
      } 
		}
			

		ILI9325_FillWindowArea(10,10,100,100,0x001f);

		pScheme = GOLCreateScheme();


		wnd=WndCreate(0,                // ID
                         0,0,GetMaxX(),GetMaxY(),   // whole screen dimension
                         WND_DRAW,                  // set state to draw all
                         NULL,             // icon
                         "Place Title Here.",       // text
                         pScheme);                     // use default GOL scheme
		WndDraw(wnd);

		btn=BtnCreate(1,20,64,50,118,0, BTN_DRAW, NULL, "ON", pScheme);
		BtnDraw(btn);



						    
    while(1)
    {

		}
		

		    
}
Esempio n. 16
0
 int main(void)
 {
		u8 Data_PC[SIZE];    //从Flash中读取数据到Data_PC,并上传至上位机
	  u16 a,b=0;

		delay_init();	    	 //延时函数初始化	  
		NVIC_Configuration();//设置NVIC中断分组2:2位抢占优先级,2位响应优先级
		uart_init(9600);	   //串口初始化为9600
		LED_Init();			     //LED端口初始化
		LCD_Init();
	  KEY_Init(); 
		WORD_Init();	
	  TIM2_Int_Init(999,7199);	  
	  TIM3_Int_Init(9,7199);
	  EXTIX_Init();		 	   //外部中断初始化
		Adc_Init();		  		 //ADC初始化
	 	SPI_Flash_Init();  	 //SPI FLASH 初始化 
		
	while(1)
	{
//功能:开机状态显示
//说明:1.开机,绿灯亮(DS1)
//      2.使用temp是为了避免重复执行该if语句
		if(flag2==1&&temp==0)     
		{
		  while(SPI_Flash_ReadID()!=W25Q64)							//检测不到W25Q64
			{
				LCD_ShowString(40,150,200,16,16,"W25Q64 Check Failed!");
				delay_ms(500);
				LCD_ShowString(40,150,200,16,16,"Please Check!      ");
				delay_ms(500);
				LED0=!LED0;//DS0闪烁
			}
	    LCD_ShowString(60,130,200,16,16,"W25Q64 Ready!");
		  LED1=0;
			temp=1;
    }
		
//功能:数据采集并保存至Flash中	
//说明:1.使用temp1是为了避免重复使能TIM3	
//      2.使用temp2是为了避免在数据上传至上位机的过程中,与终止上传功能相冲突
//      3.flag1=1代表按键按下,并开始采集	
//      4.flag2=1代表开机,flag2=0代表未开机	
//      5.采集过程中,红灯(DS0)以一定频率闪烁		
		if(flag2==1&&temp2==0&&flag1==1)
		{
      if(temp1==0)
			{
				LCD_ShowString(20,150,200,16,16,"Data collection began...");
			  TIM_Cmd(TIM3, ENABLE);   //使能TIM3中断
        LED0=0;				
      }
			temp1=1;
			if(flag_cycle==0&&flag_cycle_1==0)
			{
				SPI_Flash_Write((u8*)TEXT_Buffer2,FLASH_SIZE+counter*SIZE,SIZE);
				counter++;
				flag_cycle_1=1;
      }
			if(flag_cycle==1&&flag_cycle_1==0)
			{
				SPI_Flash_Write((u8*)TEXT_Buffer1,FLASH_SIZE+counter*SIZE,SIZE);
				counter++;
				flag_cycle_1=1;
      }						
		}

//功能:将Flash中采集到的数据上传至上位机	
//说明:1.使用temp1是为了保证上传是在采集之后进行
//      2.使用temp3是为了避免由于按键误操作使得该程序重复被执行
//      3.flag1=0代表按键再次被按下,上传开始	;若再次被按下,则上传被终止;之后再按就没有作用了	
//      4.上传过程中,红灯(DS0)以一定频率闪烁
		if(temp1==1&&temp3==0&&flag1==0)
		{
			TIM_Cmd(TIM3, DISABLE);    //失能TIM3中断
			
			//用于解决当采集时间不是42ms的倍数时,部分采集数据未写入FLash的问题
			if((time_collect-1)%42!=0)
			{
				data_residue=(time_collect-1)%42*6;
				if(flag_cycle==0)
				{
					SPI_Flash_Write((u8*)TEXT_Buffer2,FLASH_SIZE+(counter+1)*SIZE,SIZE);
        }
				if(flag_cycle==1)
				{
					SPI_Flash_Write((u8*)TEXT_Buffer1,FLASH_SIZE+(counter+1)*SIZE,SIZE);					
        }
      }
				
			LCD_ShowString(20,170,200,16,16,"Data collection complete!");
			LCD_ShowString(20,190,200,16,16,"Data is being uploaded...");
			temp2=1;

			for(a=1;a<counter;a++)
			{
				LED0=!LED0;
				SPI_Flash_Read(Data_PC,FLASH_SIZE+a*SIZE,SIZE);
				for(b=0;b<SIZE;b++)     
				{
				 if(flag1==1)      //上传中途使用按键停止传送
				 {
					break;
				 }
				 USART_GetFlagStatus(USART1, USART_FLAG_TC);
				 USART_SendData(USART1,Data_PC[b]);			  
				 while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET);				
				}
				if(flag1==1)      //上传中途使用按键停止传送
				{
				 LCD_ShowString(20,210,200,16,16,"Data upload is terminated!");	
				 break;
				}
			}
			
			//用于解决当采集时间不是42ms的倍数时,部分采集数据未写入FLash的问题
			if(flag1!=1&&(time_collect-1)%42!=0)
			{
				LED0=!LED0;
				SPI_Flash_Read(Data_PC,FLASH_SIZE+(a+1)*SIZE,SIZE);
				for(b=0;b<data_residue;b++)     
				{
				 if(flag1==1)      //上传中途使用按键停止传送
				 {
					break;
				 }
				 USART_GetFlagStatus(USART1, USART_FLAG_TC);
				 USART_SendData(USART1,Data_PC[b]);			  
				 while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET);				
				}
				if(flag1==1)      //上传中途使用按键停止传送
				{
				 LCD_ShowString(20,210,200,16,16,"Data upload is terminated!");	
				 break;
				}
      }
			
			if(flag1!=1)   //要么显示数据上传完成,要么显示数据上传完成
			{
				LCD_ShowString(20,210,200,16,16,"Data upload is completed!");
			}
			temp3=1;		
     }

//功能:关机并擦除Flash	
//说明:1.flag2=0代表关机,与上temp1,temp2是要保证前面的已被执行
//      2.关机过程中擦除Flash,完成之后红绿灯同时亮一秒后灭		 
		if(temp1==1&&temp2==1&&flag2==0)   //关机机状态显示
		{
			flag1=0;
			flag2=0;
      temp1=0;
      temp2=0;			
			LED0=1;
			LED1=1;
			SPI_Flash_Erase_Chip();
		  LED0=0;
			LED1=0;
			delay_ms(1000);
			LED0=1;
			LED1=1;
			LCD_ShowString(80,230,200,16,16,"Shutdown!");
    }
  }	
}
Esempio n. 17
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
     */     
       
  /* System clocks configuration ---------------------------------------------*/
  RCC_Configuration();

  /* NVIC configuration ------------------------------------------------------*/
  NVIC_Configuration();

  /* GPIO configuration ------------------------------------------------------*/
  GPIO_Configuration();

  /* Configure LED GPIO Pin ------------------------------------------------- */
  STM_EVAL_LEDInit(LED1);

  /* ADC1 Configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = DISABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 1;
  ADC_Init(ADC1, &ADC_InitStructure);

  /* ADC1 regular channel14 configuration */ 
  ADC_RegularChannelConfig(ADC1, ADC_Channel_14, 1, ADC_SampleTime_13Cycles5);

  /* Configure high and low analog watchdog thresholds */
  ADC_AnalogWatchdogThresholdsConfig(ADC1, 0x0B00, 0x0300);
  /* Configure channel14 as the single analog watchdog guarded channel */
  ADC_AnalogWatchdogSingleChannelConfig(ADC1, ADC_Channel_14);
  /* Enable analog watchdog on one regular channel */
  ADC_AnalogWatchdogCmd(ADC1, ADC_AnalogWatchdog_SingleRegEnable);

  /* Enable AWD interupt */
  ADC_ITConfig(ADC1, ADC_IT_AWD, ENABLE);

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

  /* Enable ADC1 reset calibaration register */   
  ADC_ResetCalibration(ADC1);
  /* Check the end of ADC1 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC1));

  /* Start ADC1 calibaration */
  ADC_StartCalibration(ADC1);
  /* Check the end of ADC1 calibration */
  while(ADC_GetCalibrationStatus(ADC1));

  /* Start ADC1 Software Conversion */ 
  ADC_SoftwareStartConvCmd(ADC1, ENABLE);

  while (1)
  {
  }
}
Esempio n. 18
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System Clocks Configuration */
  RCC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* GPIO Configuration */
  GPIO_Configuration();

  /* TIM1 and Timers(TIM3 and TIM4) synchronisation in parallel mode -----------
     1/TIM1 is configured as Master Timer:
     - PWM Mode is used
     - The TIM1 Update event is used as Trigger Output
    
  2/TIM3 and TIM4 are slaves for TIM1,
     - PWM Mode is used
     - The ITR0(TIM1) is used as input trigger for both slaves
     - Gated mode is used, so starts and stops of slaves counters
       are controlled by the Master trigger output signal(update event).

  TIM1CLK = 72 MHz, Prescaler = 0, TIM1 counter clock = 72 MHz
  The Master Timer TIM1 is running at:
  TIM1 frequency = TIM1 counter clock / (TIM1_Period + 1) = 281.250 KHz
  and the duty cycle is equal to:
  TIM1_CCR1/(TIM1_ARR + 1) = 50%

  The TIM3 is running:
  - At (TIM1 frequency)/((TIM3 period + 1)* (Repetion_Counter+1)) = 18.750 KHz
   and a duty cycle equal to TIM3_CCR1/(TIM3_ARR + 1) = 33.3%
  The TIM4 is running:
  - At (TIM1 frequency)/((TIM4 period + 1)* (Repetion_Counter+1)) = 28.125 KHz
   and a duty cycle equal to TIM4_CCR1/(TIM4_ARR + 1) = 50%
  --------------------------------------------------------------------------- */

  /* TIM3 Peripheral Configuration ----------------------------------------*/
  /* TIM3 Slave Configuration: PWM1 Mode */
  TIM_TimeBaseStructure.TIM_Period = 2;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM3 */
  TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM3, TIM_TS_ITR0);


  /* TIM4 Peripheral Configuration ----------------------------------------*/
  /* TIM4 Slave Configuration: PWM1 Mode */
  TIM_TimeBaseStructure.TIM_Period = 1;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM4 */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM4, TIM_TS_ITR0);

  /* TIM1 Peripheral Configuration ----------------------------------------*/
  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 255;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 4;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 127;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  /* Automatic Output enable, Break, dead time and lock configuration*/
  TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
  TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
  TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_1;
  TIM_BDTRInitStructure.TIM_DeadTime = 5;
  TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable;
  TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;
  TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Disable;

  TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);

  /* Master Mode selection */
  TIM_SelectOutputTrigger(TIM1, TIM_TRGOSource_Update);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);
  TIM_Cmd(TIM4, ENABLE);

  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {}
}
Esempio n. 19
0
/**
  * @brief   Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Setup the microcontroller system. Initialize the Embedded Flash Interface,
     initialize the PLL and update the SystemFrequency variable. */
  SystemInit();

  /* Initialize LEDs and Key Button mounted on STM3210X-EVAL board */       
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_PBInit(Button_KEY, Mode_GPIO);

  /* RTC Configuration */
  RTC_Configuration();

  /* Wait until Key Push button is pressed */
  while (STM_EVAL_PBGetState(Button_KEY) != 0)
  {
  }

  /* Get the Frequency value */
  RCC_GetClocksFreq(&RCC_Clocks);

  /* Enable TIM5 APB1 clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);

  /* Connect internally the TM5_CH4 Input Capture to the LSI clock output */
  GPIO_PinRemapConfig(GPIO_Remap_TIM5CH4_LSI, ENABLE);

  /* TIM5 Time base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
  TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);

  /* TIM5 Channel4 Input capture Mode configuration */
  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_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0;
  TIM_ICInit(TIM5, &TIM_ICInitStructure);

  /* Reinitialize the index for the interrupt */
  OperationComplete = 0;

  /* Enable the TIM5 Input Capture counter */
  TIM_Cmd(TIM5, ENABLE);
  /* Reset all TIM5 flags */
  TIM5->SR = 0;
  /* Enable the TIM5 channel 4 */
  TIM_ITConfig(TIM5, TIM_IT_CC4, ENABLE);

  /* NVIC configuration */
  NVIC_Configuration();

  /* Wait the TIM5 measuring operation to be completed */
  while (OperationComplete != 2)
  {}

  /* Compute the actual frequency of the LSI. (TIM5_CLK = 2 * PCLK1)  */
  if (PeriodValue != 0)
  {
    LsiFreq = (uint32_t)((uint32_t)(RCC_Clocks.PCLK1_Frequency * 2) / (uint32_t)PeriodValue);
  }

  /* Adjust the RTC prescaler value */
  RTC_SetPrescaler(LsiFreq - 1);

  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();

  /* Turn on LED2 */
  STM_EVAL_LEDOn(LED2);

  while (1)
  {
    /* Inifinite loop */
  }

}
/*
 * Init all related hardware in here
 * rt_hw_serial_init() will register all supported USART device
 */
void rt_hw_usart_init()
{
	USART_InitTypeDef USART_InitStructure;

	RCC_Configuration();

	GPIO_Configuration();

	NVIC_Configuration();

	DMA_Configuration();

	/* uart init */
#ifdef RT_USING_UART1
	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_Rx | USART_Mode_Tx;
	USART_Init(USART1, &USART_InitStructure);

	/* register uart1 */
	rt_hw_serial_register(&uart1_device, "uart1",
		RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM,
		&uart1);

	/* enable interrupt */
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
#endif

#ifdef RT_USING_UART2
	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_Rx | USART_Mode_Tx;
	USART_Init(USART2, &USART_InitStructure);

	/* register uart2 */
	rt_hw_serial_register(&uart2_device, "uart2",
		RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM,
		&uart2);

	/* Enable USART2 DMA Rx request */
	USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
#endif

#ifdef RT_USING_UART3
	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_Rx | USART_Mode_Tx;
	USART_Init(USART3, &USART_InitStructure);

	uart3_dma_tx.dma_channel= UART3_TX_DMA;

	/* register uart3 */
	rt_hw_serial_register(&uart3_device, "uart3",
		RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_DMA_TX,
		&uart3);

	/* Enable USART3 DMA Tx request */
	USART_DMACmd(USART3, USART_DMAReq_Tx , ENABLE);

	/* enable interrupt */
	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
#endif
}
Esempio n. 21
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System Clocks Configuration */
  RCC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* GPIO Configuration */
  GPIO_Configuration();

  /* DMA Configuration */
  DMA_Configuration();

  /* TIM1 DMA Transfer example -------------------------------------------------
    TIM1CLK = 72 MHz, Prescaler = 0, TIM1 counter clock = 72 MHz 
  The TIM1 Channel3 is configured to generate a complementary PWM signal with 
  a frequency equal to: TIM1 counter clock / (TIM1_Period + 1) = 17.57 KHz and 
  a variable duty cycle that is changed by the DMA after a specific number of
    Update DMA request.
  The number of this repetitive requests is defined by the TIM1 Repetion counter,
  each 3 Update Requests, the TIM1 Channel 3 Duty Cycle changes to the next new 
  value defined by the SRC_Buffer . 
  ----------------------------------------------------------------------------- */

  /* TIM1 Peripheral Configuration ----------------------------------------*/
  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 4095;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 2;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 3 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 127;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC3Init(TIM1, &TIM_OCInitStructure);

  /* TIM1 Update DMA Request enable */
  TIM_DMACmd(TIM1, TIM_DMA_Update, ENABLE);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {}
}
Esempio n. 22
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
     */

  /* System clocks configuration ---------------------------------------------*/
  RCC_Configuration();

  /* NVIC configuration ------------------------------------------------------*/
  NVIC_Configuration();

  /* GPIO configuration ------------------------------------------------------*/
  GPIO_Configuration();

  /* EXTI configuration ------------------------------------------------------*/
  EXTI_Configuration();

  /* DMA1 channel1 configuration ----------------------------------------------*/
  DMA_DeInit(DMA1_Channel1);
  DMA_InitStructure.DMA_PeripheralBaseAddr = ADC1_DR_Address;
  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)ADC_RegularConvertedValueTab;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 64;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA1_Channel1, &DMA_InitStructure);

  /* Enable DMA1 channel1 */
  DMA_Cmd(DMA1_Channel1, ENABLE);

  /* ADC1 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 2;
  ADC_Init(ADC1, &ADC_InitStructure);

  /* ADC1 regular channels configuration */
  ADC_RegularChannelConfig(ADC1, ADC_Channel_4, 1, ADC_SampleTime_28Cycles5);
  ADC_RegularChannelConfig(ADC1, ADC_Channel_14, 2, ADC_SampleTime_28Cycles5);

  /* Regular discontinuous mode channel number configuration */
  ADC_DiscModeChannelCountConfig(ADC1, 1);
  /* Enable regular discontinuous mode */
  ADC_DiscModeCmd(ADC1, ENABLE);

  /* Enable ADC1 external trigger conversion */
  ADC_ExternalTrigConvCmd(ADC1, ENABLE);

  /* Set injected sequencer length */
  ADC_InjectedSequencerLengthConfig(ADC1, 2);
  /* ADC1 injected channel configuration */
  ADC_InjectedChannelConfig(ADC1, ADC_Channel_11, 1, ADC_SampleTime_28Cycles5);
  ADC_InjectedChannelConfig(ADC1, ADC_Channel_12, 2, ADC_SampleTime_28Cycles5);
  /* ADC1 injected external trigger configuration */
  ADC_ExternalTrigInjectedConvConfig(ADC1, ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4);
  /* Enable ADC1 injected external trigger conversion */
  ADC_ExternalTrigInjectedConvCmd(ADC1, ENABLE);

  /* Enable JEOC interrupt */
  ADC_ITConfig(ADC1, ADC_IT_JEOC, ENABLE);

  /* Enable ADC1 DMA */
  ADC_DMACmd(ADC1, ENABLE);

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

  /* Enable ADC1 reset calibration register */
  ADC_ResetCalibration(ADC1);
  /* Check the end of ADC1 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC1));

  /* Start ADC1 calibration */
  ADC_StartCalibration(ADC1);
  /* Check the end of ADC1 calibration */
  while(ADC_GetCalibrationStatus(ADC1));

  while (1)
  {
  }
}
Esempio n. 23
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System clocks configuration ---------------------------------------------*/
  RCC_Configuration();

  /* NVIC configuration ------------------------------------------------------*/
  NVIC_Configuration();

  /* GPIO configuration ------------------------------------------------------*/
  GPIO_Configuration();

  /* 1st phase: SPI1 Master and SPI2 Slave */
  /* SPI1 Config -------------------------------------------------------------*/
  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
  SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
  SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_LSB;
  SPI_InitStructure.SPI_CRCPolynomial = 7;
  SPI_Init(SPI1, &SPI_InitStructure);

  /* SPI2 Config -------------------------------------------------------------*/
  SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
  SPI_Init(SPI2, &SPI_InitStructure);

  /* Enable SPI1 */
  SPI_Cmd(SPI1, ENABLE);
  /* Enable SPI2 */
  SPI_Cmd(SPI2, ENABLE);

  /* Transfer procedure */
  while (TxIdx < BufferSize)
  {
    /* Wait for SPI1 Tx buffer empty */
    while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);
    /* Send SPI2 data */
    SPI_I2S_SendData(SPI2, SPI2_Buffer_Tx[TxIdx]);
    /* Send SPI1 data */
    SPI_I2S_SendData(SPI1, SPI1_Buffer_Tx[TxIdx++]);
    /* Wait for SPI2 data reception */
    while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET);
    /* Read SPI2 received data */
    SPI2_Buffer_Rx[RxIdx] = SPI_I2S_ReceiveData(SPI2);
    /* Wait for SPI1 data reception */
    while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
    /* Read SPI1 received data */
    SPI1_Buffer_Rx[RxIdx++] = SPI_I2S_ReceiveData(SPI1);
  }

  /* Check the corectness of written dada */
  TransferStatus1 = Buffercmp(SPI2_Buffer_Rx, SPI1_Buffer_Tx, BufferSize);
  TransferStatus2 = Buffercmp(SPI1_Buffer_Rx, SPI2_Buffer_Tx, BufferSize);
  /* TransferStatus1, TransferStatus2 = PASSED, if the transmitted and received data
     are equal */
  /* TransferStatus1, TransferStatus2 = FAILED, if the transmitted and received data
     are different */

  /* 2nd phase: SPI1 Slave and SPI2 Master */
  /* SPI1 Re-configuration ---------------------------------------------------*/
  SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
  SPI_Init(SPI1, &SPI_InitStructure);

  /* SPI2 Re-configuration ---------------------------------------------------*/
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_Init(SPI2, &SPI_InitStructure);

  /* Reset TxIdx, RxIdx indexes and receive tables values */
  TxIdx = 0;
  RxIdx = 0;
  for (k = 0; k < BufferSize; k++)  SPI2_Buffer_Rx[k] = 0;
  for (k = 0; k < BufferSize; k++)  SPI1_Buffer_Rx[k] = 0;

  /* Transfer procedure */
  while (TxIdx < BufferSize)
  {
    /* Wait for SPI2 Tx buffer empty */
    while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
    /* Send SPI1 data */
    SPI_I2S_SendData(SPI1, SPI1_Buffer_Tx[TxIdx]);
    /* Send SPI2 data */
    SPI_I2S_SendData(SPI2, SPI2_Buffer_Tx[TxIdx++]);
    /* Wait for SPI1 data reception */
    while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
    /* Read SPI1 received data */
    SPI1_Buffer_Rx[RxIdx] = SPI_I2S_ReceiveData(SPI1);
    /* Wait for SPI2 data reception */
    while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET);
    /* Read SPI2 received data */
    SPI2_Buffer_Rx[RxIdx++] = SPI_I2S_ReceiveData(SPI2);
  }

  /* Check the corectness of written dada */
  TransferStatus3 = Buffercmp(SPI2_Buffer_Rx, SPI1_Buffer_Tx, BufferSize);
  TransferStatus4 = Buffercmp(SPI1_Buffer_Rx, SPI2_Buffer_Tx, BufferSize);
  /* TransferStatus3, TransferStatus4 = PASSED, if the transmitted and received data
     are equal */
  /* TransferStatus3, TransferStatus4 = FAILED, if the transmitted and received data
     are different */

  while (1)
  {}
}
Esempio n. 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_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();

  /* NVIC configuration */
  NVIC_Configuration();

  /* GPIO configuration */
  GPIO_Configuration();

  /* Configure the CEC peripheral */
  CEC_InitStructure.CEC_BitTimingMode = CEC_BitTimingStdMode;
  CEC_InitStructure.CEC_BitPeriodMode = CEC_BitPeriodStdMode;
  CEC_Init(&CEC_InitStructure);

  /* Set Prescaler value for APB1 clock PCLK1 = 24MHz */ 
  CEC_SetPrescaler(0x4AF);

  /* Set the CEC initiator address */
  CEC_OwnAddressConfig(MY_DEVICE_ADDRESS);
  
  /* Activate CEC interrupts associated to the set of RBTF,RERR, TBTF, TERR flags */
  CEC_ITConfig(ENABLE);

  /* Enable CEC */
  CEC_Cmd(ENABLE);

  /* If a frame has been received */
  while(ReceivedFrame == 0)
  {
  }
  
  /* Check the received data with the send ones */
  TransferStatus = Buffercmp(TransmitBuffer, ReceiveBuffer, ByteNumber);
  /* TransferStatus = PASSED, if the data transmitted from CEC Device1 and  
     received by CEC Device2 are the same */
  /* TransferStatus = FAILED, if the data transmitted from CEC Device1 and 
     received by CEC Device2 are different */
 
  if (TransferStatus == PASSED)
  { 
    /* OK */
    /* Turn on LED1 */
    STM_EVAL_LEDOn(LED1);
  }
  else
  { 
    /* KO */
    /* Turn on LED2 */
    STM_EVAL_LEDOn(LED2);
  }
  while(1)
  {
  }
}
Esempio n. 25
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
     */     
       
  /* System clocks configuration ---------------------------------------------*/
  RCC_Configuration();

  /* NVIC configuration ------------------------------------------------------*/
  NVIC_Configuration();

  /* GPIO configuration ------------------------------------------------------*/
  GPIO_Configuration();

  /* DMA1 channel1 configuration ----------------------------------------------*/
  DMA_DeInit(DMA1_Channel1);
  DMA_InitStructure.DMA_PeripheralBaseAddr = ADC1_DR_Address;
  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&ADC1ConvertedValue;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 1;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA1_Channel1, &DMA_InitStructure);  
  /* Enable DMA1 channel1 */
  DMA_Cmd(DMA1_Channel1, ENABLE);

  /* DMA2 channel5 configuration ----------------------------------------------*/
  DMA_DeInit(DMA2_Channel5);
  DMA_InitStructure.DMA_PeripheralBaseAddr = ADC3_DR_Address;
  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&ADC3ConvertedValue;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 1;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA2_Channel5, &DMA_InitStructure);  
  /* Enable DMA2 channel5 */
  DMA_Cmd(DMA2_Channel5, ENABLE);

  /* ADC1 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = DISABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 1;
  ADC_Init(ADC1, &ADC_InitStructure);
  /* ADC1 regular channels configuration */ 
  ADC_RegularChannelConfig(ADC1, ADC_Channel_14, 1, ADC_SampleTime_28Cycles5);    
  /* Enable ADC1 DMA */
  ADC_DMACmd(ADC1, ENABLE);

  /* ADC2 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = DISABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 1;
  ADC_Init(ADC2, &ADC_InitStructure);
  /* ADC2 regular channels configuration */ 
  ADC_RegularChannelConfig(ADC2, ADC_Channel_13, 1, ADC_SampleTime_28Cycles5);
  /* Enable ADC2 EOC interupt */
  ADC_ITConfig(ADC2, ADC_IT_EOC, ENABLE);

  /* ADC3 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = DISABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 1;
  ADC_Init(ADC3, &ADC_InitStructure);
  /* ADC3 regular channel14 configuration */ 
  ADC_RegularChannelConfig(ADC3, ADC_Channel_12, 1, ADC_SampleTime_28Cycles5);
  /* Enable ADC3 DMA */
  ADC_DMACmd(ADC3, ENABLE);

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

  /* Enable ADC1 reset calibaration register */   
  ADC_ResetCalibration(ADC1);
  /* Check the end of ADC1 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC1));

  /* Start ADC1 calibaration */
  ADC_StartCalibration(ADC1);
  /* Check the end of ADC1 calibration */
  while(ADC_GetCalibrationStatus(ADC1));

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

  /* Enable ADC2 reset calibaration register */   
  ADC_ResetCalibration(ADC2);
  /* Check the end of ADC2 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC2));

  /* Start ADC2 calibaration */
  ADC_StartCalibration(ADC2);
  /* Check the end of ADC2 calibration */
  while(ADC_GetCalibrationStatus(ADC2));

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

  /* Enable ADC3 reset calibaration register */   
  ADC_ResetCalibration(ADC3);
  /* Check the end of ADC3 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC3));

  /* Start ADC3 calibaration */
  ADC_StartCalibration(ADC3);
  /* Check the end of ADC3 calibration */
  while(ADC_GetCalibrationStatus(ADC3));

  /* Start ADC1 Software Conversion */ 
  ADC_SoftwareStartConvCmd(ADC1, ENABLE);
  /* Start ADC2 Software Conversion */ 
  ADC_SoftwareStartConvCmd(ADC2, ENABLE);
  /* Start ADC3 Software Conversion */ 
  ADC_SoftwareStartConvCmd(ADC3, ENABLE);

  while (1)
  {
  }
}
Esempio n. 26
0
File: main.c Progetto: kenziD/ANO
int main(void)
{
    float q[4];
    u8 tmp_buf[32] = {0};
    float test = 0;
    static u8 led_on = 0;

    RCC_HSE_Configuration();
    SysTick_Init();
    NVIC_Configuration();
    USART1_Config(115200);
    LED_Init();
    LED3_Flash(2,100);
    ANO_TC_I2C2_INIT(0xA6, 400000, 1, 1, 3, 3);
    //硬实时
    Tim3_Init(500);//0.005s
    TIM2_Init(999, 0);

    Mpu6050init();
    MOT_GPIO_init();
    MOT_PWM_init();
    Set_PWM(0, 0, 0, 0);
    NRF24L01_Init();
    while (NRF24L01_Check())
    {
        LED2_Flash(2,500000);
    }

    //TX mode
    NRF24L01_Mode_Config(4);
    PID_Init();
    ADC1_Init();
    while (1)
    {
        if (getMpu6050Data == 1)
        {
            //0.01ms?
            Read_Mpu6050();
            Mpu6050_Analyze();
            getMpu6050Data = 0;
        }
        if (calculateAngle == 1)//2ms period
        {
            //0.2ms T
            //LED2_ON;

            //100us
            IMU_Quateration_Update((float)fGYRO_X , (float)fGYRO_Y , (float)fGYRO_Z , (float)fACCEL_X, (float)fACCEL_Y, (float)fACCEL_Z,ypr);
            //LED2_OFF;
            calculateAngle = 0;
        }
        if (sendData == 1)//2ms period
        {
            if(led_on)
            {
                LED2_OFF;
                led_on = 0;
            }
            else
            {
                LED2_ON;
                led_on = 1;
            }

            if (NRF24L01_RxPacket(tmp_buf) == 0)
            {
                //10us
                Rc_Data_Analyze(tmp_buf,&Rc_Data);
            }
            //if wait for the IRQ it need 9ms
            //if not wait for IRQ it runtime need 100us*1.2=0.12ms

            sendSenser((int16_t)fACCEL_X, (int16_t)fACCEL_Y, (int16_t)fACCEL_Z, (int16_t)fGYRO_X, (int16_t) fGYRO_Y, (int16_t)fGYRO_Z, (int16_t)(ypr[0] * 100), (signed short int)(ypr[1] * 100));
            send_wave(32);

            //0.14ms run time
            sendPwmVoltage(&Rc_Data,(uint16_t)(motor0 / 1000.0 * 100), (uint16_t)(motor1 / 1000.0 * 100), (uint16_t)(motor2 / 1000.0 * 100), (uint16_t)(motor3 / 1000.0 * 100));//0.00003974s
            send_wave(32);

            sendData = 0;
        }
        //moveFilterAccData(fACCEL_X, fACCEL_Y, fACCEL_Z, AngleOut);

        if (!strcmp(Rc_Data.status, "stop"))
        {
            Set_PWM(0, 0, 0, 0);
        }
        else if (!strcmp(Rc_Data.status, "start"))
        {
            //LED2_ON;
            expRoll = Rc_Data.roll;
            expPitch = Rc_Data.pitch;
            expThro = Rc_Data.throttle;
            surRoll = ypr[2];
            surPitch = ypr[1];
            PID_Set();
            Set_PWM(motor0, motor1, motor2, motor3);
            //LED2_OFF;
        }
        ////Uart1_Send_PID(320,PID_ROLL.KI,PID_ROLL.KD,1,0,0);
        ////send_wave(32);
        // if (STA == 1)
        // {
        // 	receive_Data();
        // 	STA = 0;
        // 	p = 0;
        // }
    }
}
Esempio n. 27
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
     */     
       
  /* System Clocks Configuration */
  RCC_Configuration();

  /* NVIC Configuration */
  NVIC_Configuration();

  /* GPIO Configuration */
  GPIO_Configuration();

  /* ---------------------------------------------------------------
    TIM2 Configuration: Output Compare Timing Mode:
    TIM2 counter clock at 6 MHz
    CC1 update rate = TIM2 counter clock / CCR1_Val = 146.48 Hz
    CC2 update rate = TIM2 counter clock / CCR2_Val = 219.7 Hz
    CC3 update rate = TIM2 counter clock / CCR3_Val = 439.4 Hz
    CC4 update rate = TIM2 counter clock / CCR4_Val = 878.9 Hz
  --------------------------------------------------------------- */

  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) (SystemCoreClock / 12000000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  /* Prescaler configuration */
  TIM_PrescalerConfig(TIM2, PrescalerValue, TIM_PSCReloadMode_Immediate);

  /* Output Compare Timing Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM2, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM2, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM2, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* TIM IT enable */
  TIM_ITConfig(TIM2, TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE);

  /* TIM2 enable counter */
  TIM_Cmd(TIM2, ENABLE);

  while (1);
}
Esempio n. 28
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System Clocks Configuration */
  RCC_Configuration();   

  /* NVIC Configuration */
  NVIC_Configuration();

  /* FSMC for SRAM and SRAM pins configuration */
  FSMC_SRAM_Init();

  /* Write to FSMC -----------------------------------------------------------*/
  /* DMA2 channel5 configuration */
  DMA_DeInit(DMA2_Channel5);
  DMA_InitStructure.DMA_PeripheralBaseAddr = (u32)SRC_Const_Buffer;
  DMA_InitStructure.DMA_MemoryBaseAddr = (u32)Bank1_SRAM3_ADDR;    
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 32;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Enable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Word;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Word;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Enable;
  DMA_Init(DMA2_Channel5, &DMA_InitStructure);

  /* Enable DMA2 channel5 */
  DMA_Cmd(DMA2_Channel5, ENABLE);

  /* Check if DMA2 channel5 transfer is finished */
  while(!DMA_GetFlagStatus(DMA2_FLAG_TC5));

  /* Clear DMA2 channel5 transfer complete flag bit */
  DMA_ClearFlag(DMA2_FLAG_TC5);

  /* Read from FSMC ----------------------------------------------------------*/
  /* Destination buffer initialization */ 
  for(Idx=0; Idx<128; Idx++) DST_Buffer[Idx]=0;

  /* DMA1 channel3 configuration */
  DMA_DeInit(DMA1_Channel3);
  DMA_InitStructure.DMA_PeripheralBaseAddr = (u32)Bank1_SRAM3_ADDR;  
  DMA_InitStructure.DMA_MemoryBaseAddr = (u32)DST_Buffer;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 128;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Enable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Enable;
  DMA_Init(DMA1_Channel3, &DMA_InitStructure);

  /* Enable DMA1 channel3 */
  DMA_Cmd(DMA1_Channel3, ENABLE);

  /* Check if DMA1 channel3 transfer is finished */
  while(!DMA_GetFlagStatus(DMA1_FLAG_TC3));

  /* Clear DMA1 channel3 transfer complete flag bit */
  DMA_ClearFlag(DMA1_FLAG_TC3);

  /* Check if the transmitted and received data are equal */
  TransferStatus = Buffercmp(SRC_Const_Buffer, (u32*)DST_Buffer, BufferSize);
  /* TransferStatus = PASSED, if the transmitted and received data 
     are the same */
  /* TransferStatus = FAILED, if the transmitted and received data 
     are different */

  while (1)								
  {
  }
}
Esempio n. 29
0
/*********************************************************************
  * @brief  Initializes the UART peripheral.
	* @param  None
  * @retval None   
	* @date   20141205
***********************************************************************/
void UARTx_Init(void)
{
	UART_GPIO_Init();
	UART_Config();
	NVIC_Configuration();
}
Esempio n. 30
0
int main(void)
 {
//	u8 key;
//	u16 i=0;
	u16 adc_91000,adc_91200,reg_read_data=0,reg_write_data=0;
	float LMP91000_VOUT,LMP91200_VOUT,Temp_Integer,Temp_Decimal;
 	short temp;
	u8 read_val[5] = {0xff};
    u8 status = TI_LMP91000_NOT_READY; 
 	SystemInit();
	delay_init(72);	     //延时初始化
	NVIC_Configuration();
 	uart_init(9600);
 	LED_Init();
 	KEY_Init();
	Adc_Init();
	IIC_Init();			//IIC初始化
	LMP91200_Init();    //初始化PH
	delay_ms(500);
	printf("\nHello XXL");



/************************************************************
* 溶氧电极初始化及数据采集
************************************************************/	
	LMP91000_ENABLE();
																				 // enable LM
    while (status == TI_LMP91000_NOT_READY)                                      // wait while device is not ready
    	status = LMP91000_ReadOneByte(TI_LMP91000_STATUS_REG);                   // Read device ready status

	read_val[0] = LMP91000_ReadOneByte(TI_LMP91000_LOCK_REG);                     // Read from lock register default value 0x01
	read_val[1] = LMP91000_ReadOneByte(TI_LMP91000_TIACN_REG);                    // Read TIA control register default value 0x03
	read_val[2] = LMP91000_ReadOneByte(TI_LMP91000_REFCN_REG);                    // Read Reference control register default value 0x20
	read_val[3] = LMP91000_ReadOneByte(TI_LMP91000_MODECN_REG);                   // Read Mode control register default value 0x00
  
	LMP91000_WriteOneByte(TI_LMP91000_LOCK_REG, TI_LMP91000_WRITE_UNLOCK);        // unlock the registers for write
 
	LMP91000_WriteOneByte(TI_LMP91000_TIACN_REG, TIACN_NEW_VALUE);                // Modify TIA control register
	LMP91000_WriteOneByte(TI_LMP91000_REFCN_REG, REFCN_NEW_VALUE);                // Modify REF control register
	LMP91000_WriteOneByte(TI_LMP91000_MODECN_REG, MODECN_NEW_VALUE);              // Modify MODE control register

	read_val[1] = LMP91000_ReadOneByte(TI_LMP91000_TIACN_REG);                    // Read to confirm register is modified
	read_val[2] = LMP91000_ReadOneByte(TI_LMP91000_REFCN_REG);                    // Read to confirm register is modified
	read_val[3] = LMP91000_ReadOneByte(TI_LMP91000_MODECN_REG);                   // Read to confirm register is modified
	read_val[4] = LMP91000_ReadOneByte(TI_LMP91000_STATUS_REG);  
// test if write/read values match
	if (read_val[1] == TIACN_NEW_VALUE)
	{
//    while (1)                                                                  // no error: blink LED continuously
//    {
        delay_ms(500);
        LED1=!LED1;//绿灯闪烁
//    } 
	} else
	{
		delay_ms(500);
		LED0=!LED0;//红灯闪烁                            // error
	}   

// 获取LMP91000输出电压
//    while(1)
//    {	
       adc_91000=Get_Adc(ADC_Channel_8);
	   LMP91000_VOUT=(float)adc_91000*(3.3/4096);
	   LMP91000_VOUT=LMP91000_VOUT;
	   printf("\n\nDO=%fv ",LMP91000_VOUT);

	   temp=DS18B20_Get_Temp();
	   if(temp<0)
	   {
			temp=-temp;
	   }
	   Temp_Integer=temp/10;
	   Temp_Integer=Temp_Integer;	   //整数
	   Temp_Decimal=temp%10;
	   Temp_Decimal=Temp_Decimal;	   //小数
       printf(" Temp=%f.%fc " __TIME__ "",Temp_Integer,Temp_Decimal);

   	   delay_ms(1000);
//    }
	LMP91000_WriteOneByte(TI_LMP91000_LOCK_REG, TI_LMP91000_WRITE_LOCK);          // lock the registers  
	LMP91000_DISABLE();

/************************************************************
* PH电极初始化及数据采集,无论在空气,碱水,酸水中vout总是1.420~1.429,可能电极坏掉
************************************************************/	

  Clr_LMP91200_CSN;
  	
  reg_write_data = TI_LMP91200_CONFIG_REG_TEST_VALUE;                               // value to write 
  reg_read_data = SPIx_ReadWriteByte(reg_write_data);                     // Write to config register, read old value  
  reg_read_data = SPIx_ReadWriteByte(reg_write_data);                     // Write again to read previous update
  reg_read_data = SPIx_ReadWriteByte(reg_write_data);                     // Write again to read previous update,if not read this time,bit-15 will be wrong
  
//  Set_LMP91200_CSN;
while(1)
  // test if write/read values match
{

    if (reg_write_data == reg_read_data)
    {
	    adc_91200=Get_Adc(ADC_Channel_9);
	    LMP91200_VOUT=(float)adc_91200*(3.3/4096);
	    LMP91200_VOUT=LMP91200_VOUT;
		LED1=!LED1;								   //正确则绿灯亮
	    delay_ms(500);	
    }
    else
    {
	    LED0=!LED0;								   //错误则黄灯亮
	    delay_ms(300);
    }
}

/************************************************************
* 温度传感器初始化及数据采集
************************************************************/	

	while(DS18B20_Init())//初始化DS18B20,兼检测18B20
	{
		delay_ms(600);
//		error_report();//DS18B20 未连接
	}

	while(1)
	{
	 	temp=DS18B20_Get_Temp();
		if(temp<0)
		{
			temp=-temp;
		}
		Temp_Integer=temp/10;
		Temp_Integer=Temp_Integer;	   //整数
		Temp_Decimal=temp%10;
		Temp_Decimal=Temp_Decimal;	   //小数
		delay_ms(500);
		LED1=!LED1;//DS1闪烁
	}





/************************************************************
* 按键扫描
************************************************************/	


	  
#if 0
	while(1)
	{
		key=KEY_Scan();
		if(key==1)//KEY0按下,写入24C02
		{
           ;
		}
		if(key==3)//KEY_UP按下,读取字符串并显示
		{
           ;
		}
		i++;
		delay_ms(10);

	}
#endif
 }