【STM32学习】(20)STM32实现双轴按键遥感

【STM32学习】(20)STM32实现双轴按键遥感

实物的样子:

使用双路ADC实现对传感器的X和Y方向的值采集。

硬件:STM32L052K8*、双轴按键遥感传感器

接线:

SW 接 PA6

LED灯 接 PA3

开启ADC 1和2通道 对应的IO口请查资料

开启USART1串口 对应的IO口请查资料

使用环境是CubeMX环境创建工程,方法如下:

核心代码如下:

main.c

/* USER CODE BEGIN Header */

/**

******************************************************************************

* @file : main.c

* @brief : Main program body

******************************************************************************

** This notice applies to any and all portions of this file

* that are not between comment pairs USER CODE BEGIN and

* USER CODE END. Other portions of this file, whether

* inserted by the user or by software development tools

* are owned by their respective copyright owners.

*

* COPYRIGHT(c) 2020 STMicroelectronics

*

* Redistribution and use in source and binary forms, with or without modification,

* are permitted provided that the following conditions are met:

* 1. Redistributions of source code must retain the above copyright notice,

* this list of conditions and the following disclaimer.

* 2. Redistributions in binary form must reproduce the above copyright notice,

* this list of conditions and the following disclaimer in the documentation

* and/or other materials provided with the distribution.

* 3. Neither the name of STMicroelectronics nor the names of its contributors

* may be used to endorse or promote products derived from this software

* without specific prior written permission.

*

* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"

* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE

* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE

* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE

* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL

* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR

* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER

* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,

* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*

******************************************************************************

*/

/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/

#include "main.h"

#include "stdio.h"

/* Private includes ----------------------------------------------------------*/

/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/

/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/

/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/

/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

ADC_HandleTypeDef hadc;

DMA_HandleTypeDef hdma_adc;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */

#ifdef _GNUC_

#define PUTCHAR_PROTOTYPE int io_putchar(int ch)

#else

#define PUTCHAR_PROTOTYPE int fputc(int ch,FILE *f)

#endif

PUTCHAR_PROTOTYPE

{

HAL_UART_Transmit(&huart1,(uint8_t *)&ch,1,0XFFFF);

return ch;

}

/* USER CODE END PV */

uint32_t AD_Value[100];

uint8_t i;

uint32_t ad1,ad2;

/* Private function prototypes -----------------------------------------------*/

void SystemClock_Config(void);

static void MX_GPIO_Init(void);

static void MX_DMA_Init(void);

static void MX_USART1_UART_Init(void);

static void MX_ADC_Init(void);

/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**

* @brief The application entry point.

* @retval int

*/

int main(void)

{

/* USER CODE BEGIN 1 */

char flag_key = 0;

char i;

/* 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 */

/* USER CODE END SysInit */

/* Initialize all configured peripherals */

MX_GPIO_Init();

MX_DMA_Init();

MX_USART1_UART_Init();

MX_ADC_Init();

/* USER CODE BEGIN 2 */

HAL_GPIO_WritePin(GPIOA,GPIO_PIN_3,GPIO_PIN_SET);

/* USER CODE END 2 */

printf("\n\r wantin \n\r");

/* Infinite loop */

/* USER CODE BEGIN WHILE */

HAL_ADC_Start_DMA(&hadc,(uint32_t *)&AD_Value,100);

while (1)

{

/* USER CODE END WHILE */

if(HAL_GPIO_ReadPin(KEY_GPIO_Port,KEY_Pin) == 0)

{

HAL_Delay(20);

if(HAL_GPIO_ReadPin(KEY_GPIO_Port,KEY_Pin) == 0)

{

if(0 == flag_key)

{

flag_key = 1;

HAL_GPIO_WritePin(GPIOA,GPIO_PIN_3,GPIO_PIN_RESET);

}

else

{

flag_key = 0;

HAL_GPIO_WritePin(GPIOA,GPIO_PIN_3,GPIO_PIN_SET);

}

}

while(HAL_GPIO_ReadPin(KEY_GPIO_Port,KEY_Pin) == 0);

}

/* USER CODE BEGIN 3 */

HAL_Delay(1000);

for(i=0,ad1=0,ad2=0;i<100;)

{

ad1+=AD_Value[i++];

ad2+=AD_Value[i++];

}

ad1 /= 50;

ad2 /= 50;

printf("\n\r******* ADC DMA ******** \n\r");

printf("\n\rJOY_X = %.1f V\n\r",ad2*3.3/4096);

printf("\n\rJOY_Y = %.1f V\n\r",ad1*3.3/4096);

if(((ad2*3.3/4096)>=1.0&&(ad2*3.3/4096)<=2.8) && ((ad1*3.3/4096)>=3.0&&(ad1*3.3/4096)<=3.3))

{

printf("\n\r***前进****\n\r");

}

if(((ad2*3.3/4096)>=0&&(ad2*3.3/4096)<=0.5) && ((ad1*3.3/4096)>=1.0&&(ad1*3.3/4096)<=2.8))

{

printf("\n\r***向左****\n\r");

}

if(((ad2*3.3/4096)>=3.0&&(ad2*3.3/4096)<=3.3) && ((ad1*3.3/4096)>=1.0&&(ad1*3.3/4096)<=2.8))

{

printf("\n\r***向右****\n\r");

}

if(((ad2*3.3/4096)>=1.0&&(ad2*1.0/4096)<=2.8) && ((ad1*3.3/4096)>=0&&(ad1*3.3/4096)<=0.5))

{

printf("\n\r***后退****\n\r");

}

}

/* USER CODE END 3 */

}

/**

* @brief System Clock Configuration

* @retval None

*/

void SystemClock_Config(void)

