Example #1
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
    /* STM32F0xx HAL library initialization:
         - Configure the Flash prefetch
         - Systick timer is configured by default as source of time base, but user
           can eventually implement his proper time base source (a general purpose
           timer for example or other time source), keeping in mind that Time base
           duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
           handled in milliseconds basis.
         - Low Level Initialization
       */
    HAL_Init();

    /* Initialize LEDs */
    BSP_LED_Init(LED1);
    BSP_LED_Init(LED2);
    BSP_LED_Init(LED3);
    BSP_LED_Init(LED4);

    /* Configure the system clock to have a system clock = 48 MHz */
    SystemClock_Config();

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

    /* SysTick Timer is configured by default to generate an interrupt each 1 msec.
       ---------------------------------------------------------------------------
      1. The configuration is done using HAL_SYSTICK_Config() located in HAL_Init().

      2. The HAL_SYSTICK_Config() function configure:
         - The SysTick Reload register with value passed as function parameter.
         - Configure the SysTick IRQ priority to the lowest value.
         - Reset the SysTick Counter register.
         - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
         - Enable the SysTick Interrupt.
         - Start the SysTick Counter.

      3. The SysTick time base 1 msec is computed using the following formula:

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

         - Reload Value is the parameter to be passed for SysTick_Config() function
         - Reload Value should not exceed 0xFFFFFF

      @note: Caution, the SysTick time base 1 msec must not be changed due to use
             of these time base by HAL driver.
    */

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

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

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

        /* Insert 100 ms delay */
        HAL_Delay(100);
    }
}
Example #2
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure LED2, LED2 and LED2 */
  BSP_LED_Init(LED2);
  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /*##-1- Configure the SPI peripheral #######################################*/
  /* Set the SPI parameters */
  SpiHandle.Instance               = SPIx;

  SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
  SpiHandle.Init.Direction         = SPI_DIRECTION_2LINES;
  SpiHandle.Init.CLKPhase          = SPI_PHASE_1EDGE;
  SpiHandle.Init.CLKPolarity       = SPI_POLARITY_LOW;
  SpiHandle.Init.CRCCalculation    = SPI_CRCCALCULATION_DISABLE;
  SpiHandle.Init.CRCPolynomial     = 7;
  SpiHandle.Init.DataSize          = SPI_DATASIZE_8BIT;
  SpiHandle.Init.FirstBit          = SPI_FIRSTBIT_MSB;
  SpiHandle.Init.NSS               = SPI_NSS_SOFT;
  SpiHandle.Init.TIMode            = SPI_TIMODE_DISABLE;
  SpiHandle.Init.NSSPMode          = SPI_NSS_PULSE_DISABLE;
  SpiHandle.Init.CRCLength         = SPI_CRC_LENGTH_8BIT;

#ifdef MASTER_BOARD
  SpiHandle.Init.Mode = SPI_MODE_MASTER;
#else
  SpiHandle.Init.Mode = SPI_MODE_SLAVE;
#endif /* MASTER_BOARD */

  if(HAL_SPI_Init(&SpiHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

#ifdef MASTER_BOARD
  /* Configure push button */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO);
  /* Wait for Button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_USER) != GPIO_PIN_RESET)
  {
    BSP_LED_Toggle(LED2);
    HAL_Delay(100);
  }
  BSP_LED_Off(LED2);
#endif /* MASTER_BOARD */

  /*##-2- Start the Full Duplex Communication process ########################*/  
  /* While the SPI in TransmitReceive process, user can transmit data through 
     "aTxBuffer" buffer & receive data through "aRxBuffer" */
  /* Timeout is set to 5S */
  
  switch(HAL_SPI_TransmitReceive(&SpiHandle, (uint8_t*)aTxBuffer, (uint8_t *)aRxBuffer, BUFFERSIZE, 5000))
  {
    case HAL_OK:
      /* Communication is completed ___________________________________________ */
      /* Compare the sent and received buffers */
      if (Buffercmp((uint8_t *)aTxBuffer, (uint8_t *)aRxBuffer, BUFFERSIZE))
      {
        /* Transfer error in transmission process */
        Error_Handler();
      }
      /* Turn LED2 on: Transfer in transmission/Reception process is correct */
      BSP_LED_On(LED2);
      break;

    case HAL_TIMEOUT:
      /* An Error Occur ______________________________________________________ */
    case HAL_ERROR:
      /* Call Timeout Handler */
      Error_Handler();
      break;
    default:
      break;
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #3
0
void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *I2cHandle)
{
  /* Toggle LED2: Transfer in reception process is correct */
  BSP_LED_Toggle(LED2);
}
Example #4
0
File: main.c Project: z80/stm32f429
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{

  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure LED3 and LED4 */
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED4);
  
  /* Configure the system clock to 180 MHz */
  SystemClock_Config();

  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART1 configured as follow:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance          = USARTx;
  
  UartHandle.Init.BaudRate     = 9600;
  UartHandle.Init.WordLength   = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits     = UART_STOPBITS_1;
  UartHandle.Init.Parity       = UART_PARITY_NONE;
  UartHandle.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode         = UART_MODE_TX_RX;
  UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
    
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef TRANSMITTER_BOARD

  /* Configure USER Button */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);
  /* Wait for USER Button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_KEY) == RESET)
  {
  }
  
  /* The board sends the message and expects to receive it back */
  
  /*##-2- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-3- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }
  
  /* Reset transmission flag */
  UartReady = RESET;

  /* Turn LED3 Off */
  BSP_LED_Off(LED3);
  
  /*##-4- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

#else
  
  /* The board receives the message and sends it back */

  /*##-2- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-3- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;
  
  /* Turn LED3 Off */
  BSP_LED_Off(LED3);
  
  /*##-4- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
#endif /* TRANSMITTER_BOARD */
  
  /*##-5- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }
  
  /* Reset transmission flag */
  UartReady = RESET;

  /*##-6- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
  {
    Error_Handler();
  }

  /* Infinite loop */
  while (1)
  {
    /* Toggle LED3 */
    BSP_LED_Toggle(LED3);
    
    /* Wait for 40ms */
    HAL_Delay(40);
  }
}
Example #5
0
/**
  * @brief  COMP1 interrupt callback
  * @param  hcomp : COMP handle 
  * @retval none
  */
void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp)
{
  /* Turn On LED1 */
  BSP_LED_Toggle(LED1);
}
Example #6
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 72 MHz */
  SystemClock_Config();

  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);
  
  /*##-1- Configure the I2C peripheral ######################################*/
  I2cHandle.Instance             = I2Cx;

  I2cHandle.Init.Timing          = I2C_TIMING;
  I2cHandle.Init.OwnAddress1     = I2C_ADDRESS;
  I2cHandle.Init.AddressingMode  = I2C_ADDRESSINGMODE_7BIT;
  I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  I2cHandle.Init.OwnAddress2     = 0xFF;
  I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  I2cHandle.Init.NoStretchMode   = I2C_NOSTRETCH_DISABLE;  
  
  if(HAL_I2C_Init(&I2cHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /* Enable the Analog I2C Filter */
  HAL_I2CEx_ConfigAnalogFilter(&I2cHandle,I2C_ANALOGFILTER_ENABLE);

#ifdef MASTER_BOARD
  
  /* Configure Key Button*/
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);

  /* Wait for Key Button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_KEY) != GPIO_PIN_RESET)
  {
  }

  /* Wait for Key Button release before starting the Communication */
  while (BSP_PB_GetState(BUTTON_KEY) != GPIO_PIN_SET)
  {
  }

  while(1)
  {
    /* Initialize number of data variables */
    hTxNumData = TXBUFFERSIZE;
    hRxNumData = RXBUFFERSIZE;

    /* Update bTransferRequest to send buffer write request for Slave */
    bTransferRequest = MASTER_REQ_WRITE;

    /*##-2- Master sends write request for slave #############################*/
    while(HAL_I2C_Master_Transmit_IT(&I2cHandle, (uint16_t)I2C_ADDRESS, (uint8_t*)&bTransferRequest, 1)!= HAL_OK)
    {
      /* Error_Handler() function is called when Timout error occurs.
         When Acknowledge failure ocucurs (Slave don't acknowledge it's address)
         Master restarts communication */
      if (HAL_I2C_GetError(&I2cHandle) != HAL_I2C_ERROR_AF)
      {
        Error_Handler();
      }
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }

    /*##-3- Master sends number of data to be written ########################*/
    while(HAL_I2C_Master_Transmit_IT(&I2cHandle, (uint16_t)I2C_ADDRESS, (uint8_t*)&hTxNumData, 2)!= HAL_OK)
    {
      /* Error_Handler() function is called when Timout error occurs.
         When Acknowledge failure ocucurs (Slave don't acknowledge it's address)
         Master restarts communication */
      if (HAL_I2C_GetError(&I2cHandle) != HAL_I2C_ERROR_AF)
      {
        Error_Handler();
      }
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }

    /*##-4- Master sends aTxBuffer to slave ##################################*/
    while(HAL_I2C_Master_Transmit_IT(&I2cHandle, (uint16_t)I2C_ADDRESS, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
    {
      /* Error_Handler() function is called when Timout error occurs.
         When Acknowledge failure ocucurs (Slave don't acknowledge it's address)
         Master restarts communication */
      if (HAL_I2C_GetError(&I2cHandle) != HAL_I2C_ERROR_AF)
      {
        Error_Handler();
      }
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }

    /* Update bTransferRequest to send buffer read request for Slave */
    bTransferRequest = MASTER_REQ_READ;

    /*##-5- Master sends read request for slave ##############################*/
    while(HAL_I2C_Master_Transmit_IT(&I2cHandle, (uint16_t)I2C_ADDRESS, (uint8_t*)&bTransferRequest, 1)!= HAL_OK)
    {
      /* Error_Handler() function is called when Timout error occurs.
         When Acknowledge failure ocucurs (Slave don't acknowledge it's address)
         Master restarts communication */
      if (HAL_I2C_GetError(&I2cHandle) != HAL_I2C_ERROR_AF)
      {
        Error_Handler();
      }
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }

    /*##-6- Master sends number of data to be read ###########################*/
    while(HAL_I2C_Master_Transmit_IT(&I2cHandle, (uint16_t)I2C_ADDRESS, (uint8_t*)&hRxNumData, 2)!= HAL_OK)
    {
      /* Error_Handler() function is called when Timout error occurs.
         When Acknowledge failure ocucurs (Slave don't acknowledge it's address)
         Master restarts communication */
      if (HAL_I2C_GetError(&I2cHandle) != HAL_I2C_ERROR_AF)
      {
        Error_Handler();
      }
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }

    /*##-7- Master receives aRxBuffer from slave #############################*/
    while(HAL_I2C_Master_Receive_IT(&I2cHandle, (uint16_t)I2C_ADDRESS, (uint8_t*)aRxBuffer, RXBUFFERSIZE)!= HAL_OK)
    {
      /* Error_Handler() function is called when Timout error occurs.
         When Acknowledge failure ocucurs (Slave don't acknowledge it's address)
         Master restarts communication */
      if (HAL_I2C_GetError(&I2cHandle) != HAL_I2C_ERROR_AF)
      {
        Error_Handler();
      }
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }
    /* Check correctness of received buffer ##################################*/
    if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,hRxNumData))
    {
      /* Processing Error */
      Error_Handler();
    }

    /* Flush Rx buffers */
    Flush_Buffer((uint8_t*)aRxBuffer,RXBUFFERSIZE);

    /* Toggle LED1 */
    BSP_LED_Toggle(LED1);

    /* This delay permit the key to see LED3 toggling */
    HAL_Delay(25);
  }
#else
  while(1)
  {
    /* Initialize number of data variables */
    hTxNumData = 0;
    hRxNumData = 0;

    /*##-2- Slave receive request from master ################################*/
    while(HAL_I2C_Slave_Receive_IT(&I2cHandle, (uint8_t*)&bTransferRequest, 1)!= HAL_OK)
    {
    }

    /*  Before starting a new communication transfer, you need to check the current
    state of the peripheral; if it’s busy you need to wait for the end of current
    transfer before starting a new one.
    For simplicity reasons, this example is just waiting till the end of the
    transfer, but application may perform other tasks while transfer operation
    is ongoing. */
    while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
    {
    }

    /* If master request write operation #####################################*/
    if (bTransferRequest == MASTER_REQ_WRITE)
    {
      /*##-3- Slave receive number of data to be read ########################*/
      while(HAL_I2C_Slave_Receive_IT(&I2cHandle, (uint8_t*)&hRxNumData, 2)!= HAL_OK);

      /*  Before starting a new communication transfer, you need to check the current
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */
      while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
      {
      }

      /*##-4- Slave receives aRxBuffer from master ###########################*/
      while(HAL_I2C_Slave_Receive_IT(&I2cHandle, (uint8_t*)aRxBuffer, hRxNumData)!= HAL_OK);

      /*  Before starting a new communication transfer, you need to check the current
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */
      while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
      {
      }

      /* Check correctness of received buffer ################################*/
      if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,hRxNumData))
      {
        /* Processing Error */
        Error_Handler();
      }

      /* Flush Rx buffers */
      Flush_Buffer((uint8_t*)aRxBuffer,RXBUFFERSIZE);

      /* Toggle LED1 */
      BSP_LED_Toggle(LED1);
    }
    /* If master request write operation #####################################*/
    else
    {
      /*##-3- Slave receive number of data to be written #####################*/
      while(HAL_I2C_Slave_Receive_IT(&I2cHandle, (uint8_t*)&hTxNumData, 2)!= HAL_OK);

      /*  Before starting a new communication transfer, you need to check the current
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */
      while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
      {
      }

      /*##-4- Slave transmit aTxBuffer to master #############################*/
      while(HAL_I2C_Slave_Transmit_IT(&I2cHandle, (uint8_t*)aTxBuffer, RXBUFFERSIZE)!= HAL_OK);

      /*  Before starting a new communication transfer, you need to check the current
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */
      while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY)
      {
      }
    }
  }
