// TODO: Packet RX timeout, buffer full check?
void uartRxCompleteCallback(Client* c)
{
	static uint8_t packetCount = 0;
	static uint8_t rxState = RX_PACKET_IDLE;

	c->rxBuffer[packetCount++] = c->rxByte;
	switch (rxState)
	{
	case RX_PACKET_IDLE:
		rxState = RX_PACKET_GOTLENGTH;
		break;
	case RX_PACKET_GOTLENGTH:
		rxState = RX_PACKET_GOTCOMMAND;
		break;
	case RX_PACKET_GOTCOMMAND:
		; // has to be here, otherwise 'deceleration after label' error
		uint8_t packetLength = c->rxBuffer[0];
		if (packetCount == packetLength + 1) // Got rest of packet
		{
			packetCount = 0;
			// Integrity checking
			uint32_t crcRx = c->rxBuffer[packetLength - 3] | (c->rxBuffer[packetLength - 2] << 8)
					| (c->rxBuffer[packetLength - 1] << 16) | (c->rxBuffer[packetLength] << 24);
			uint32_t crcCode = HAL_CRC_Calculate(c->peripheral_CRC, (uint32_t*)(c->rxBuffer), packetLength - 3);
			crcCode ^= 0xffffffff;
			if (crcRx == crcCode) // validate packet
			{
				rxHandlePacket(c, c->rxBuffer);
			}
			rxState = RX_PACKET_IDLE;
		}
		break;
	}
	HAL_UART_Receive_IT(c->peripheral_UART, &c->rxByte, 1);
}
static bool writePacket(Client* c, uint8_t command, uint8_t* payload, uint8_t pLength)
{
	c->workBuffer[0] = pLength + 5;
	c->workBuffer[1] = command;
	if (payload != NULL)
	{
		for (uint8_t i = 2; i < pLength + 2; i++)
		{
			c->workBuffer[i] = payload[i - 2];
		}
	}
	uint32_t crcCode = HAL_CRC_Calculate(c->peripheral_CRC, (uint32_t*)(c->workBuffer), pLength + 2);
	crcCode ^= 0xffffffff;
	c->workBuffer[pLength + 2] = crcCode & 0x000000FF;
	c->workBuffer[pLength + 3] = (crcCode & 0x0000FF00) >> 8;
	c->workBuffer[pLength + 4] = (crcCode & 0x00FF0000) >> 16;
	c->workBuffer[pLength + 5] = (crcCode & 0xFF000000) >> 24;

	// see if packet will fit in transmit buffer
	if ((int)(pLength) + 6 > 256 - c->txBuf.available(&c->txBuf))
	{
		return false;
	}

	// write packet into tx buffer
	for (int i = 0; i < pLength + 6; i++)
	{
		c->txBuf.Buf[c->txBuf.pT++] = c->workBuffer[i];
	}
	c->txBuf.isFull = (c->txBuf.pT == c->txBuf.pH);

	startTX(c, false, true, false);

	return true;
}
Exemple #3
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data 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.
       - Set NVIC Group Priority to 4
       - Low Level Initialization: global MSP (MCU Support Package) initialization
     */
  HAL_Init();

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

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

  /*##-1- Configure the CRC peripheral #######################################*/
  CrcHandle.Instance = CRC;

  if (HAL_CRC_Init(&CrcHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /*##-2- Compute the CRC of "aDataBuffer" ###################################*/
  uwCRCValue = HAL_CRC_Calculate(&CrcHandle, (uint32_t *)aDataBuffer, BUFFER_SIZE);

  /*##-3- Compare the CRC value to the Expected one ##########################*/
  if (uwCRCValue != uwExpectedCRCValue)
  {
    /* Wrong CRC value: Turn LED3 on */
    Error_Handler();
  }
  else
  {
    /* Right CRC value: Turn LED1 on */
    BSP_LED_On(LED1);
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Exemple #4
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Enable the CPU Cache */
  CPU_CACHE_Enable();

  /* STM32F7xx HAL library initialization:
       - Configure the Flash ART accelerator on ITCM interface
       - 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 216 MHz */
  SystemClock_Config();

  /* Since MFX is used, LED init is done after clock config */
  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);

  /*##-1- Configure the CRC peripheral #######################################*/
  CrcHandle.Instance = CRC;

  /* The default polynomial is not used. It is required to defined it in CrcHandle.Init.GeneratingPolynomial*/  
  CrcHandle.Init.DefaultPolynomialUse    = DEFAULT_POLYNOMIAL_DISABLE;
  
  /* Set the value of the polynomial */
  CrcHandle.Init.GeneratingPolynomial    = CRC_POLYNOMIAL_8B;
  
  /* The size of the polynomial to configure the IP is 8b*/
  CrcHandle.Init.CRCLength               = CRC_POLYLENGTH_8B;

  /* The default init value is used */
  CrcHandle.Init.DefaultInitValueUse     = DEFAULT_INIT_VALUE_ENABLE;

  /* The input data are not inverted */
  CrcHandle.Init.InputDataInversionMode  = CRC_INPUTDATA_INVERSION_NONE;

  /* The output data are not inverted */
  CrcHandle.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_DISABLE;

  /* The input data are 32 bits lenght */
  CrcHandle.InputDataFormat              = CRC_INPUTDATA_FORMAT_WORDS;

  if (HAL_CRC_Init(&CrcHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /*##-2- Compute the CRC of "aDataBuffer" ###################################*/
  uwCRCValue = HAL_CRC_Calculate(&CrcHandle, (uint32_t *)&aDataBuffer, BUFFER_SIZE);

  /*##-3- Compare the CRC value to the Expected one ##########################*/
  if (uwCRCValue != uwExpectedCRCValue)
  {
    /* Wrong CRC value: Turn LED3 on */
    Error_Handler();
  }
  else
  {
    /* Right CRC value: Turn LED1 on */
    BSP_LED_On(LED1);
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Exemple #5
0
/**
  * @brief  Receive a packet from sender
  * @param  data
  * @param  length
  *     0: end of transmission
  *     2: abort by sender
  *    >0: packet length
  * @param  timeout
  * @retval HAL_OK: normally return
  *         HAL_BUSY: abort by user
  */
static HAL_StatusTypeDef ReceivePacket(uint8_t *p_data, uint32_t *p_length, uint32_t timeout)
{
  uint32_t crc;
  uint32_t packet_size = 0;
  HAL_StatusTypeDef status;
  uint8_t char1;

  *p_length = 0;
  status = HAL_UART_Receive(&huart2, &char1, 1, timeout);

  if (status == HAL_OK)
  {
    switch (char1)
    {
      case SOH:
        packet_size = PACKET_SIZE;
        break;
      case STX:
        packet_size = PACKET_1K_SIZE;
        break;
      case EOT:
        break;
      case CA:
        if ((HAL_UART_Receive(&huart2, &char1, 1, timeout) == HAL_OK) && (char1 == CA))
        {
          packet_size = 2;
        }
        else
        {
          status = HAL_ERROR;
        }
        break;
      case ABORT1:
      case ABORT2:
        status = HAL_BUSY;
        break;
      default:
        status = HAL_ERROR;
        break;
    }
    *p_data = char1;

    if (packet_size >= PACKET_SIZE )
    {
      status = HAL_UART_Receive(&huart2, &p_data[PACKET_NUMBER_INDEX], packet_size + PACKET_OVERHEAD_SIZE, timeout);

      /* Simple packet sanity check */
      if (status == HAL_OK )
      {
        if (p_data[PACKET_NUMBER_INDEX] != ((p_data[PACKET_CNUMBER_INDEX]) ^ NEGATIVE_BYTE))
        {
          packet_size = 0;
          status = HAL_ERROR;
        }
        else
        {
          /* Check packet CRC */
          crc = p_data[ packet_size + PACKET_DATA_INDEX ] << 8;
          crc += p_data[ packet_size + PACKET_DATA_INDEX + 1 ];
          if (HAL_CRC_Calculate(&hcrc, (uint32_t*)&p_data[PACKET_DATA_INDEX], packet_size) != crc )
          {
            packet_size = 0;
            status = HAL_ERROR;
          }
        }
      }
      else
      {
        packet_size = 0;
      }
    }
  }
  *p_length = packet_size;
  return status;
}
Exemple #6
0
/**
 * @brief  Computes the 32-bit CRC of a given buffer of data word(32-bit).
 * @param  pBuf: pointer to the buffer containing the data to be computed
 * @param  length: length of the buffer to be computed
 * @retval 32-bit CRC
 */
static inline uint32_t crcCRC32(uint32_t pBuf[], uint32_t length)
{
    return HAL_CRC_Calculate(&hcrc, pBuf, length);
}
Exemple #7
0
/**
  * @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();

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

  /* Configure LED2 */
  BSP_LED_Init(LED2);

  /*##-1- Configure the CRC peripheral #######################################*/
  CrcHandle.Instance = CRC;

  /* The default polynomial is used */
  CrcHandle.Init.DefaultPolynomialUse    = DEFAULT_POLYNOMIAL_ENABLE;

  /* The default init value is used */
  CrcHandle.Init.DefaultInitValueUse     = DEFAULT_INIT_VALUE_ENABLE;

  /* The input data are not inverted */
  CrcHandle.Init.InputDataInversionMode  = CRC_INPUTDATA_INVERSION_NONE;

  /* The output data are not inverted */
  CrcHandle.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_DISABLE;

  /* The input data are 32-bit long words */
  CrcHandle.InputDataFormat              = CRC_INPUTDATA_FORMAT_WORDS;

  if (HAL_CRC_Init(&CrcHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /*##-2- Compute the CRC of "aDataBuffer" ###################################*/
  uwCRCValue = HAL_CRC_Calculate(&CrcHandle, (uint32_t *)aDataBuffer, BUFFER_SIZE);

  /*##-3- Compare the CRC value to the Expected one ##########################*/
  if (uwCRCValue != uwExpectedCRCValue)
  {
    /* Wrong CRC value: enter Error_Handler */
    Error_Handler();
  }
  else
  {
    /* Right CRC value: Turn LED2 on */
    BSP_LED_On(LED2);
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Exemple #8
0
/**
  * @brief  Transmit a file using the ymodem protocol
  * @param  p_buf: Address of the first byte
  * @param  p_file_name: Name of the file sent
  * @param  file_size: Size of the transmission
  * @retval COM_StatusTypeDef result of the communication
  */
COM_StatusTypeDef Ymodem_Transmit (uint8_t *p_buf, const uint8_t *p_file_name, uint32_t file_size)
{
  uint32_t errors = 0, ack_recpt = 0, size = 0, pkt_size;
  uint8_t *p_buf_int;
  COM_StatusTypeDef result = COM_OK;
  uint32_t blk_number = 1;
  uint8_t a_rx_ctrl[2];
  uint8_t i;
#ifdef CRC16_F    
  uint32_t temp_crc;
#else /* CRC16_F */   
  uint8_t temp_chksum;
#endif /* CRC16_F */  

  /* Prepare first block - header */
  PrepareIntialPacket(aPacketData, p_file_name, file_size);

  while (( !ack_recpt ) && ( result == COM_OK ))
  {
    /* Send Packet */
    HAL_UART_Transmit(&huart2, &aPacketData[PACKET_START_INDEX], PACKET_SIZE + PACKET_HEADER_SIZE, NAK_TIMEOUT);

    /* Send CRC or Check Sum based on CRC16_F */
#ifdef CRC16_F    
    temp_crc = HAL_CRC_Calculate(&hcrc, (uint32_t*)&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
    Serial_PutByte(temp_crc >> 8);
    Serial_PutByte(temp_crc & 0xFF);
#else /* CRC16_F */   
    temp_chksum = CalcChecksum (&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
    Serial_PutByte(temp_chksum);
#endif /* CRC16_F */

    /* Wait for Ack and 'C' */
    if (HAL_UART_Receive(&huart2, &a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK)
    {
      if (a_rx_ctrl[0] == ACK)
      {
        ack_recpt = 1;
      }
      else if (a_rx_ctrl[0] == CA)
      {
        if ((HAL_UART_Receive(&huart2, &a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK) && (a_rx_ctrl[0] == CA))
        {
          HAL_Delay( 2 );
          __HAL_UART_FLUSH_DRREGISTER(&huart2);
          __HAL_UART_CLEAR_IT(&huart2, UART_CLEAR_OREF);
          result = COM_ABORT;
        }
      }
    }
    else
    {
      errors++;
    }
    if (errors >= MAX_ERRORS)
    {
      result = COM_ERROR;
    }
  }

  p_buf_int = p_buf;
  size = file_size;

  /* Here 1024 bytes length is used to send the packets */
  while ((size) && (result == COM_OK ))
  {
    /* Prepare next packet */
    PreparePacket(p_buf_int, aPacketData, blk_number, size);
    ack_recpt = 0;
    a_rx_ctrl[0] = 0;
    errors = 0;

    /* Resend packet if NAK for few times else end of communication */
    while (( !ack_recpt ) && ( result == COM_OK ))
    {
      /* Send next packet */
      if (size >= PACKET_1K_SIZE)
      {
        pkt_size = PACKET_1K_SIZE;
      }
      else
      {
        pkt_size = PACKET_SIZE;
      }

      HAL_UART_Transmit(&huart2, &aPacketData[PACKET_START_INDEX], pkt_size + PACKET_HEADER_SIZE, NAK_TIMEOUT);
      
      /* Send CRC or Check Sum based on CRC16_F */
#ifdef CRC16_F    
      temp_crc = HAL_CRC_Calculate(&hcrc, (uint32_t*)&aPacketData[PACKET_DATA_INDEX], pkt_size);
      Serial_PutByte(temp_crc >> 8);
      Serial_PutByte(temp_crc & 0xFF);
#else /* CRC16_F */   
      temp_chksum = CalcChecksum (&aPacketData[PACKET_DATA_INDEX], pkt_size);
      Serial_PutByte(temp_chksum);
#endif /* CRC16_F */
      
      /* Wait for Ack */
      if ((HAL_UART_Receive(&huart2, &a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK) && (a_rx_ctrl[0] == ACK))
      {
        ack_recpt = 1;
        if (size > pkt_size)
        {
          p_buf_int += pkt_size;
          size -= pkt_size;
          if (blk_number == (USER_FLASH_SIZE / PACKET_1K_SIZE))
          {
            result = COM_LIMIT; /* boundary error */
          }
          else
          {
            blk_number++;
          }
        }
        else
        {
          p_buf_int += pkt_size;
          size = 0;
        }
      }
      else
      {
        errors++;
      }

      /* Resend packet if NAK  for a count of 10 else end of communication */
      if (errors >= MAX_ERRORS)
      {
        result = COM_ERROR;
      }
    }
  }

  /* Sending End Of Transmission char */
  ack_recpt = 0;
  a_rx_ctrl[0] = 0x00;
  errors = 0;
  while (( !ack_recpt ) && ( result == COM_OK ))
  {
    Serial_PutByte(EOT);

    /* Wait for Ack */
    if (HAL_UART_Receive(&huart2, &a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK)
    {
      if (a_rx_ctrl[0] == ACK)
      {
        ack_recpt = 1;
      }
      else if (a_rx_ctrl[0] == CA)
      {
        if ((HAL_UART_Receive(&huart2, &a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK) && (a_rx_ctrl[0] == CA))
        {
          HAL_Delay( 2 );
          __HAL_UART_FLUSH_DRREGISTER(&huart2);
          __HAL_UART_CLEAR_IT(&huart2, UART_CLEAR_OREF);
          result = COM_ABORT;
        }
      }
    }
    else
    {
      errors++;
    }

    if (errors >=  MAX_ERRORS)
    {
      result = COM_ERROR;
    }
  }

  /* Empty packet sent - some terminal emulators need this to close session */
  if ( result == COM_OK )
  {
    /* Preparing an empty packet */
    aPacketData[PACKET_START_INDEX] = SOH;
    aPacketData[PACKET_NUMBER_INDEX] = 0;
    aPacketData[PACKET_CNUMBER_INDEX] = 0xFF;
    for (i = PACKET_DATA_INDEX; i < (PACKET_SIZE + PACKET_DATA_INDEX); i++)
    {
      aPacketData [i] = 0x00;
    }

    /* Send Packet */
    HAL_UART_Transmit(&huart2, &aPacketData[PACKET_START_INDEX], PACKET_SIZE + PACKET_HEADER_SIZE, NAK_TIMEOUT);

    /* Send CRC or Check Sum based on CRC16_F */
#ifdef CRC16_F    
    temp_crc = HAL_CRC_Calculate(&hcrc, (uint32_t*)&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
    Serial_PutByte(temp_crc >> 8);
    Serial_PutByte(temp_crc & 0xFF);
#else /* CRC16_F */   
    temp_chksum = CalcChecksum (&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
    Serial_PutByte(temp_chksum);
#endif /* CRC16_F */

    /* Wait for Ack and 'C' */
    if (HAL_UART_Receive(&huart2, &a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK)
    {
      if (a_rx_ctrl[0] == CA)
      {
          HAL_Delay( 2 );
          __HAL_UART_FLUSH_DRREGISTER(&huart2);
          __HAL_UART_CLEAR_IT(&huart2, UART_CLEAR_OREF);
          result = COM_ABORT;
      }
    }
  }
Exemple #9
0
uint32_t BL_crc_calccrc32(uint32_t *data, uint32_t len)
{
    return(HAL_CRC_Calculate(&hcrc, data, len));
}
Exemple #10
0
/* 发送采样数据 */
static void send_capture_data(void)
{
    uint32_T type = 0;

    /* 避免函数退出 栈内存被破坏(DMA传输 要求内存数据保持) */
    static uint8_T frame_buf[COMM_FRAME_CAPTURE_FRAME_MAX_SIZE] = {0};
    uint32_T len = 0;

    uint32_T i = 0;
    uint32_T fill_bytes_count = 0;
    uint32_T crc32_calculated = 0;
    uint32_T now_ms = 0;
    f32_T quat[4] = {0.0f}; 
    f32_T euler[CTRL_EULER_MAX] = {0.0f}; 
    f32_T pid_out[CTRL_EULER_MAX] = {0.0f}; 
    int32_T accelerator_max = 0;
    int32_T accelerator[PWM_MAX] = {0};
    uint32_T *p_ui32 = NULL;
    static uint32_T last_ms = 0;

    /* 无帧可发 */
    if(!(s_send_interval
    || s_send_accelerator_flag
    || s_send_dmp_quat_flag
    || s_send_euler_flag
    || s_send_pid_flag))
    {
        return;
    }

    /* 可以发送 */
    now_ms = HAL_GetTick();
    if(now_ms - last_ms > s_send_interval)
    {
        /* 上行且有传感数据长度32 */
        type = COMM_FRAME_SENSOR_DATA_BIT
             | COMM_FRAME_DIRECTION_BIT;

        /* 跳过type和len域 */
        len += 8;

        /* 填充时间 */
        frame_buf[len++] = (uint8_T)(now_ms >> 24);
        frame_buf[len++] = (uint8_T)((now_ms >> 16));
        frame_buf[len++] = (uint8_T)((now_ms >> 8));
        frame_buf[len++] = (uint8_T)(now_ms); 

        if(s_send_dmp_quat_flag)
        {
            mpu9250_get_quat(quat);
#if 0
            /* 调试上位机绘图基准 */
            quat[0] = 1.0f;
            quat[1] = 0.0f;
            quat[2] = 0.0f;
            quat[3] = 0.0f;
#endif
            p_ui32 = (uint32_T *)quat;
            for(i = 0; i < 4; i++) 
            {
                frame_buf[len++] = (uint8_T)( (uint32_T)p_ui32[i] >> 24);
                frame_buf[len++] = (uint8_T)(((uint32_T)p_ui32[i] >> 16));
                frame_buf[len++] = (uint8_T)(((uint32_T)p_ui32[i] >> 8));
                frame_buf[len++] = (uint8_T)( (uint32_T)p_ui32[i]);
            }

            type |= COMM_FRAME_DMP_QUAT_BIT;
        } 

        /* 油门数据 */
        if(s_send_accelerator_flag)
        { 
            ctrl_get_acceleralor(accelerator, &accelerator_max);

            for(i = 0; i < PWM_MAX; i++) 
            { 
                frame_buf[len++] = (uint8_T)(accelerator[i] >> 24);
                frame_buf[len++] = (uint8_T)(accelerator[i] >> 16);
                frame_buf[len++] = (uint8_T)(accelerator[i] >> 8);
                frame_buf[len++] = (uint8_T)(accelerator[i]);
            } 
            
            frame_buf[len++] = (uint8_T)(accelerator_max >> 24);
            frame_buf[len++] = (uint8_T)(accelerator_max >> 16);
            frame_buf[len++] = (uint8_T)(accelerator_max >> 8);
            frame_buf[len++] = (uint8_T)(accelerator_max);

            type |= COMM_FRAME_ACCELERATOR_DATA_BIT;
        }

        /* 欧拉角 */
        if(s_send_euler_flag)
        { 
            mpu9250_get_quat(quat);
            math_quaternion2euler(euler, quat);

            p_ui32 = (uint32_T *)euler;
            for(i = 0; i < CTRL_EULER_MAX; i++) 
            {
                frame_buf[len++] = (uint8_T)(p_ui32[i] >> 24);
                frame_buf[len++] = (uint8_T)(p_ui32[i] >> 16);
                frame_buf[len++] = (uint8_T)(p_ui32[i] >> 8);
                frame_buf[len++] = (uint8_T)(p_ui32[i]);
            }

            type |= COMM_FRAME_EULER_DATA_BIT;
        }

        /* pid数据 */
        if(s_send_pid_flag)
        { 
            ctrl_get_pid_out(pid_out);
            p_ui32 = (uint32_T *)pid_out;
            for(i = 0; i < CTRL_EULER_MAX; i++) 
            {
                frame_buf[len++] = (uint8_T)(p_ui32[i] >> 24);
                frame_buf[len++] = (uint8_T)(p_ui32[i] >> 16);
                frame_buf[len++] = (uint8_T)(p_ui32[i] >> 8);
                frame_buf[len++] = (uint8_T)(p_ui32[i]);
            }

            type |= COMM_FRAME_PID_DATA_BIT;
        }

        /* 填充 */
        fill_bytes_count = len & 0x03;
        for(i = 0; i < fill_bytes_count; i++)
        {
            frame_buf[len++] = COMM_FRAME_FILLED_VAL;
        }

        /* 填写type域 */
        frame_buf[0] = (uint8_T)(type >> 24);
        frame_buf[1] = (uint8_T)(type >> 16);
        frame_buf[2] = (uint8_T)(type >> 8);
        frame_buf[3] = (uint8_T)(type);

        /* 计入crc长度 */
        len += 4;
				len -= 8; /* len中长度值不包括type+len */
        /* 填写len域 */
        frame_buf[4] = (uint8_T)(len >> 24);
        frame_buf[5] = (uint8_T)(len >> 16);
        frame_buf[6] = (uint8_T)(len >> 8);
        frame_buf[7] = (uint8_T)(len);
        
        /* len偏移到crc位置 */
        len += 4;
        /* 计算校验 */
        crc32_calculated = HAL_CRC_Calculate(&s_crc, (uint32_T *)frame_buf, len / 4); 
        frame_buf[len++] = (uint8_T)(crc32_calculated >> 24);
        frame_buf[len++] = (uint8_T)(crc32_calculated >> 16);
        frame_buf[len++] = (uint8_T)(crc32_calculated >> 8);
        frame_buf[len++] = (uint8_T)(crc32_calculated);

        /* 发帧 */
        if(len > COMM_FRAME_SENDED_MIN)
        {
#if 0
            /* 出错 用于检查 crc是否为0 */
            if(0 == frame_buf[n-1])
            {
                ERR_STR("crc错误.");
            }
#endif
            uart_send_bytes((drv_uart_T *)s_comm_uart, frame_buf, len);
            last_ms = now_ms;
        }
    }
Exemple #11
0
static bool_T parse(const uint8_T *buf)
{ 
    bool_T has_capture_data = FALSE;
    comm_frame_T frame = {0};
    uint32_T crc32_calculated = 0;

    frame.type  = buf[0] << 24;
    frame.type |= buf[1] << 16;
    frame.type |= buf[2] << 8;
    frame.type |= buf[3];

    frame.len   = buf[4] << 24;
    frame.len  |= buf[5] << 16;
    frame.len  |= buf[6] << 8;
    frame.len  |= buf[7];

    frame.crc   = buf[COMM_DOWN_FRAME_BUF_SIZE - 4] << 24;
    frame.crc  |= buf[COMM_DOWN_FRAME_BUF_SIZE - 3] << 16;
    frame.crc  |= buf[COMM_DOWN_FRAME_BUF_SIZE - 2] << 8;
    frame.crc  |= buf[COMM_DOWN_FRAME_BUF_SIZE - 1];

    /* 长度检查 固定长度 data+crc32 8Bytes */
    if(COMM_DOWN_FRAME_DATA_AND_CRC32_SIZE != frame.len) /* 错误帧 不处理 */
    {
        return FALSE;
    }

    /* CRC检查 */ 
    crc32_calculated = HAL_CRC_Calculate(&s_crc, (uint32_T *)buf, COMM_DOWN_FRAME_BUF_SIZE / sizeof(uint32_T) - 1); 
    if(crc32_calculated != frame.crc) /* 校验失败*/
    {
        return FALSE;
    }

    /* 类型检查 */ 
    if(!is_down_frame(frame.type)) /* 错 收到上行帧 */
    {
        return FALSE;
    }
   
    /* 采样请求帧 */
    if(is_sensor_data_frame(frame.type))
    { 
        /* 获取采样间隔 */
        s_send_interval  = buf[8] << 24;
        s_send_interval |= buf[9] << 16;
        s_send_interval |= buf[10] << 8;
        s_send_interval |= buf[11]; 
        
        /* 限制时间间隔(无符号32位 必然大于0不用比下界) */
        if(s_send_interval > COMM_FRAME_INTERVAL_MAX)
        {
            s_send_interval = COMM_FRAME_INTERVAL_MAX;
        }

        /* 发送四元数 */
        if(is_dmp_quat_needded(frame.type))
        {
            s_send_dmp_quat_flag = TRUE;
            has_capture_data = TRUE;
        }

        /* 发送油门 */
        if(is_acceletorater_needded(frame.type))
        {
            s_send_accelerator_flag = TRUE;
            has_capture_data = TRUE;
        }

        /* 发送欧拉角 */
        if(is_euler_needded(frame.type))
        {
            s_send_euler_flag = TRUE;
            has_capture_data = TRUE;
        }

        /* 发送PID */
        if(is_pid_needded(frame.type))
        {
            s_send_pid_flag = TRUE;
            has_capture_data = TRUE;
        }

        return has_capture_data;
    }

    /* PID参数设置帧 */
    if(is_pid_frame(frame.type))
    {
        int32_T ctrl_type = buf[8]; 
        int32_T kp_i = 0;
        int32_T ki_i = 0;
        int32_T kd_i = 0;
        int32_T *p_i32 = NULL;
        PID_T pid;

        /* 非法pid帧 */
        if(!((CTRL_THETA == ctrl_type) || (CTRL_PHI == ctrl_type) || (CTRL_PSI == ctrl_type)))
        {
            return FALSE;
        }

        kp_i  = buf[9]  << 24;
        kp_i |= buf[10] << 16;
        kp_i |= buf[11] << 8;
        kp_i |= buf[12];

        ki_i  = buf[13] << 24;
        ki_i |= buf[14] << 16;
        ki_i |= buf[15] << 8;
        ki_i |= buf[16];

        kd_i  = buf[17] << 24;
        kd_i |= buf[18] << 16;
        kd_i |= buf[19] << 8;
        kd_i |= buf[20];

        p_i32 = &kp_i;
        pid.kp = *((f32_T *)p_i32);
        p_i32 = &ki_i;
        pid.ki = *((f32_T *)p_i32);
        p_i32 = &kd_i;
        pid.kd = *((f32_T *)p_i32);
        
        ctrl_set_pid(ctrl_type, &pid);
    }

    /* 飞控帧 */
    if(is_flyer_ctrl_frame(frame.type))
    {
        int32_T ctrl_type = buf[8];
        int32_T val[PWM_MAX] = {0};

        /* return 替代break */
        switch(ctrl_type)
        {
            /* 熄火 */
            case 0x00: 
                { 
                    ctrl_motor_off();
                    return TRUE;
                }

            /* 油门 */
            case 0x01: 
                {
                    for(int32_T i = 0; i < PWM_MAX; i++)
                    {
                        val[i]  = buf[9] << 8;
                        val[i] |= buf[10];
                    }
                    ctrl_set_acceleralor(val);
                    return TRUE;
                }
            /* 错误类型 */
            default:
                return FALSE;
        }
    }

    return FALSE;
}
Exemple #12
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 the system clock to 48 MHz */
  SystemClock_Config();

  /* Configure LED2 */
  BSP_LED_Init(LED2);


  /****************************************************************************/
  /*                                                                          */
  /*                     CRC peripheral initialization                        */
  /*                                                                          */    
  /****************************************************************************/
    
  CrcHandle.Instance = CRC;

  /* The default polynomial is not used. The one to be used must be defined 
     in CrcHandle.Init.GeneratingPolynomial */  
  CrcHandle.Init.DefaultPolynomialUse    = DEFAULT_POLYNOMIAL_DISABLE;
  
  /* Set the value of the generating polynomial. 
    The one used in that example is the 7-bit long CRC generating
    polynomial X^7 + X^6 + X^5 + X^2 + 1 */
  CrcHandle.Init.GeneratingPolynomial    = CRC_POLYNOMIAL_7B;
  
  /* The user-defined generating polynomial yields a 7-bit long CRC */
  CrcHandle.Init.CRCLength               = CRC_POLYLENGTH_7B;

  /* The default init value is used */
  CrcHandle.Init.DefaultInitValueUse     = DEFAULT_INIT_VALUE_ENABLE;

  /* The input data are not inverted */
  CrcHandle.Init.InputDataInversionMode  = CRC_INPUTDATA_INVERSION_NONE;

  /* The output data are not inverted */
  CrcHandle.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_DISABLE;

  /* The input data are bytes (8-bit long data) */
  CrcHandle.InputDataFormat              = CRC_INPUTDATA_FORMAT_BYTES;

  /* De-initialize the CRC peripheral */
  if (HAL_CRC_DeInit(&CrcHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }  

  /* Then, initialize the CRC handle */
  if (HAL_CRC_Init(&CrcHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }


  /****************************************************************************/
  /*                                                                          */
  /*         CRC computation of a first bytes stream                          */
  /*                                                                          */    
  /****************************************************************************/

  /* The 7-bit long CRC of a 5-byte buffer is computed. After IP initialization, 
     the CRC calculator is initialized with the default value that is 0x7F for 
     a 7-bit CRC.
    
    The computed CRC is stored in uint32_t uwCRCValue. The 7-bit long CRC is made of
    uwCRCValue 7 LSB bits. */

  uwCRCValue = HAL_CRC_Accumulate(&CrcHandle, (uint32_t *)&CRC7_DATA8_TEST5, BUFFER_SIZE_5);

  /* Compare the CRC value to the expected one */
  if (uwCRCValue != uwExpectedCRCValue_1)
  {
    /* Wrong CRC value: enter Error_Handler */
    Error_Handler();
  }

  
  /****************************************************************************/
  /*                                                                          */
  /*         CRC computation of a second bytes stream                         */
  /*                                                                          */    
  /****************************************************************************/

  /* The 7-bit long CRC of a 17-byte buffer is computed. The CRC calculator
    is not re-initialized, instead the previously computed CRC is used
    as initial value. */

  uwCRCValue = HAL_CRC_Accumulate(&CrcHandle, (uint32_t *)&CRC7_DATA8_TEST17, BUFFER_SIZE_17);

  /* Compare the CRC value to the expected one */
  if (uwCRCValue != uwExpectedCRCValue_2)
  {
    /* Wrong CRC value: enter Error_Handler */
    Error_Handler();
  }


  /****************************************************************************/
  /*                                                                          */
  /*         CRC computation of a single byte                                 */
  /*                                                                          */    
  /****************************************************************************/

  /* The 7-bit long CRC of a 1-byte buffer is computed. The CRC calculator
    is not re-initialized, instead the previously computed CRC is used
    as initial value. */

  uwCRCValue = HAL_CRC_Accumulate(&CrcHandle, (uint32_t *)&CRC7_DATA8_TEST1, BUFFER_SIZE_1);

  /* Compare the CRC value to the expected one */
  if (uwCRCValue != uwExpectedCRCValue_3)
  {
    /* Wrong CRC value: enter Error_Handler */
    Error_Handler();
  }


  /****************************************************************************/
  /*                                                                          */
  /*         CRC computation of the last bytes stream                         */
  /*                                                                          */    
  /****************************************************************************/

  /* The 7-bit long CRC of a 2-byte buffer is computed. The CRC calculator
    is re-initialized with the default value that is 0x7F for a 7-bit CRC.
    This is done with a call to HAL_CRC_Calculate() instead of 
    HAL_CRC_Accumulate(). */

  uwCRCValue = HAL_CRC_Calculate(&CrcHandle, (uint32_t *)&CRC7_DATA8_TEST2, BUFFER_SIZE_2);

  /* Compare the CRC value to the expected one */
  if (uwCRCValue != uwExpectedCRCValue_4)
  {
    /* Wrong CRC value: enter Error_Handler */
    Error_Handler();
  }
  else
  {
    /* Right CRC value: Turn LED2 on */
    BSP_LED_On(LED2);
  }  


  /* Infinite loop */
  while (1)
  {
  }
}
unsigned long  board_unique_crcid_compute (void *in_buf, int in_buf_length,
                                           int flags_32_8)
{
    unsigned char  *in_buf8;
    unsigned long  *in_buf32;
    unsigned int   crc_input,   i;
    uint32_t       crcResult;

    in_buf8 = (unsigned char*) in_buf;
    if (flags_32_8 == 8)
       { for (i = 0;  i < in_buf_length;  i++)
            u32Buffer[i] = in_buf8[i];  // convert from 8-bit to L.O. 32-bit
            // STM32: generate random seed from CRC unit
         crcResult = HAL_CRC_Accumulate (&CrcHandle, u32Buffer, 6);  // yields 0
         crcResult = HAL_CRC_Calculate (&CrcHandle, u32Buffer, 6);   // ditto WTF
       }
      else
       {    // is already in 32-bit format - use in place
            // STM32: generate random seed from CRC unit
         crcResult = HAL_CRC_Accumulate (&CrcHandle, in_buf,
                                         in_buf_length);  // yields 0
         crcResult = HAL_CRC_Calculate  (&CrcHandle, in_buf,
                                         in_buf_length);  // ditto WTF
       }

    _g_crcid_Result = crcResult;                     // all done, Save results

    return (_g_crcid_Result);
}