{

RCC_OscInitTypeDef RCC_OscInitStruct = {0};

RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

/**Configure the main internal regulator output voltage

*/

__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

/**Initializes the CPU, AHB and APB busses clocks

*/

RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;

RCC_OscInitStruct.HSIState = RCC_HSI_ON;

RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;

RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;

RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;

RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_6;

RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_3;

if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)

{

Error_Handler();

}

/**Initializes the CPU, AHB and APB busses clocks

*/

RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK

|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;

RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;

RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;

RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)

{

Error_Handler();

}

PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;

PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;

if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)

{

Error_Handler();

}

}

/**

* @brief ADC Initialization Function

* @param None

* @retval None

*/

static void MX_ADC_Init(void)

{

/* USER CODE BEGIN ADC_Init 0 */

/* USER CODE END ADC_Init 0 */

ADC_ChannelConfTypeDef sConfig = {0};

/* USER CODE BEGIN ADC_Init 1 */

/* USER CODE END ADC_Init 1 */

/**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)

*/

hadc.Instance = ADC1;

hadc.Init.OversamplingMode = DISABLE;

hadc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV8;

hadc.Init.Resolution = ADC_RESOLUTION_12B;

hadc.Init.SamplingTime = ADC_SAMPLETIME_7CYCLES_5;

hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;

hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;

hadc.Init.ContinuousConvMode = ENABLE;

hadc.Init.DiscontinuousConvMode = DISABLE;

hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;

hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;

hadc.Init.DMAContinuousRequests = ENABLE;

hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV;

hadc.Init.Overrun = ADC_OVR_DATA_PRESERVED;

hadc.Init.LowPowerAutoWait = DISABLE;

hadc.Init.LowPowerFrequencyMode = DISABLE;

hadc.Init.LowPowerAutoPowerOff = DISABLE;

if (HAL_ADC_Init(&hadc) != HAL_OK)

{

Error_Handler();

}

/**Configure for the selected ADC regular channel to be converted.

*/

sConfig.Channel = ADC_CHANNEL_1;

sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;

if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)

{

Error_Handler();

}

/**Configure for the selected ADC regular channel to be converted.

*/

sConfig.Channel = ADC_CHANNEL_2;

if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)

{

Error_Handler();

}

/* USER CODE BEGIN ADC_Init 2 */

/* USER CODE END ADC_Init 2 */

}

/**

* @brief USART1 Initialization Function

* @param None

* @retval None

*/

static void MX_USART1_UART_Init(void)

{

/* USER CODE BEGIN USART1_Init 0 */

/* USER CODE END USART1_Init 0 */

/* USER CODE BEGIN USART1_Init 1 */

/* USER CODE END USART1_Init 1 */

huart1.Instance = USART1;

huart1.Init.BaudRate = 115200;

huart1.Init.WordLength = UART_WORDLENGTH_8B;

huart1.Init.StopBits = UART_STOPBITS_1;

huart1.Init.Parity = UART_PARITY_NONE;

huart1.Init.Mode = UART_MODE_TX_RX;

huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;

huart1.Init.OverSampling = UART_OVERSAMPLING_16;

huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;

huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;

if (HAL_UART_Init(&huart1) != HAL_OK)

{

Error_Handler();

}

/* USER CODE BEGIN USART1_Init 2 */

/* USER CODE END USART1_Init 2 */

}

/**

* Enable DMA controller clock

*/

static void MX_DMA_Init(void)

{

/* DMA controller clock enable */

__HAL_RCC_DMA1_CLK_ENABLE();

/* DMA interrupt init */

/* DMA1_Channel1_IRQn interrupt configuration */

HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);

HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);

}

/**

* @brief GPIO Initialization Function

* @param None

* @retval None

*/

static void MX_GPIO_Init(void)

{

GPIO_InitTypeDef GPIO_InitStruct = {0};

/* GPIO Ports Clock Enable */

__HAL_RCC_GPIOA_CLK_ENABLE();

/*Configure GPIO pin : KEY_Pin */

GPIO_InitStruct.Pin = KEY_Pin;

GPIO_InitStruct.Mode = GPIO_MODE_INPUT;

GPIO_InitStruct.Pull = GPIO_PULLUP;

HAL_GPIO_Init(KEY_GPIO_Port, &GPIO_InitStruct);

GPIO_InitStruct.Pin = GPIO_PIN_3;

GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;

GPIO_InitStruct.Pull = GPIO_NOPULL;

HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**

* @brief This function is executed in case of error occurrence.

* @retval None

*/

void Error_Handler(void)

{

/* USER CODE BEGIN Error_Handler_Debug */

/* User can add his own implementation to report the HAL error return state */

/* USER CODE END Error_Handler_Debug */

}

#ifdef USE_FULL_ASSERT

/**

* @brief Reports the name of the source file and the source line number

* where the assert_param error has occurred.

* @param file: pointer to the source file name

* @param line: assert_param error line source number

* @retval None

*/

void assert_failed(uint8_t *file, uint32_t line)

{

/* USER CODE BEGIN 6 */

/* User can add his own implementation to report the file name and line number,

tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

/* USER CODE END 6 */

}

#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

实验效果,通过串口展示效果,很灵敏,后期控制小车的运动方向会比机械按键NICE!!!!

相关推荐

魔兽世界战士职业任务流程攻略 魔兽战士职业任务怎么通关
日本清酒
365bet盘口开户

日本清酒

📅 09-12 🔥 921
惠修一口价
365三式投注

惠修一口价

📅 07-29 🔥 10
笔记本电脑频繁断网的原因及解决方法
365三式投注

笔记本电脑频繁断网的原因及解决方法

📅 08-21 🔥 397
《绝地求生:刺激战场》无法进入游戏 下载安装失败解决办法
《绝地求生:刺激战场》无法进入游戏 下载安装失败解决办法