#endif /* MASTER_BOARD */
}
Example #7
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
    /* STM32F0xx HAL library initialization:
         - Configure the Flash prefetch
         - Systick timer is configured by default as source of time base, but user
           can eventually implement his proper time base source (a general purpose
           timer for example or other time source), keeping in mind that Time base
           duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
           handled in milliseconds basis.
         - Low Level Initialization
       */
    HAL_Init();

    /* Configure LED3 and LED4 and User push-button */
    BSP_LED_Init(LED3);
    BSP_LED_Init(LED4);
    BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);

    /* Configure the system clock to 48 MHz */
    SystemClock_Config();


    /*##-1- Check if the system has resumed from WWDG reset ####################*/
    if (__HAL_RCC_GET_FLAG(RCC_FLAG_WWDGRST) != RESET)
    {
        /* WWDGRST flag set: Turn LED3 on */
        BSP_LED_On(LED3);

        /* Clear reset flags */
        __HAL_RCC_CLEAR_RESET_FLAGS();
    }
    else
    {
        /* WWDGRST flag is not set: Turn LED3 off */
        BSP_LED_Off(LED3);
    }

    /*##-2- Configure the WWDG peripheral ######################################*/
    /* WWDG clock counter = (PCLK1 (48MHz)/4096)/8) = 1464.8 Hz (~683 us)
       WWDG Window value = 80 means that the WWDG counter should be refreshed only
       when the counter is below 80 (and greater than 64 (63+1)) otherwise a reset will
       be generated.
       WWDG Counter value = 127, WWDG timeout = ~683 us * 64 = 43.7 ms */
    WwdgHandle.Instance = WWDG;

    WwdgHandle.Init.Prescaler = WWDG_PRESCALER_8;
    WwdgHandle.Init.Window    = 80;
    WwdgHandle.Init.Counter   = 127;

    if (HAL_WWDG_Init(&WwdgHandle) != HAL_OK)
    {
        /* Initialization Error */
        Error_Handler();
    }

    /*##-3- Start the WWDG #####################################################*/
    if (HAL_WWDG_Start(&WwdgHandle) != HAL_OK)
    {
        Error_Handler();
    }

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

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

        /* Refresh WWDG: update counter value to 127, the refresh window is:
        refresh window between 32.1ms (~683 * (127-80)) and 43.7ms (~683 * 64) */

        if (HAL_WWDG_Refresh(&WwdgHandle, 127) != HAL_OK)
        {
            Error_Handler();
        }
    }
}
Example #8
0
/**
  * @brief  SSL client task.
  * @param  pvParameters not used
  * @retval None
  */
void ssl_client(void const * argument)
{
  int ret, len, server_fd;
  unsigned char buf[1024];
  ssl_context ssl;
  x509_cert cacert;
  
  memset( &ssl, 0, sizeof( ssl_context ) );
  memset( &cacert, 0, sizeof( x509_cert ) );
  
  /*
  *  Initialize certificates
  */
  printf( "  . Loading the CA root certificate ..." );
  
#if defined(POLARSSL_CERTS_C)
  ret = x509parse_crt( &cacert, (const unsigned char *) test_ca_crt,
                      strlen( test_ca_crt ) );
#else
  ret = 1;
  printf("POLARSSL_CERTS_C not defined.");
#endif
  
  if( ret < 0 )
  {
    printf( " failed\n  !  x509parse_crt returned -0x%x\n\n", -ret );
    goto exit;
  }
  
  printf( " ok (%d skipped)\n", ret );
  
  /* Start the connection */
  do
  {
    printf(( "\n\rSSL : Start the connection \n\r"));
    printf("\n\rConnecting to tcp/%s/ Port:%4d...", SSL_SERVER_NAME, SSL_SERVER_PORT); 
    
    /* Bint the connection to SSL server port */
    ret = net_connect(&server_fd, SSL_SERVER_NAME, SSL_SERVER_PORT);
    if(ret != 0)
    {
      /* Connection to SSL server failed */
      printf(" failed \n\r ! net_connect returned %d\n\r", -ret);
      
      /* Wait 500 ms until next retry */
      vTaskDelay(500);
    } 
  }while(ret!=0);
  
  printf( " ok\n\r" );
  
  /*
  * 2. Setup stuff
  */
  printf( "  . Setting up the SSL/TLS structure..." );
  
  if( ( ret = ssl_init( &ssl ) ) != 0 )
  {
    printf( " failed\n  ! ssl_init returned %d\n\n\r", ret );
    goto exit;
  }
  
  printf( " ok\n\r" );
  
  ssl_set_endpoint( &ssl, SSL_IS_CLIENT );
  ssl_set_authmode( &ssl, SSL_VERIFY_OPTIONAL );
  ssl_set_ca_chain( &ssl, &cacert, NULL, "PolarSSL Server 1" );
  
  ssl_set_rng( &ssl, RandVal , NULL );
  ssl_set_dbg( &ssl, my_debug, NULL);
  ssl_set_bio( &ssl, net_recv, &server_fd,
              net_send, &server_fd );
  
  /* Set max ssl version to TLS v1.1 because TLS v1.2 needs SHA-256 for HASH
     which is not supported by STM32F217xx Hardware*/
  ssl_set_max_version( &ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_2);
  
  /*
  * Handshake
  */
  printf( "  . Performing the SSL/TLS handshake..." );
  
  while( ( ret = ssl_handshake( &ssl ) ) != 0 )
  {
    if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
    {
      printf( " failed\n  ! ssl_handshake returned -0x%x\n\n\r", -ret );
      goto exit;
    }
  }
  
  printf( " ok\n\r" );
  
  /*
  * Verify the server certificate
  */
  printf( "\n\r  . Verifying peer X.509 certificate..." );
  
  if( ( ret = ssl_get_verify_result( &ssl ) ) != 0 )
  {
    printf( " failed\n\r" );
    
    if( ( ret & BADCERT_EXPIRED ) != 0 )
      printf( "  ! server certificate has expired\n" );
    
    if( ( ret & BADCERT_REVOKED ) != 0 )
      printf( "  ! server certificate has been revoked\n" );
    
    if( ( ret & BADCERT_CN_MISMATCH ) != 0 )
      printf( "  ! CN mismatch (expected CN=%s)\n", "PolarSSL Server 1" );
    
    if( ( ret & BADCERT_NOT_TRUSTED ) != 0 )
      printf( "  ! self-signed or not signed by a trusted CA\n" );
    
    printf( "\n\r" );
  }
  else
    printf( " ok\n\r" );
  
  /*
  * Write the GET request
  */
  printf( "  > Write to server:" );
  
  len = sprintf( (char *) buf, GET_REQUEST );
  
  while( ( ret = ssl_write( &ssl, buf, len ) ) <= 0 )
  {
    if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
    {
      printf( " failed\n  ! ssl_write returned %d\n\n\r", ret );
      goto exit;
    }
  }
  
  len = ret;
  printf( " %d bytes written\n\n\r%s", len, (char *) buf );
  
  /*
  * Read the HTTP response
  */
  printf( "  < Read from server:" );
  
  do
  {
    len = sizeof( buf ) - 1;
    memset( buf, 0, sizeof( buf ) );
    ret = ssl_read( &ssl, buf, len );
    
    if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
      continue;
    
    if( ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY )
      break;
    
    if( ret < 0 )
    {
      printf( "failed\n\r  ! ssl_read returned %d\n\n\r", ret );
      break;
    }
    
    if( ret == 0 )
    {
      printf( "\n\nEOF\n\n\r" );
      break;
    }
    
    len = ret;
    printf( " %d bytes read\n\n\r%s", len, (char *) buf );
  }
  while( 1 );
  
exit:

#ifdef POLARSSL_ERROR_C
  if( ret != 0 )
  {
    char error_buf[100];
    error_strerror( ret, error_buf, 100 );
    printf("Last error was: %d - %s\n\n\r", ret, error_buf );
  }
#endif
  
  x509_free( &cacert );
  net_close( server_fd );
  ssl_free( &ssl );
  
  memset( &ssl, 0, sizeof( ssl ) );
  
  /* Infinite loop */
  for( ;; ) 
  {
    /* Toggle LED1 */
    BSP_LED_Toggle(LED1);
    
    /* Insert 400 ms delay */
    osDelay(400);
  }
}
Example #9
0
/**
  * @brief  Mutex Low Priority Thread.
  * @param  argument: Not used
  * @retval None
  */
