首页 > 代码库 > 利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(2)【非dma和中断方式】

利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(2)【非dma和中断方式】

上回讲到怎么采集一路的adc的数据,这次我们来采集两路的数据。

技术分享

技术分享

现在直接修改原先的代码

/* Private variables ---------------------------------------------------------*/
uint16_t AD_Value_Buf[2];
uint16_t AD_X_Value = 0;
uint16_t AD_Y_Value = 0;
/* USER CODE END PV */
/* USER CODE BEGIN 3 */
  for(uint8_t i=0;i<2;i++)
  {
      /*##-1- Start the conversion process #######################################*/   
    HAL_ADC_Start(&hadc1);//<为启动ADC装换
    /*##-2- Wait for the end of conversion #####################################*/ 
    /**
     *   Before starting a new conversion, you need to check the current state of
     *   the peripheral; if it’s busy you need to wait for the end of current
     *   conversion before starting a new one.
     *   For simplicity reasons, this example is just waiting till the end of the
     *   conversion, but application may perform other tasks while conversion
     *   operation is ongoing. 
     */
    HAL_ADC_PollForConversion(&hadc1, 50);//<表示等待转换完成,第二个参数表示超时时间,单位ms.
    /* Check if the continous conversion of regular channel is finished */
    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC)) 
    {

        /*##-3- Get the converted value of regular channel  ######################*/
        AD_Value_Buf[i] = HAL_ADC_GetValue(&hadc1);
        #ifdef RTT_LOG_ENABLED
        loge("AD_Value_Buf[%d] %d",i,AD_Value_Buf[i]);
        #endif//RTT_LOG_ENABLED
    }  
  }

    HAL_ADC_Stop(&hadc1);

 现在测测一下

技术分享

现在和我们的HID的报告相结合

  mouseHID.buttons = 0;
  mouseHID.x = 0;
  mouseHID.y = 0;
  mouseHID.wheel = 0;
    AD_X_Value = http://www.mamicode.com/AD_Value_Buf[0];
    AD_Y_Value = AD_Value_Buf[1];
    #ifdef RTT_LOG_ENABLED
    loge("AD_X_Value %d",AD_X_Value);
    loge("AD_Y_Value %d",AD_Y_Value);
   #endif//RTT_LOG_ENABLED
// Send HID report mouseHID.x = AD_Value_map(AD_X_Value,0,4095,-20,20);//从0-4095映射到-20~20 mouseHID.y = AD_Value_map(AD_Y_Value,0,4095,20,-20);//从0-4095映射到20~-20 USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t*)&mouseHID, sizeof(struct mouseHID_t));
/* USER CODE BEGIN 0 */
int16_t AD_Value_map(int16_t x, int16_t in_min, int16_t in_max, int16_t out_min, int16_t out_max)
{
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}     
/* USER CODE END 0 */

 

利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(2)【非dma和中断方式】