STM32F103 CubeMX ADC 驱动 PS2游戏摇杆控制杆传感器模块
- 1. 工程配置
- 1.1 配置debug口
- 1.2 配置时钟
- 1.3 配置ADC
- 1.4 配置串口
- 1.5 配置时钟
- 1.6 生成工程
- 2. 代码编写
- 2.1 串口代码
- 2.2 ADC读取数据的代码
1. 工程配置
1.1 配置debug口
1.2 配置时钟
1.3 配置ADC
1.4 配置串口
1.5 配置时钟
这里时钟配置成了72M,
1.6 生成工程
2. 代码编写
2.1 串口代码
/* USER CODE BEGIN 0 */
#include <stdio.h>
//重定向c库函数printf到串口USARTx,重定向后可使用printf函数
int fputc(int ch, FILE *f)
{
/* 发送一个字节数据到串口USARTx */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return (ch);
}
/* USER CODE END 0 */
2.2 ADC读取数据的代码
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
//USB 卸载操作,取消按复位键后无法识别的问题
USB_Disconnected();
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC1_Init();
MX_TIM2_Init();
MX_TIM3_Init();
MX_USART1_UART_Init();
MX_USB_DEVICE_Init();
MX_ADC2_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Encoder_Start(&htim2, TIM_CHANNEL_ALL);
HAL_TIM_Encoder_Start(&htim3, TIM_CHANNEL_ALL);
//2.添加数组
unsigned char enter[100] = {0};
uint16_t ADC0_Value=0;
uint16_t ADC1_Value=0;
char ADcKey = 0;
char DirectionA = 0;
short CaptureNumberA =0;
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
//get adc data
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);
ADC0_Value = (uint16_t)HAL_ADC_GetValue(&hadc1);
HAL_ADC_Start(&hadc2);
HAL_ADC_PollForConversion(&hadc2, HAL_MAX_DELAY);
ADC1_Value = (uint16_t)HAL_ADC_GetValue(&hadc2);
ADcKey = HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_8);
//获得脉冲
//DirectionA = __HAL_TIM_IS_TIM_COUNTING_DOWN(&htim2);
CaptureNumberA=__HAL_TIM_GET_COUNTER(&htim2);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(100);
sprintf(enter,"ADC0:%d,ADC1:%d,ADC_key: %d CaptureNumberA:%d \r\n",ADC0_Value,ADC1_Value,ADcKey,CaptureNumberA);
CDC_Transmit_FS(enter,sizeof(enter)); //USB 串口发送数据
}
/* USER CODE END 3 */
}