static void MutexLowPriorityThread(void const *argument)
{
  /* Just to remove compiler warning. */
  (void) argument;
  
  for(;;)
  {
    /* Keep attempting to obtain the mutex.  We should only obtain it when
    the medium-priority thread has suspended itself, which in turn should only
    happen when the high-priority thread is also suspended. */
    if(osMutexWait(osMutex, mutexNO_DELAY) == osOK)
    {
      /* Is the high and medium-priority threads suspended? */
      if((osThreadGetState(osHighPriorityThreadHandle) != osThreadSuspended) || (osThreadGetState(osMediumPriorityThreadHandle) != osThreadSuspended))
      {
        /* Toggle LED 3 to indicate error */
        BSP_LED_Toggle(LED3);
      }
      else
      {
        /* Keep count of the number of cycles this task has performed 
        so a stall can be detected. */
        LowPriorityThreadCycles++;
        BSP_LED_Toggle(LED4);
        
        /* We can resume the other tasks here even though they have a
        higher priority than the this thread. When they execute they
        will attempt to obtain the mutex but fail because the low-priority 
        thread is still the mutex holder.  this thread will then inherit 
        the higher priority.  The medium-priority thread will block indefinitely 
        when it attempts to obtain the mutex, the high-priority thread will only 
        block for a fixed period and an error will be latched if the 
        high-priority thread has not returned the mutex by the time this 
        fixed period has expired. */
        osThreadResume(osMediumPriorityThreadHandle);
        osThreadResume(osHighPriorityThreadHandle);
        
        /* The other two tasks should now have executed and no longer
        be suspended. */
        if((osThreadGetState(osHighPriorityThreadHandle) == osThreadSuspended) || (osThreadGetState(osMediumPriorityThreadHandle) == osThreadSuspended))
        {
          /* Toggle LED 3 to indicate error */
          BSP_LED_Toggle(LED3);
        }
        
        /* Release the mutex, disinheriting the higher priority again. */
        if(osMutexRelease(osMutex) != osOK)
        {
          /* Toggle LED 3 to indicate error */
          BSP_LED_Toggle(LED3);
        }
      }
    }
    
#if configUSE_PREEMPTION == 0
    {
      taskYIELD();
    }
#endif
  }
}
Example #10
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure Green, Red and Orange LEDs */
  BSP_LED_Init(LED_GREEN);
  BSP_LED_Init(LED_RED);
  BSP_LED_Init(LED_ORANGE);    
  
  /* Configure the system clock to 72 Mhz */
  SystemClock_Config();
 
  /* Enable Power Clock */
  __PWR_CLK_ENABLE();
  
  /* Check and handle if the system was resumed from StandBy mode */ 
  if(__HAL_PWR_GET_FLAG(PWR_FLAG_SB) != RESET)
  {
    __HAL_PWR_CLEAR_FLAG(PWR_FLAG_SB);

    /* Turn on the Orange LED */
    BSP_LED_On(LED_ORANGE);
    uwStandByOutFlag = 1;
  }
 
 /* infinite loop */
  while(1)
  {

    /* Configure User Button */
    BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
    UserButtonStatus = 0;
    
    /* Wait until User button is pressed to enter the Low Power mode.
       In the meantime, LED_GREEN is blinking */
    while(UserButtonStatus == 0)
    {
      BSP_LED_Toggle(LED_GREEN); 
      HAL_Delay(100);
      
      /* if exiting from stand-by mode, 
         keep LED_ORANGE ON for about 3 sec. */
      if (uwStandByOutFlag > 0)
      {
        uwStandByOutFlag++;
        if (uwStandByOutFlag == 30)
        {
          BSP_LED_Off(LED_ORANGE);
          uwStandByOutFlag = 0; 
        }
      }
      /* if exiting from stop mode thru RTC alarm
        interrupt, keep LED_ORANGE ON for about 3 sec. */      
      if (uwWakeUpIntFlag > 0)
      {
        uwWakeUpIntFlag++;
        if (uwWakeUpIntFlag == 30)
        {
          BSP_LED_Off(LED_BLUE);
          uwWakeUpIntFlag = 0; 
        }
      }
    }
    
    /* Loop while Key button is maintained pressed */
    while(BSP_PB_GetState(BUTTON_KEY) != SET) {} 
    
    
    /* Make sure LED_GREEN is turned off to 
      reduce low power mode consumption */
    BSP_LED_Off(LED_GREEN);
    
#if defined (SLEEP_MODE)
    /* Sleep Mode Entry 
    - System Running at PLL (72 MHz)
    - Flash 2 wait state
    - Instruction and Data caches ON
    - Prefetch ON
    - Code running from Internal FLASH
    - All peripherals disabled.
    - Wakeup using EXTI Line (Key Button PE.06)
    */
    SleepMode_Measure();
#elif defined (STOP_MODE)
    /* STOP Mode Entry 
    - RTC Clocked by LSI
    - Regulator in LP mode
    - HSI, HSE OFF and LSI OFF if not used as RTC Clock source  
    - No IWDG
    - Wakeup using EXTI Line (Key Button PE.06)
    */
    StopMode_Measure();      
#elif defined (STOP_RTC_MODE)
    /* STOP Mode Entry 
    - RTC Clocked by LSI
    - Regulator in LP mode
    - HSI, HSE OFF and LSI OFF if not used as RTC Clock source  
    - No IWDG
    - Automatic Wakeup using RTC clocked by LSI (after ~20s)
    */
    StopRTCMode_Measure();  
#elif defined (STANDBY_MODE)
    /* STANDBY Mode Entry 
    - Backup SRAM and RTC OFF
    - IWDG and LSI OFF
    - Wakeup using WakeUp Pin (Key Button PE.06)
    */
    StandbyMode_Measure();
#elif defined (STANDBY_RTC_MODE)
    /* STANDBY Mode with RTC on LSI Entry 
    - RTC Clocked by LSI
    - IWDG OFF and LSI OFF if not used as RTC Clock source
    - Automatic Wakeup using RTC clocked by LSI (after ~20s)
    */
    StandbyRTCMode_Measure();
#endif    
  }
}
Example #11
0
/**
  * @brief  PWR PVD interrupt callback
  * @param  none 
  * @retval none
  */
void HAL_PWR_PVDCallback(void)
{
  /* Toggle LED1 */
  BSP_LED_Toggle(LED1);
}
Example #12
0
/**
  * @brief  Demo application for IAP through USB mass storage.
  * @param  None
  * @retval None
  */
void FW_UPGRADE_Process(void)
{
    switch(Demo_State)
    {
    case DEMO_INIT:
        /* Register the file system object to the FatFs module */
        if(f_mount(&USBH_fatfs, "", 0 ) != FR_OK )
        {
            /* FatFs initialization fails */
            /* Toggle LED3 and LED4 in infinite loop */
            FatFs_Fail_Handler();
        }

        /* TO DO */

        //    /* Flash Disk is write protected: Turn LED4 On and Toggle LED3 in infinite loop */
        //    if(USBH_MSC_Param.MSWriteProtect == DISK_WRITE_PROTECTED)
        //    {
        //      /* Turn LED4 On */
        //      BSP_LED_On(LED4);
        //      /* Toggle LED3 in infinite loop */
        //      Fail_Handler();
        //    }

        /* Go to IAP menu */
        Demo_State = DEMO_IAP;
        break;

    case DEMO_IAP:
        while(USBH_MSC_IsReady(&hUSBHost))
        {
            /* Control BUFFER_SIZE value */
            USBH_USR_BufferSizeControl();

            /* Keep LED1 and LED3 Off when Device connected */
            BSP_LED_Off(LED3);
            BSP_LED_Off(LED4);

            /* USER Button pressed Delay */
            IAP_UploadTimeout();

            /* Writes Flash memory */
            COMMAND_Download();

            /* Check if USER Button is already pressed */
            if((UploadCondition == 0x01))
            {
                /* Reads all flash memory */
                COMMAND_Upload();
            }
            else
            {
                /* Turn LED4 Off: Download Done */
                BSP_LED_Off(LED4);
                /* Turn LED3 On: Waiting KEY button pressed */
                BSP_LED_On(LED3);
            }

            /* Waiting USER Button Released */
            while((BSP_PB_GetState(BUTTON_KEY) == GPIO_PIN_RESET) && (Appli_state == APPLICATION_READY))
            {}

            /* Waiting USER Button Pressed */
            while((BSP_PB_GetState(BUTTON_KEY) != GPIO_PIN_RESET) && (Appli_state == APPLICATION_READY))
            {}

            /* Waiting USER Button Released */
            while((BSP_PB_GetState(BUTTON_KEY) == GPIO_PIN_RESET) && (Appli_state == APPLICATION_READY))
            {}

            if(Appli_state == APPLICATION_READY)
            {
                /* Jump to user application code located in the internal Flash memory */
                COMMAND_Jump();
            }
        }
        break;

    default:
        break;
    }
    if(Appli_state == APPLICATION_DISCONNECT)
    {
        /* Toggle LED3: USB device disconnected */
        BSP_LED_Toggle(LED4);
        HAL_Delay(100);
    }
}
Example #13
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{

  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure LED2 */
  BSP_LED_Init(LED2);


  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance        = USARTx;

  UartHandle.Init.BaudRate   = 9600;
  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits   = UART_STOPBITS_1;
  UartHandle.Init.Parity     = UART_PARITY_NONE;
  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode       = UART_MODE_TX_RX;
  UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }  
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef TRANSMITTER_BOARD

  /* Configure User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Wait for User push-button press before starting the Communication.
     In the meantime, LED2 is blinking */
  while(UserButtonStatus == 0)
  {
      /* Toggle LED2*/
      BSP_LED_Toggle(LED2); 
      HAL_Delay(100);
  }
  
  BSP_LED_Off(LED2); 
  
  
  /* The board sends the message and expects to receive it back */
  
  /*##-2- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE, 5000)!= HAL_OK)
  {
    Error_Handler();   
  }
  
  
  /*##-3- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE, 5000) != HAL_OK)
  {
    Error_Handler();  
  }
   
 
#else
  
  /* The board receives the message and sends it back */

  /*##-2- Put UART peripheral in reception process ###########################*/
  if(HAL_UART_Receive(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE, 0x1FFFFFF) != HAL_OK)
  {
    Error_Handler();
  }
 
  
  /*##-3- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE, 5000)!= HAL_OK)
  {
    Error_Handler();
  }
  
  
#endif /* TRANSMITTER_BOARD */
  
  /*##-4- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
  {
    Error_Handler();
  }
   
  /* Turn on LED2 if test passes then enter infinite loop */
  BSP_LED_On(LED2); 
  /* Infinite loop */
  while (1)
  {
  }
}
Example #14
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure LED */
  BSP_LED_Init(LED2); 

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /* Enable Power Clock */
  __HAL_RCC_PWR_CLK_ENABLE();

  /* Check and handle if the system was resumed from StandBy mode */
  if (__HAL_PWR_GET_FLAG(PWR_FLAG_SB) != RESET)
  {
    __HAL_PWR_CLEAR_FLAG(PWR_FLAG_SB);

    /* Configure User push-button */
    BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO);

    /* Turn on the LED2 and keep 
       it on for 2 sec. to indicate
       exit from stand-by mode */
    BSP_LED_On(LED2);
    while(BSP_PB_GetState(BUTTON_USER) == GPIO_PIN_RESET){}
    HAL_Delay(2000);

    uwStandByOutFlag = 1;

  }

  /* Infinite loop */
  while(1)
  {
    /* Configure User push-button as external interrupt generator */
    BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
    UserButtonStatus = 0;
    
    /* Wait until User push-button is pressed to enter the Low Power mode.
       In the meantime, LED2 is blinks */
    while (UserButtonStatus == 0)
    {
      /* Toggle LED2 */
      BSP_LED_Toggle(LED2); 
      HAL_Delay(100);

    }

    /* Make sure LED2 is turned off to 
       reduce low power mode consumption */
    BSP_LED_Off(LED2);

#if defined (SLEEP_MODE)
    /* Sleep Mode Entry
        - System Running at PLL (48 MHz)
        - Flash 2 wait state
        - Instruction and Data caches ON
        - Prefetch ON
        - Code running from Internal FLASH
        - All peripherals disabled.
        - Wakeup using EXTI Line (User push-button PC.13)
    */
    SleepMode_Measure();
#elif defined (STOP_RTC_MODE)
    /* STOP Mode Entry 
    - RTC Clocked by LSI or LSE
    - Regulator in LP mode
    - HSI, HSE OFF and LSI OFF if not used as RTC Clock source  
    - No IWDG
    - Automatic Wakeup using RTC clocked by LSI (after ~20s)
    - Wakeup using EXTI Line (User push-button PC.13)
    */
    StopRTCMode_Measure();
#elif defined (STANDBY_MODE)
    /* STANDBY Mode Entry
        - RTC OFF
        - IWDG and LSI OFF
        - Wakeup using WakeUp Pin PWR_WAKEUP_PIN2 connected to PC.13
    */
    StandbyMode_Measure();
#elif defined (STANDBY_RTC_MODE)
    /* STANDBY Mode with RTC on LSE/LSI Entry
        - RTC Clocked by LSE or LSI
        - IWDG OFF and LSI OFF if not used as RTC Clock source
        - Automatic Wakeup using RTC clocked by LSE/LSI (after ~20s)
    */
    StandbyRTCMode_Measure();
#endif
  }
}
Example #15
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure LED2 */
  BSP_LED_Init(LED2);

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /*##-1- Configure the SPI peripheral #######################################*/
  /* Set the SPI parameters */
  SpiHandle.Instance               = SPIx;
  SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
  SpiHandle.Init.Direction         = SPI_DIRECTION_2LINES;
  SpiHandle.Init.CLKPhase          = SPI_PHASE_1EDGE;
  SpiHandle.Init.CLKPolarity       = SPI_POLARITY_LOW;
  SpiHandle.Init.CRCCalculation    = SPI_CRCCALCULATION_DISABLE;
  SpiHandle.Init.CRCPolynomial     = 7;
  SpiHandle.Init.DataSize          = SPI_DATASIZE_8BIT;
  SpiHandle.Init.FirstBit          = SPI_FIRSTBIT_MSB;
  SpiHandle.Init.NSS               = SPI_NSS_SOFT;
  SpiHandle.Init.TIMode            = SPI_TIMODE_DISABLE;
  SpiHandle.Init.NSSPMode          = SPI_NSS_PULSE_DISABLE;
  SpiHandle.Init.CRCLength         = SPI_CRC_LENGTH_8BIT;

