1. 程式人生 > >利用STM32CubeMX來生成USB_HID_Mouse工程【添加ADC】(1)

利用STM32CubeMX來生成USB_HID_Mouse工程【添加ADC】(1)

page perf stm32cube ets lar hid data before variable

現在原來的基礎上添加ADC的功能。

現在(利用STM32CubeMX來生成USB_HID_Mouse工程)基礎上新增硬件

JoyStick Shield 遊戲搖桿擴展板

技術分享

與STM32F103C8的連接

目前使用

JoyStick Shield STM32F103C8

X----PA1(ADC1_IN1)

Y----PA2(ADC1_IN2)

好了我們現在STM32CubeMX來打開之前的工程

技術分享

現在我們先設置ADC1_IN1

技術分享

讓我們來看其adc的默認配置

技術分享

現在直接生成工程。

會發現在原來的工程基礎上多了一些ADC的初始化函數等。

現在我們在main.C新增

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
uint16_t AD_X_Value = 0;
/* USER CODE END PV */
/* USER CODE BEGIN 3 */
  
  /*##-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_X_Value = HAL_ADC_GetValue(&hadc1); #ifdef RTT_LOG_ENABLED loge("AD_X_Value %d",AD_X_Value); #endif //RTT_LOG_ENABLED } #if 0 // Send HID report mouseHID.x = 10; USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t*)&mouseHID, sizeof(struct mouseHID_t)); #endif HAL_Delay(1000); } /* USER CODE END 3 */

在加上我喜歡的RTT【不知道RTT的可以參考 [轉]使用RTT(Real-Time Terminal)】

別忘記在main.c加上

/* USER CODE BEGIN Includes */
#include "usbd_hid.h"

#ifdef RTT_LOG_ENABLED
#include "rtt_log.h"
#endif //RTT_LOG_ENABLED

/* USER CODE END Includes */

將在HAL_MspInit()代碼中 __HAL_AFIO_REMAP_SWJ_DISABLE();給註釋掉

下載編譯

我們可以看到x軸變化的時候數據

技術分享

利用STM32CubeMX來生成USB_HID_Mouse工程【添加ADC】(1)