#ifdef MASTER_BOARD
  SpiHandle.Init.Mode = SPI_MODE_MASTER;
#else
  SpiHandle.Init.Mode = SPI_MODE_SLAVE;
#endif /* MASTER_BOARD */

  if(HAL_SPI_Init(&SpiHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }
  
#ifdef MASTER_BOARD
  /* Configure User push-button */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO);
  /* Wait for User push-button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_USER) != GPIO_PIN_RESET)
  {
    BSP_LED_Toggle(LED2);
    HAL_Delay(40);
  }
  BSP_LED_Off(LED2);
#endif /* MASTER_BOARD */

  /*##-2- Start the Full Duplex Communication process ########################*/  
  /* While the SPI in TransmitReceive process, user can transmit data through 
     "aTxBuffer" buffer & receive data through "aRxBuffer" */
  if(HAL_SPI_TransmitReceive_IT(&SpiHandle, (uint8_t*)aTxBuffer, (uint8_t *)aRxBuffer, BUFFERSIZE) != HAL_OK)
  {
    /* Transfer error in transmission process */
    Error_Handler();
  }

  /*##-3- Wait for the end of the transfer ###################################*/  
  /*  Before starting a new communication transfer, you need to check the current   
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the 
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */  
  while (HAL_SPI_GetState(&SpiHandle) != HAL_SPI_STATE_READY)
  {
  } 

  /*##-4- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer, (uint8_t*)aRxBuffer, BUFFERSIZE))
  {
    /* Processing Error */
    Error_Handler();     
  }

  /* Infinite loop */  
  while (1)
  {
  }
}
Example #16
0
File: main.c Project: z80/stm32f429
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  uint32_t index = 0;
  RTC_TamperTypeDef  stamperstructure;
  
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure the system clock to 180 MHz */
  SystemClock_Config();

  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);

  /* Configure User push-button button */
  BSP_PB_Init(BUTTON_TAMPER, BUTTON_MODE_GPIO);
  
  /*##-1- Configure the RTC peripheral #######################################*/
  /* Configure RTC prescaler and RTC data registers */
  /* RTC configured as follows:
      - Hour Format    = Format 24
      - Asynch Prediv  = Value according to source clock
      - Synch Prediv   = Value according to source clock
      - OutPut         = Output Disable
      - OutPutPolarity = High Polarity
      - OutPutType     = Open Drain */
  RtcHandle.Instance            = RTC;
  RtcHandle.Init.HourFormat     = RTC_HOURFORMAT_24;
  RtcHandle.Init.AsynchPrediv   = RTC_ASYNCH_PREDIV;
  RtcHandle.Init.SynchPrediv    = RTC_SYNCH_PREDIV;
  RtcHandle.Init.OutPut         = RTC_OUTPUT_DISABLE;
  RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  RtcHandle.Init.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN;
  
  if (HAL_RTC_Init(&RtcHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /*##-2- Configure RTC Tamper ###############################################*/
  stamperstructure.Tamper                       = RTC_TAMPER_1;
  /* Use PC13 as Tamper 1 with interrupt mode */
  stamperstructure.PinSelection                 = RTC_TAMPERPIN_PC13;
  stamperstructure.Trigger                      = RTC_TAMPERTRIGGER_FALLINGEDGE;
  stamperstructure.Filter                       = RTC_TAMPERFILTER_DISABLE;
  stamperstructure.SamplingFrequency            = RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768;
  stamperstructure.PrechargeDuration            = RTC_TAMPERPRECHARGEDURATION_1RTCCLK;
  stamperstructure.TamperPullUp                 = RTC_TAMPER_PULLUP_ENABLE;
  stamperstructure.TimeStampOnTamperDetection   = RTC_TIMESTAMPONTAMPERDETECTION_DISABLE;

  if (HAL_RTCEx_SetTamper_IT(&RtcHandle, &stamperstructure) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /* Clear the Tamper interrupt pending bit */
  __HAL_RTC_TAMPER_CLEAR_FLAG(&RtcHandle,RTC_FLAG_TAMP1F);

  /*##-3- Write Data on the Back Up registers ################################*/
  for (index = 0; index < BACKUP_COUNT; index++)
  {
    HAL_RTCEx_BKUPWrite(&RtcHandle, aBKPDataReg[index], 0xDF59 + (index * 0x5A));
  }

  /*##-4- Check Data is stored on the Back Up registers ######################*/
  for (index = 0; index < BACKUP_COUNT; index++)
  {
    if (HAL_RTCEx_BKUPRead(&RtcHandle, aBKPDataReg[index]) != (0xDF59 + (index * 0x5A)))
    {
      Error_Handler();
    }
  }

  /*##-5- Wait for the tamper button is pressed ##############################*/
  while (TamperStatus != SET)
  {
    /* Toggle LED1 with a period of 1s */
    BSP_LED_Toggle(LED1);

    /* Delay */
    HAL_Delay(1000);
  }

  /*##-6- Deactivate the tamper                 ##############################*/
  HAL_RTCEx_DeactivateTamper(&RtcHandle, RTC_TAMPER_1);
    
  /*##-7- Check Data is cleared on the Back Up registers #####################*/
  for (index = 0; index < BACKUP_COUNT; index++)
  {
    if (HAL_RTCEx_BKUPRead(&RtcHandle, aBKPDataReg[index]) != 0x00)
    {
      Error_Handler();
    }
  }

  /* Infinite loop */
  while (1)
  {
    /* Turn LED1 on */
    BSP_LED_Toggle(LED1);

    /* Delay */
    HAL_Delay(100);
  }
}
Example #17
0
File: main.c Project: shjere/common
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32L0xx HAL library initialization:
       - Configure the Flash prefetch, Flash preread and Buffer caches
       - Systick timer is configured by default as source of time base, but user 
             can eventually implement his proper time base source (a general purpose 
             timer for example or other time source), keeping in mind that Time base 
             duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
             handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();
  
  /*******************************************************************************
  *                          Common Configuration Routines                       *
  *******************************************************************************/  
 
 /* Configure LED2 and Key Button */
  BSP_LED_Init(LED2);
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  /* Configure the system clock to 32 Mhz */
  SystemClock_Config();     
  

  /*##-1- Check if the system has resumed from IWDG reset ####################*/
  if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST) != RESET)
  { 
    /* IWDGRST flag set: Turn LED2 on */
    BSP_LED_On(LED2);

    /* Insert 4s delay */
    HAL_Delay(4000);
    
    /* Clear reset flags */
    __HAL_RCC_CLEAR_RESET_FLAGS();
  }
  else
  {
    /* IWDGRST flag is not set: Turn LED2 off */
    BSP_LED_Off(LED2);
  }
 
  /*##-2- Get the LSI frequency: TIM21 is used to measure the LSI frequency ###*/
  uwLsiFreq = GetLSIFrequency();
  
  /*##-3- Configure & Initialize the IWDG peripheral ######################################*/
  /* 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 */
  IwdgHandle.Instance = IWDG;

  IwdgHandle.Init.Prescaler = IWDG_PRESCALER_32;
  IwdgHandle.Init.Reload = uwLsiFreq/128;
  IwdgHandle.Init.Window = IWDG_WINDOW_DISABLE;

  if(HAL_IWDG_Init(&IwdgHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }
  
  /*##-4- Start the IWDG #####################################################*/ 
  if(HAL_IWDG_Start(&IwdgHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
  /* Infinite loop */ 
  while (1)
  {
    /* Toggle LED2 */
    BSP_LED_Toggle(LED2);

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

    /* Refresh IWDG: reload counter */
    if(HAL_IWDG_Refresh(&IwdgHandle) != HAL_OK)
    {
      /* Refresh Error */
      Error_Handler();
    }
  }
}
Example #18
0
/**
  * @brief  Period elapsed callback in non blocking mode
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  BSP_LED_Toggle(LED1);
}
Example #19
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
#ifdef TRANSMITTER_BOARD
  GPIO_InitTypeDef  GPIO_InitStruct;
#endif
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
             can eventually implement his proper time base source (a general purpose 
             timer for example or other time source), keeping in mind that Time base 
             duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
             handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();
  
  /* Configure LED3 */
  BSP_LED_Init(LED3);

#ifdef TRANSMITTER_BOARD
  /* Configure PA.12 (Arduino D2) as input with External interrupt */
  GPIO_InitStruct.Pin = GPIO_PIN_12;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;

  /* Enable GPIOA clock */
  __HAL_RCC_GPIOA_CLK_ENABLE();

  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* Enable and set PA.12 (Arduino D2) EXTI Interrupt to the lowest priority */
  NVIC_SetPriority((IRQn_Type)(EXTI4_15_IRQn), 0x03);
  HAL_NVIC_EnableIRQ((IRQn_Type)(EXTI4_15_IRQn));
  /* Wait for the user to set GPIOA to GND before starting the Communication.
     In the meantime, LED3 is blinking */
  while(VirtualUserButtonStatus == 0)
  {
      /* Toggle LED3*/
      BSP_LED_Toggle(LED3);
      HAL_Delay(100);
  }

  BSP_LED_Off(LED3);
#endif

  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance        = USARTx;

  UartHandle.Init.BaudRate   = 9600;
  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits   = UART_STOPBITS_1;
  UartHandle.Init.Parity     = UART_PARITY_NONE;
  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode       = UART_MODE_TX_RX;
  UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }  
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef TRANSMITTER_BOARD
  
  /* The board sends the message and expects to receive it back */
  /* DMA is programmed for reception before starting the transmission, in order to
     be sure DMA Rx is ready when board 2 will start transmitting */

  /*##-2- Program the Reception process #####################################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

  /*##-3- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-4- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;
  
#else
  
  /* The board receives the message and sends it back */

  /*##-2- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

  /*##-3- Wait for the end of the transfer ###################################*/
  /* While waiting for message to come from the other board, LED3 is
     blinking according to the following pattern: a double flash every half-second */  
  while (UartReady != SET)
  {
      BSP_LED_On(LED3); 
      HAL_Delay(100);
      BSP_LED_Off(LED3); 
      HAL_Delay(100);
      BSP_LED_On(LED3); 
      HAL_Delay(100);
      BSP_LED_Off(LED3); 
      HAL_Delay(500); 
  }

  /* Reset transmission flag */
  UartReady = RESET;
  BSP_LED_Off(LED3); 
  
  /*##-4- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
#endif /* TRANSMITTER_BOARD */
  
  /*##-5- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;

  /*##-6- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
  {
    Error_Handler();
  }
   
  /* Turn on LED3 if test passes then enter infinite loop */
  BSP_LED_On(LED3); 
  /* Infinite loop */
  while (1)
  {
  }
}
Example #20
0
File: main.c Project: z80/stm32f429
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure LED3, LED4, LED5 and LED6 */
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED4);
  BSP_LED_Init(LED5);
  BSP_LED_Init(LED6);
  
  /* Configure USER Button, used to trigger an interrupt each time it's pressed.
     In the ISR the PLL source will be changed from HSE to HSI, and vice versa. */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);  

  /* Enable Power Control clock */
  __HAL_RCC_PWR_CLK_ENABLE();

  /* The voltage scaling allows optimizing the power consumption when the device is 
     clocked below the maximum system frequency, to update the voltage scaling value 
     regarding system frequency refer to product datasheet.  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
   
  /* Enable HSE oscillator and configure the PLL to reach the max system frequency (168MHz)
     when using HSE oscillator as PLL clock source. */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 7;
  if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }
  
  /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers.
     The SysTick 1 msec interrupt is required for the HAL process (Timeout management); by default
     the configuration is done using the HAL_Init() API, and when the system clock configuration
     is updated the SysTick configuration will be adjusted by the HAL_RCC_ClockConfig() API. */
  RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;  
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;  
  if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /* STM32F405x/407x/415x/417x Revision Z devices: prefetch is supported  */
  if (HAL_GetREVID() == 0x1001)
  {
    /* Enable the Flash prefetch */
    __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
  }

  /* Output SYSCLK divided by 2 on MCO2 pin(PC9) */ 
  HAL_RCC_MCOConfig(RCC_MCO2, RCC_MCO2SOURCE_SYSCLK, RCC_MCODIV_2);

  /* Toggle some LEDs in an infinite loop */  
  while (1)
  {
   /* Toggle LED3 */
    BSP_LED_Toggle(LED3);
    HAL_Delay(100);
    /* Toggle LED4 */
    BSP_LED_Toggle(LED4);
    HAL_Delay(100);
    /* Toggle LED6 */
    BSP_LED_Toggle(LED6);
    HAL_Delay(100);
  }
}
Example #21
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 180 MHz */
  SystemClock_Config();
  
  /* Configure LED1, LED2, LED3 and LED4 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED4);
  
  /* Initialize the Push buttons */
  /* Wakeup button used for Volume Low */    
  BSP_PB_Init(BUTTON_WAKEUP, BUTTON_MODE_GPIO); 
  /* Tamper button used for Volume High */ 
  BSP_PB_Init(BUTTON_TAMPER, BUTTON_MODE_GPIO);  
  
  /* Initialize the LCD */
  BSP_LCD_Init();
  
  BSP_LCD_LayerDefaultInit(1, 0xC0130000);
  
  BSP_LCD_SelectLayer(1);
  
  /* Display message on EVAL LCD **********************************************/
  /* Clear the LCD */ 
  BSP_LCD_Clear(LCD_COLOR_BLUE);  
  
  /* Set the LCD Back Color */
  BSP_LCD_SetBackColor(LCD_COLOR_BLUE);
  
  /* Set the LCD Text Color */
  BSP_LCD_SetTextColor(LCD_COLOR_WHITE);
  BSP_LCD_DisplayStringAt(0, LINE(0), (uint8_t *)MESSAGE1, CENTER_MODE);
  BSP_LCD_DisplayStringAt(0, LINE(1), (uint8_t *)MESSAGE2, CENTER_MODE);
  BSP_LCD_DisplayStringAt(0, LINE(2), (uint8_t *)MESSAGE3, CENTER_MODE);
  
  /* Turn on LEDs available on EVAL *******************************************/
  BSP_LED_On(LED1);
  BSP_LED_On(LED2);
  BSP_LED_On(LED3);
  BSP_LED_On(LED4);
  
  /* Initialize the Audio codec and all related peripherals (SAI, I2C, IOs...) */  
  if(AUDIO_Init() == AUDIO_ERROR_NONE)
  {
    BSP_LCD_DisplayStringAt(0, LINE(4), (uint8_t *)"====================", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, LINE(5), (uint8_t *)"Tamper: Vol+        ", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, LINE(6), (uint8_t *)"Wakeup: Vol-        ", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, LINE(7), (uint8_t *)"====================", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, LINE(8), (uint8_t *)"  AUDIO CODEC   OK  ", CENTER_MODE);    
  }
  else
  {
    BSP_LCD_DisplayStringAt(0, LINE(4), (uint8_t *)"  AUDIO CODEC  FAIL ", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, LINE(5), (uint8_t *)" Try to reset board ", CENTER_MODE);
  }
  
  /* 
  Start playing the file from a circular buffer, once the DMA is enabled, it is 
  always in running state. Application has to fill the buffer with the audio data 
  using Transfer complete and/or half transfer complete interrupts callbacks 
  (EVAL_AUDIO_TransferComplete_CallBack() or EVAL_AUDIO_HalfTransfer_CallBack()...
  */
  AUDIO_Start();
  
  /* Display the state on the screen */
  BSP_LCD_DisplayStringAt(0, LINE(9), (uint8_t *)"       PLAYING...     ", CENTER_MODE);

   
  /* IMPORTANT:
     AUDIO_Process() is called by the SysTick Handler, as it should be called 
     within a periodic process */
   
  /* Infinite loop */
  while(1)
  {      
    /* Check on the Volume high button */
    if (BSP_PB_GetState(BUTTON_WAKEUP) != RESET)
    {
      /* Wait to avoid rebound */
      while (BSP_PB_GetState(BUTTON_WAKEUP) != RESET);
      
      /* Decrease volume by 5% */
      if (uwVolume > 5)
        uwVolume -= 5; 
      else
        uwVolume = 0; 
      
      /* Apply the new volume to the codec */
      BSP_AUDIO_OUT_SetVolume(uwVolume);
      BSP_LCD_DisplayStringAt(0, LINE(10), (uint8_t *)"       VOL:   -     ", CENTER_MODE); 
    }    
    
    /* Check on the Volume high button */
    if (BSP_PB_GetState(BUTTON_TAMPER) == RESET)
    {
      /* Wait to avoid rebound */
      while (BSP_PB_GetState(BUTTON_TAMPER) == RESET);
      
      /* Increase volume by 5% */
      if (uwVolume < 95)
        uwVolume += 5; 
      else
        uwVolume = 100; 
      
      /* Apply the new volume to the codec */
      BSP_AUDIO_OUT_SetVolume(uwVolume);
      BSP_LCD_DisplayStringAt(0, LINE(10), (uint8_t *)"       VOL:   +     ", CENTER_MODE);
    }  
    
    /* Toggle LED3 */
    BSP_LED_Toggle(LED3);
    
    /* Insert 100 ms delay */
    HAL_Delay(100);
    
    /* Toggle LED2 */
    BSP_LED_Toggle(LED2);
    
    /* Insert 100 ms delay */
    HAL_Delay(100);
  } 
}
Example #22
0
/* Funzione: client_request_time(uint8_t client_id)
 * Parametri: client_id: id del nodo che effettua la richiesta
 * @brief : chiede all'host di sincronizzare gli orologi
 *
 * */
void client_request_time(uint8_t client_id){

	sys_time temp;

	suspend_time();

	uint32_t send_tick = HAL_GetTick();

	//network_level_request_time(client_id, &temp);

	uint32_t receive_tick = HAL_GetTick();

	uint16_t delay = (receive_tick - send_tick) / 2;
	uint16_t old_millis = temp.milliseconds;
	temp.milliseconds += delay;

	if(old_millis < temp.milliseconds){
		_sys_time.milliseconds = old_millis-temp.milliseconds;
					if (++_sys_time.seconds % 60 == 0) { /*Incrementa secondi. Se sono arrivati a 60 ==> ho contato 1 minuto*/

						BSP_LED_Toggle(LED5);
						_sys_time.seconds = 0;
						if (++_sys_time.minutes % 60 == 0) { /*Incrementa minuti. Se sono arrivati a 60 ==> ho contato 1 ora*/

							_sys_time.minutes = 0;
							if (++_sys_time.hour % 24 == 0) { /*Incrementa ore. Se sono arrivate a 24 ==> ho contato 1 giorno*/

								BSP_LED_Toggle(LED3);
								_sys_time.hour = 0;
								_sys_time.day++; /*Incrementa giorni.*/

								/*Controlla valore del giorno a seconda del mese per capire se si deve incrementare il mese*/

								if (((_sys_time.month & 1) && (_sys_time.month < 8)) || //gennaio, marzo, maggio ,luglio,
										(!(_sys_time.month & 1)
												&& (_sys_time.month >= 8))) { //agosto, ottobre, dicembre

									if (_sys_time.day % 32 == 0) {
										_sys_time.day = 1;
										_sys_time.month++;
									}
								} else if (_sys_time.month == 2) {			//febbraio

									if (_sys_time.day % 29 == 0) {
										_sys_time.day = 1;
										_sys_time.month++;
									}

								} else {
									if (_sys_time.day % 31 == 0) {		//restanti mesi
										_sys_time.day = 1;
										_sys_time.month++;
									}
								}

								if (_sys_time.month % 13 == 0) {//Se i mesi sono arrivati a 12 ==> ho contato un anno

									_sys_time.month = 1;
									_sys_time.year++;

								}

							}

						}
					}
				}

	start_time();

}
Example #23
0
static void BlueNRG_Init()
{
  int rc;
  uint8_t bdaddr[] = {0x12, 0x34, 0x00, 0xE1, 0x80, 0x02};
  uint16_t service_handle, dev_name_char_handle, appearance_char_handle;
  const char *ble_name = "BlueNRG";

  BSP_LED_On(LED3);
  HCI_Init();

  /* Enable and set EXTI for BlueNRG IRQ */
  HAL_NVIC_SetPriority(BLUENRG_IRQ_EXTI_IRQn, 2, 0);
  HAL_NVIC_EnableIRQ(BLUENRG_IRQ_EXTI_IRQn);

  BlueNRG_RST();

  BSP_LED_On(LED4);
  rc = aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET,
                                 CONFIG_DATA_PUBADDR_LEN, bdaddr);
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED4);
  }

  BSP_LED_On(LED5);
  rc = aci_gatt_init();
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED5);
  }

  BSP_LED_On(LED6);
  rc = aci_gap_init(1, &service_handle, &dev_name_char_handle,
                    &appearance_char_handle);
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED6);
  }

  BSP_LED_Off(LED3);
  rc = aci_gatt_update_char_value(service_handle, dev_name_char_handle,
                                  0, strlen(ble_name), (uint8_t *)ble_name);
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED3);
  }

  BSP_LED_Off(LED4);
  rc = aci_gap_set_auth_requirement(MITM_PROTECTION_REQUIRED,
                                    OOB_AUTH_DATA_ABSENT,
                                    NULL,
                                    7,
                                    16,
                                    USE_FIXED_PIN_FOR_PAIRING,
                                    123456,
                                    BONDING);
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED4);
  }

  /* sensors have been initialized in HW_Init() */

  BSP_LED_Off(LED5);
  rc = Add_Acc_Service();
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED5);
  }

  BSP_LED_Off(LED6);
  rc = Add_Environmental_Sensor_Service();
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED6);
  }

  /* Init_User_Timer();
  Start_User_Timer(); */

  BSP_LED_On(LED3);
  /* -2 dBm output power */
  rc = aci_hal_set_tx_power_level(1, 4);
  while (rc) {
    HAL_Delay(100);
    BSP_LED_Toggle(LED3);
  }
}
Example #24
0
/* Funzione: Time_SYSTICK_Callback(void)
 * @brief : callback per il systick che incrementa, sulla base del tick di sitema, l'orologio
 *
 * */
void Time_SYSTICK_Callback(void) {

	if (is_time_enabled()) {

		BSP_LED_Toggle(LED4);
		if (++_sys_time.milliseconds % 1000 == 0) { /*Incrementa millisecondi. Se sono arrivati a 1000 ==> ho contato 1 secondo*/

			BSP_LED_Toggle(LED6);
#if TIME_SERVER==0
			_count++;
#endif
			_sys_time.milliseconds = 0;
			if (++_sys_time.seconds % 60 == 0) { /*Incrementa secondi. Se sono arrivati a 60 ==> ho contato 1 minuto*/

				BSP_LED_Toggle(LED5);
				_sys_time.seconds = 0;
				if (++_sys_time.minutes % 60 == 0) { /*Incrementa minuti. Se sono arrivati a 60 ==> ho contato 1 ora*/

					_sys_time.minutes = 0;
					if (++_sys_time.hour % 24 == 0) { /*Incrementa ore. Se sono arrivate a 24 ==> ho contato 1 giorno*/

						BSP_LED_Toggle(LED3);
						_sys_time.hour = 0;
						_sys_time.day++; /*Incrementa giorni.*/

						/*Controlla valore del giorno a seconda del mese per capire se si deve incrementare il mese*/

						if (((_sys_time.month & 1) && (_sys_time.month < 8)) || //gennaio, marzo, maggio ,luglio,
								(!(_sys_time.month & 1)
										&& (_sys_time.month >= 8))) { //agosto, ottobre, dicembre

							if (_sys_time.day % 32 == 0) {
								_sys_time.day = 1;
								_sys_time.month++;
							}
						} else if (_sys_time.month == 2) {			//febbraio

							if (_sys_time.day % 29 == 0) {
								_sys_time.day = 1;
								_sys_time.month++;
							}

						} else {
							if (_sys_time.day % 31 == 0) {		//restanti mesi
								_sys_time.day = 1;
								_sys_time.month++;
							}
						}

						if (_sys_time.month % 13 == 0) {//Se i mesi sono arrivati a 12 ==> ho contato un anno

							_sys_time.month = 1;
							_sys_time.year++;

						}

					}

				}
			}
		}

	}
#if TIME_SERVER == 0
	if( _count == _timeout ){
		_count = 0;
		//signal(timeout)
	}
#endif

} // end callback
Example #25
0
/**
  * @brief  Audio Play demo
  * @param  None
  * @retval None
  */
void AudioRec_demo (void)
{
  uint16_t NbRecord_done = 0;
  uint8_t FreqStr[256] = {0};
  AudioRec_State = REC_NONE_STATE;
  buffer_ctl.rec_length = 0;
  /* Initialize AudioRecFullBuff at the address of the audio_play reader */

  AudioRecFullBuff_addr = AUDIO_REC_START_ADDR;

  AudioRec_SetHint();

#ifdef JOYSTICK

  /* Initialize Joystick */
  if (BSP_JOY_Init(JOY_MODE_GPIO) != IO_OK)
  {
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_RED);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"ERROR", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 80, (uint8_t *)"Joystick cannot be initialized", CENTER_MODE);
  }
#endif

  /* Initialize Audio Recorder */
  if (BSP_AUDIO_IN_Init(DEFAULT_AUDIO_IN_FREQ, DEFAULT_AUDIO_IN_BIT_RESOLUTION, DEFAULT_AUDIO_IN_CHANNEL_NBR) == AUDIO_OK)
  {
    AudioRec_State = REC_RESET_STATE;
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_GREEN);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"  AUDIO RECORD INIT OK  ", CENTER_MODE);
  }
  else
  {
    AudioRec_State = REC_ERROR_STATE;
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_RED);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"  AUDIO RECORD INIT FAIL", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 80, (uint8_t *)"  Try to reset board ", CENTER_MODE);
  }
  
  /* Infinite loop */
  while (buffer_ctl.rec_length < AUDIO_REC_TOTAL_SIZE)
  {
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_BLUE);

    if (buffer_ctl.it_state == TRANSFER_HALF)
    {
      /* PDM to PCM data convert */
      BSP_AUDIO_IN_PDMToPCM((uint16_t*)&buffer_ctl.pdm_buff[0],
                            &buffer_ctl.pcm_buff[buffer_ctl.pcm_ptr]);

      buffer_ctl.pcm_ptr+= AUDIO_IN_PDM_BUFFER_SIZE/4/2;

      if(buffer_ctl.pcm_ptr == AUDIO_IN_PCM_BUFFER_SIZE/2)
      {
        buffer_ctl.wr_state   =  BUFFER_FULL;
        buffer_ctl.offset  = 0;
      }

      if(buffer_ctl.pcm_ptr >= AUDIO_IN_PCM_BUFFER_SIZE)
      {
        buffer_ctl.wr_state   =  BUFFER_FULL;
        buffer_ctl.offset  = AUDIO_IN_PCM_BUFFER_SIZE/2;
        buffer_ctl.pcm_ptr = 0;
      }
      buffer_ctl.it_state = TRANSFER_NONE;
    }

    if (buffer_ctl.it_state == TRANSFER_FULL)
    {
      /* PDM to PCM data convert */
      if (BSP_AUDIO_IN_PDMToPCM((uint16_t*)&buffer_ctl.pdm_buff[INTERNAL_BUFF_SIZE/2], &buffer_ctl.pcm_buff[buffer_ctl.pcm_ptr]) == 0)
      {
        buffer_ctl.pcm_ptr+= AUDIO_IN_PDM_BUFFER_SIZE/4/2;

        if(buffer_ctl.pcm_ptr == AUDIO_IN_PCM_BUFFER_SIZE/2)
        {
          buffer_ctl.wr_state =  BUFFER_FULL;
          buffer_ctl.offset = 0;
        }

        if(buffer_ctl.pcm_ptr >= AUDIO_IN_PCM_BUFFER_SIZE)
        {
          buffer_ctl.wr_state =  BUFFER_FULL;
          buffer_ctl.offset = AUDIO_IN_PCM_BUFFER_SIZE/2;
          buffer_ctl.pcm_ptr = 0;
         }
      }
      buffer_ctl.it_state = TRANSFER_NONE;
      NbRecord_done++;

    }

    /* PCM buffer is full, copy it into the record_file */
    if (buffer_ctl.wr_state == BUFFER_FULL)
    {
      memcpy((uint32_t *)AudioRecFullBuff_addr, (uint8_t*)(buffer_ctl.pcm_buff + buffer_ctl.offset), AUDIO_IN_PCM_BUFFER_SIZE);
      AudioRecFullBuff_addr += AUDIO_IN_PCM_BUFFER_SIZE;
      buffer_ctl.rec_length += AUDIO_IN_PCM_BUFFER_SIZE;
      buffer_ctl.wr_state =  BUFFER_EMPTY;
    }

#ifdef JOYSTICK
    /* Get the Joystick State */
    JoyState = BSP_JOY_GetState();
    switch (JoyState)
    {
      case JOY_SEL:
#endif
        if (AudioRec_State == REC_RESET_STATE)
        {
          /* Display the state on the screen */
          BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
          BSP_LCD_SetTextColor(LCD_COLOR_BLUE);
          BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 80, (uint8_t *)"       RECORDING...     ", CENTER_MODE);
          /* Start Recording */
          buffer_ctl.rec_length = 0;
          buffer_ctl.wr_state = BUFFER_EMPTY;
          buffer_ctl.it_state = TRANSFER_NONE;
          BSP_AUDIO_IN_Record((uint16_t*)&buffer_ctl.pdm_buff[0], INTERNAL_BUFF_SIZE);
          AudioRec_State = RECORD_ONGOING;
        }
#ifdef JOYSTICK
        break;
      default:
        break;
    }
#endif

    if (CheckForUserInput() > 0)
    {
      /* Stop recorder and exit the test (go to next test) */
      BSP_AUDIO_IN_Stop();
      return;
    }
  }

  /* Stop recorder once buffer_ctl.rec_length < AUDIO_REC_TOTAL_SIZE*/
  BSP_AUDIO_IN_Stop();

  BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
  BSP_LCD_SetTextColor(LCD_COLOR_BLUE);
  sprintf((char*)FreqStr, "RECORDING DONE, %d frames, START PLAYBACK", NbRecord_done);
  BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 65, (uint8_t *)FreqStr, CENTER_MODE);
  NbRecord_done = buffer_ctl.rec_length / (DEFAULT_AUDIO_IN_FREQ * DEFAULT_AUDIO_IN_CHANNEL_NBR * 2);
  sprintf((char*)FreqStr, "Elapsed_time: %d frames", NbRecord_done);
  BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 45, (uint8_t *)FreqStr, CENTER_MODE);



  /* -----------Start Playback -------------- */

  /* Initialize audio IN at REC_FREQ*/
  if(BSP_AUDIO_OUT_Init(OUTPUT_DEVICE_HEADPHONE, 95, DEFAULT_AUDIO_IN_FREQ/2) == 0)
  {
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_GREEN);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"  AUDIO CODEC   OK  ", CENTER_MODE);
  }
  else
  {
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_RED);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"  AUDIO CODEC  FAIL ", CENTER_MODE);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 80, (uint8_t *)" Try to reset board ", CENTER_MODE);
  }

  /* Play the recorded buffer*/
  if(AUDIO_Play_Start((uint32_t *)AUDIO_REC_START_ADDR, (uint32_t)AUDIO_REC_TOTAL_SIZE) == 0)
  {
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_GREEN);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"  AUDIO PLAYBACK   OK  ", CENTER_MODE);
  } else
  {
    BSP_LCD_SetBackColor(LCD_COLOR_WHITE);
    BSP_LCD_SetTextColor(LCD_COLOR_RED);
    BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 95, (uint8_t *)"  AUDIO PLAYBACK  FAIL ", CENTER_MODE);
  }
  
  BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize() - 25, (uint8_t *)"PLAYBACK DONE", CENTER_MODE);

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

    /* Insert 100 ms delay */
    HAL_Delay(100);
    if (CheckForUserInput() > 0)
    {
      /* Set LED4 */
      BSP_LED_On(LED4);
      /* Stop recorder */
      BSP_AUDIO_IN_Stop();
      /* Stop Player before close Test */
      BSP_AUDIO_OUT_Stop(CODEC_PDWN_SW);
      return;
    }
  }
}
Example #26
0
/**
  * @brief  Update the recorded data. 
  * @param  None
  * @retval None
  */
void WaveRecorderProcess(void)
{     
  /* Current size of the recorded buffer */
  uint32_t byteswritten = 0; 

  WaveCounter = 0;
  LEDsState = LEDS_OFF;

  /* Remove Wave file if it exists on USB Flash Disk */
  f_unlink(REC_WAVE_NAME);
  
  /* Open the file to write on it */
  if((AppliState == APPLICATION_IDLE) || (f_open(&WavFile, REC_WAVE_NAME, FA_CREATE_ALWAYS | FA_WRITE) != FR_OK))
  {   
    while(1)
    {
     /* Toggle LED5 in infinite loop to signal that: USB Flash Disk is not connected/removed
      or an issue has occurred when creating/opening Wave file */
      BSP_LED_Toggle(LED5); 
    }
  }
  else
  {
    WaveRecStatus = 1;
  }
  /* Initialize header file */
  WavProcess_EncInit(DEFAULT_AUDIO_IN_FREQ, pHeaderBuff);
  
  /* Write the header Wave */
  f_write(&WavFile, pHeaderBuff, 44, (void *)&byteswritten);
  
  /* Increment the Wave counter */  
  BufferCtl.fptr = byteswritten;
  
  BufferCtl.offset = BUFFER_OFFSET_NONE;
  BSP_AUDIO_IN_Init(DEFAULT_AUDIO_IN_FREQ, DEFAULT_AUDIO_IN_BIT_RESOLUTION, DEFAULT_AUDIO_IN_CHANNEL_NBR);
  BSP_AUDIO_IN_Record((uint16_t*)&InternalBuffer[0], INTERNAL_BUFF_SIZE);
  
  /* Reset the time recording base variable */
  TimeRecBase = 0;
  ITCounter = 0;
  LEDsState = LED3_TOGGLE;
  
  while(AppliState != APPLICATION_IDLE)
  { 
    /* Wait for the recording time */  
    if(TimeRecBase <= DEFAULT_TIME_REC)
    {
      /* Check if there are Data to write in Usb Key */
      if(AUDIODataReady == 1)
      {
        /* write buffer in file */
        res = f_write(&WavFile, (uint8_t*)(WrBuffer+AUDIOBuffOffset), WR_BUFFER_SIZE, (void*)&byteswritten);
        if(res != FR_OK)
        {
          Error_Handler();
        }
        BufferCtl.fptr += byteswritten;
        AUDIODataReady = 0;
      }
      
      /* User button pressed */
      if(CmdIndex != CMD_RECORD)
      {
        /* Stop Audio Recording */
        WaveRecorderStop();
        /* Switch Command Index to Play */
        CmdIndex = CMD_PLAY;
        /* Toggoling LED6 to signal Play */
        LEDsState = LED6_TOGGLE;
        break;
      }
    }
    else /* End of recording time DEFAULT_TIME_REC */
    {
      /* Stop Audio Recording */
      WaveRecorderStop();
      /* Change Command Index to Stop */
      CmdIndex = CMD_STOP;
      /* Toggoling LED4 to signal Stop */
      LEDsState = LED4_TOGGLE;
      AUDIODataReady = 0;
      break;
    }
  }
  
  /* Update the data length in the header of the recorded Wave */    
  f_lseek(&WavFile, 0);
  
  /* Parse the wav file header and extract required information */
  WavProcess_HeaderUpdate(pHeaderBuff, &WaveFormat);
  f_write(&WavFile, pHeaderBuff, 44, (void*)&byteswritten);
  
  /* Close file and unmount MyFilesystem */
  f_close (&WavFile);
  f_mount(NULL, 0, 1);
  
  /* Change Command Index to Play */
  CmdIndex = CMD_PLAY;
}
Example #27
0
void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *I2cHandle)
{
  /* Toggle LED2: Transfer in transmission process is correct */
  BSP_LED_Toggle(LED2);
}
Example #28
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{

  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure LED3 */
  BSP_LED_Init(LED3);

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();


#ifdef BOARD_IN_STOP_MODE  
  /* HSI must be UART clock source to be able to wake up the MCU */
  USARTx_RCC_CONFIG(RCC_USARTxCLKSOURCE_HSI);
#endif
  
  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
   
  UartHandle.Instance        = USARTx;
  HAL_UART_DeInit(&UartHandle); 

  UartHandle.Init.BaudRate   = 9600;
  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits   = UART_STOPBITS_1;
  UartHandle.Init.Parity     = UART_PARITY_NONE;
  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode       = UART_MODE_TX_RX;
  UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  
  
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef BOARD_IN_STOP_MODE
  
    BSP_LED_On(LED3);
    /* wait for two seconds before test start */
    HAL_Delay(2000);
  
   /* make sure that no UART transfer is on-going */ 
   while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_BUSY) == SET);
   /* make sure that UART is ready to receive
   * (test carried out again later in HAL_UARTEx_StopModeWakeUpSourceConfig) */   
   while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_REACK) == RESET);

  /* set the wake-up event:
   * specify wake-up on RXNE flag */
  WakeUpSelection.WakeUpEvent = UART_WAKEUP_ON_READDATA_NONEMPTY;
  if (HAL_UARTEx_StopModeWakeUpSourceConfig(&UartHandle, WakeUpSelection)!= HAL_OK)
  {
    Error_Handler(); 
  }
 
  /* Enable the UART Wake UP from stop mode Interrupt */
  __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_WUF);
  
  /* about to enter stop mode: switch off LED */
  BSP_LED_Off(LED3);
  /* enable MCU wake-up by UART */
  HAL_UARTEx_EnableStopMode(&UartHandle); 
  /* enter stop mode */
  HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);

  /* ... STOP mode ... */  
  
  

  SystemClock_Config_fromSTOP();
  /* at that point, MCU has been awoken: the LED has been turned back on */
  /* Wake Up based on RXNE flag successful */ 
  HAL_UARTEx_DisableStopMode(&UartHandle);

  /* wait for some delay */
  HAL_Delay(100);
  /* Inform other board that wake up is successful */
  if (HAL_UART_Transmit(&UartHandle, (uint8_t*)aTxBuffer1, COUNTOF(aTxBuffer1)-1, 5000)!= HAL_OK)  
  {
    Error_Handler();
  }  
  
  /*##-2- Wake Up second step  ###############################################*/
  /* make sure that no UART transfer is on-going */ 
  while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_BUSY) == SET);
  /* make sure that UART is ready to receive 
   * (test carried out again later in HAL_UARTEx_StopModeWakeUpSourceConfig) */    
  while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_REACK) == RESET);
  
  /* set the wake-up event:
   * specify wake-up on start-bit detection */
  WakeUpSelection.WakeUpEvent = UART_WAKEUP_ON_STARTBIT;
  if (HAL_UARTEx_StopModeWakeUpSourceConfig(&UartHandle, WakeUpSelection)!= HAL_OK)
  {
    Error_Handler(); 
  }

  /* Enable the UART Wake UP from stop mode Interrupt */
  __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_WUF);
  
  /* about to enter stop mode: switch off LED */
  BSP_LED_Off(LED3);
  /* enable MCU wake-up by UART */
  HAL_UARTEx_EnableStopMode(&UartHandle); 
  /* enter stop mode */
  HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);

  /* ... STOP mode ... */
   
  SystemClock_Config_fromSTOP();  
  /* at that point, MCU has been awoken: the LED has been turned back on */
  /* Wake Up on start bit detection successful */ 
  HAL_UARTEx_DisableStopMode(&UartHandle);
  /* wait for some delay */
  HAL_Delay(100);
  /* Inform other board that wake up is successful */
  if (HAL_UART_Transmit(&UartHandle, (uint8_t*)aTxBuffer2, COUNTOF(aTxBuffer2)-1, 5000)!= HAL_OK)  
  {
    Error_Handler();
  }   
  
  
  /*##-3- Wake Up third step  ################################################*/
 /* make sure that no UART transfer is on-going */ 
  while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_BUSY) == SET);
  /* make sure that UART is ready to receive
   * (test carried out again later in HAL_UARTEx_StopModeWakeUpSourceConfig) */       
  while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_REACK) == RESET);
     
  /* set the wake-up event:  
   * specify address-to-match type. 
   * The address is 0x29, meaning the character triggering the 
   * address match is 0xA9 */
  WakeUpSelection.WakeUpEvent = UART_WAKEUP_ON_ADDRESS;
  WakeUpSelection.AddressLength = UART_ADDRESS_DETECT_7B; 
  WakeUpSelection.Address = 0x29;  
  if (HAL_UARTEx_StopModeWakeUpSourceConfig(&UartHandle, WakeUpSelection)!= HAL_OK)
  {
    Error_Handler(); 
  }

  /* Enable the UART Wake UP from stop mode Interrupt */
  __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_WUF);
  
  /* about to enter stop mode: switch off LED */
  BSP_LED_Off(LED3);
  /* enable MCU wake-up by UART */
  HAL_UARTEx_EnableStopMode(&UartHandle); 
  /* enter stop mode */
  HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);

  /* ... STOP mode ... */
   
  SystemClock_Config_fromSTOP();  
  /* at that point, MCU has been awoken: the LED has been turned back on */
  /* Wake Up on 7-bit address detection successful */ 
  HAL_UARTEx_DisableStopMode(&UartHandle);
  /* wait for some delay */
  HAL_Delay(100);
  /* Inform other board that wake up is successful */
  if (HAL_UART_Transmit(&UartHandle, (uint8_t*)aTxBuffer3, COUNTOF(aTxBuffer3)-1, 5000)!= HAL_OK)  
  {
    Error_Handler();
  } 
  

  /*##-4- Wake Up fourth step  ###############################################*/   
 /* make sure that no UART transfer is on-going */ 
  while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_BUSY) == SET);
  /* make sure that UART is ready to receive
   * (test carried out again later in HAL_UARTEx_StopModeWakeUpSourceConfig) */      
  while(__HAL_UART_GET_FLAG(&UartHandle, USART_ISR_REACK) == RESET);
    
  /* set the wake-up event:  
   * specify address-to-match type. 
   * The address is 0x2, meaning the character triggering the 
   * address match is 0x82 */
  WakeUpSelection.WakeUpEvent = UART_WAKEUP_ON_ADDRESS;
  WakeUpSelection.AddressLength = UART_ADDRESS_DETECT_4B; 
  WakeUpSelection.Address = 0x2;  
  if (HAL_UARTEx_StopModeWakeUpSourceConfig(&UartHandle, WakeUpSelection)!= HAL_OK)
  {
    Error_Handler(); 
  }

  /* Enable the UART Wake UP from stop mode Interrupt */
  __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_WUF);
  
  /* about to enter stop mode: switch off LED */
  BSP_LED_Off(LED3);
  /* enable MCU wake-up by UART */
  HAL_UARTEx_EnableStopMode(&UartHandle); 
  /* enter stop mode */
  HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);

  /* ... STOP mode ... */
  
  SystemClock_Config_fromSTOP();
  /* at that point, MCU has been awoken: the LED has been turned back on */
  /* Wake Up on 4-bit address detection successful */ 
  /* wait for some delay */
  HAL_Delay(100);
  /* Inform other board that wake up is successful */
  if (HAL_UART_Transmit(&UartHandle, (uint8_t*)aTxBuffer4, COUNTOF(aTxBuffer4)-1, 5000)!= HAL_OK)  
  {
    Error_Handler();
  } 

  
#else

/* initialize the User push-button in Interrupt mode */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);
  
  /* Wait for User push-button press before starting the test.
     In the meantime, LED3 is blinking */
  while(UserButtonStatus == 0)
  {
      /* Toggle LED3 */
      BSP_LED_Toggle(LED3); 
      HAL_Delay(100);
  }

  
  
  /*##-2- Send the wake-up from stop mode first trigger ######################*/
  /*      (RXNE flag setting)                                                 */
  BSP_LED_On(LED3);
  if(HAL_UART_Transmit(&UartHandle, (uint8_t*)aWakeUpTrigger1, COUNTOF(aWakeUpTrigger1)-1, 5000)!= HAL_OK)
  {
    Error_Handler();
  }
  
  /* Put UART peripheral in reception process to wait for other board
     wake up confirmation */  
  if(HAL_UART_Receive(&UartHandle, (uint8_t *)aRxBuffer, COUNTOF(aTxBuffer1)-1, 10000) != HAL_OK)
  {
    Error_Handler();
  } 
  BSP_LED_Off(LED3);
   
  /* Compare the expected and received buffers */
  if(Buffercmp((uint8_t*)aTxBuffer1,(uint8_t*)aRxBuffer,COUNTOF(aTxBuffer1)-1))
  {
    Error_Handler();
  } 

  /* wait for two seconds before test second step */
  HAL_Delay(2000);
  
  /*##-3- Send the wake-up from stop mode second trigger #####################*/
  /*      (start Bit detection)                                               */
  BSP_LED_On(LED3);  
  if(HAL_UART_Transmit(&UartHandle, (uint8_t*)aWakeUpTrigger2, COUNTOF(aWakeUpTrigger2)-1, 5000)!= HAL_OK)
  {
    Error_Handler();
  }

  /* Put UART peripheral in reception process to wait for other board
     wake up confirmation */  
  if(HAL_UART_Receive(&UartHandle, (uint8_t *)aRxBuffer, COUNTOF(aTxBuffer2)-1, 10000) != HAL_OK)
  {
    Error_Handler();
  } 
  BSP_LED_Off(LED3);
   
  /* Compare the expected and received buffers */
  if(Buffercmp((uint8_t*)aTxBuffer2,(uint8_t*)aRxBuffer,COUNTOF(aTxBuffer2)-1))
  {
    Error_Handler();
  } 

  /* wait for two seconds before test third step */
  HAL_Delay(2000);


  /*##-4- Send the wake-up from stop mode third trigger ######################*/
  /*      (7-bit address match)                                               */ 
  BSP_LED_On(LED3);  
  if(HAL_UART_Transmit(&UartHandle, (uint8_t*)aWakeUpTrigger3, 1, 5000)!= HAL_OK)
  {
    Error_Handler();
  }
 
  /* Put UART peripheral in reception process to wait for other board
     wake up confirmation */  
  if(HAL_UART_Receive(&UartHandle, (uint8_t *)aRxBuffer, COUNTOF(aTxBuffer3)-1, 10000) != HAL_OK)
  {
    Error_Handler();
  } 
  BSP_LED_Off(LED3);
   
  /* Compare the expected and received buffers */
  if(Buffercmp((uint8_t*)aTxBuffer3,(uint8_t*)aRxBuffer,COUNTOF(aTxBuffer3)-1))
  {
    Error_Handler();
  } 

  /* wait for two seconds before test fourth and last step */
  HAL_Delay(2000);


  /*##-5- Send the wake-up from stop mode fourth trigger #####################*/
  /*      (4-bit address match)                                               */  
  BSP_LED_On(LED3); 
  if(HAL_UART_Transmit(&UartHandle, (uint8_t*)aWakeUpTrigger4, 1, 5000)!= HAL_OK)
  {
    Error_Handler();
  }
 
  
  /* Put UART peripheral in reception process to wait for other board
     wake up confirmation */  
  if(HAL_UART_Receive(&UartHandle, (uint8_t *)aRxBuffer, COUNTOF(aTxBuffer4)-1, 10000) != HAL_OK)
  {
    Error_Handler();
  } 
  BSP_LED_Off(LED3);
   
  /* Compare the expected and received buffers */
  if(Buffercmp((uint8_t*)aTxBuffer4,(uint8_t*)aRxBuffer,COUNTOF(aTxBuffer4)-1))
  {
    Error_Handler();
  } 

  HAL_Delay(2000);

#endif /* BOARD_IN_STOP_MODE */


  
  /* Turn on LED3 if test passes then enter infinite loop */
  BSP_LED_On(LED3); 
  while (1)
  {
  }
}
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure LED3 and LED4 */
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED4);

  /* Configure the system clock to 180 MHz */
  SystemClock_Config();
  
  /*##-1- Configure the SPI peripheral #######################################*/
  /* Set the SPI parameters */
  SpiHandle.Instance               = SPIx;
  SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
  SpiHandle.Init.Direction         = SPI_DIRECTION_2LINES;
  SpiHandle.Init.CLKPhase          = SPI_PHASE_1EDGE;
  SpiHandle.Init.CLKPolarity       = SPI_POLARITY_HIGH;
  SpiHandle.Init.CRCCalculation    = SPI_CRCCALCULATION_DISABLE;
  SpiHandle.Init.CRCPolynomial     = 7;
  SpiHandle.Init.DataSize          = SPI_DATASIZE_8BIT;
  SpiHandle.Init.FirstBit          = SPI_FIRSTBIT_MSB;
  SpiHandle.Init.NSS               = SPI_NSS_SOFT;
  SpiHandle.Init.TIMode            = SPI_TIMODE_DISABLE;
  
#ifdef MASTER_BOARD
  SpiHandle.Init.Mode = SPI_MODE_MASTER;
#else
  SpiHandle.Init.Mode = SPI_MODE_SLAVE;
#endif /* MASTER_BOARD */

  if(HAL_SPI_Init(&SpiHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }
  
#ifdef MASTER_BOARD
  /* Configure USER Button */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);

  /* Wait for USER Button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_KEY) != 1)
  {
    BSP_LED_Toggle(LED3);
    HAL_Delay(40);
  }
  
    BSP_LED_Off(LED3);
#endif /* MASTER_BOARD */

  /*##-2- Start the Full Duplex Communication process ########################*/  
  /* While the SPI in TransmitReceive process, user can transmit data through 
     "aTxBuffer" buffer & receive data through "aRxBuffer" */
  if(HAL_SPI_TransmitReceive_DMA(&SpiHandle, (uint8_t*)aTxBuffer, (uint8_t *)aRxBuffer, BUFFERSIZE) != HAL_OK)
  {
    /* Transfer error in transmission process */
    Error_Handler();
  }

  /*##-3- Wait for the end of the transfer ###################################*/  
  /*  Before starting a new communication transfer, you need to check the current   
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the 
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */  
  while (HAL_SPI_GetState(&SpiHandle) != HAL_SPI_STATE_READY)
  {
  } 

  /*##-4- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer, (uint8_t*)aRxBuffer, BUFFERSIZE))
  {
    /* Transfer error in transmission process */
    Error_Handler();
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #30
0
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
  BSP_LED_Toggle(LED_GREEN);
  return;
}