复制一下之前ADC的工程,打开cubemx
cubemx配置
1.在Connectivity中点击USART1
Mode(模式):Asynchronous(异步模式)
2.将PA9设置为USART1_TX,PA10设置为USART1_RX。
3.配置Parameter Settings.
Baud Rate(波特率):9600
4.配置NVIC Settings
勾选 USART1 global interrupt/USART1 wake-up interrupt through EXTI line 25
点击Generated Code、
代码编写
在my_main.h中添加头文件
#include "usart.h"
#include "string.h"
my,main.c
#include "my_main.h"
#include "stm32g4xx_hal_adc.h"
#include "adc.h"
#include "usart.h"
#include "string.h"
uint8_t led_sta=0x10;
char text[30];
char usart_tx[50];
char usart_rx[50];
void LED_Disp(uint8_t dsLED)
{
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_All,GPIO_PIN_SET);//所有LED熄灭(l小写)
HAL_GPIO_WritePin(GPIOC,dsLED<<8,GPIO_PIN_RESET);//左移8位:控制C8-15引脚,值为1的点亮
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_SET);//开锁存器
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);//关锁存器
}
float adc_read(ADC_HandleTypeDef *hadc)
{
uint16_t adc_val;
float adc_f;
HAL_ADC_Start(hadc);
adc_val=HAL_ADC_GetValue(hadc);
adc_f=adc_val*3.3f/4096.0f;
return adc_f;
}
float adc_read_os(ADC_HandleTypeDef *hadc)//带 过采样
{
uint16_t adc_val;
float adc_f;
HAL_ADC_Start(hadc);
adc_val=HAL_ADC_GetValue(hadc);
adc_f=adc_val*3.3f/65536.0f;
return adc_f;
}
void setup()
{
HAL_ADCEx_Calibration_Start(&hadc2,ADC_SINGLE_ENDED);
HAL_UARTEx_ReceiveToIdle_IT(&huart1,(uint8_t*)usart_rx,50);
HAL_ADCEx_Calibration_Start(&hadc2,ADC_SINGLE_ENDED);
LED_Disp(0x00);//关掉所有LED
LCD_Init();//LCD初始化
LCD_Clear(Black);
LCD_SetBackColor(Black);
LCD_SetTextColor(White);
}
void loop()
{
float adc_data_PB15;
adc_data_PB15=adc_read(&hadc2);
sprintf(usart_tx," PB15=%.4fV \r\n ",adc_data_PB15);
HAL_UART_Transmit(&huart1,(uint8_t *)usart_tx,strlen(usart_tx),50);
}
示例:密码锁
#include "my_main.h"
#include "stm32g4xx_hal_adc.h"
#include "adc.h"
#include "usart.h"
#include "string.h"
uint8_t led_sta=0x10;
char text[30];
extern struct Bkeys bkey[];
char usart_tx[50];
char usart_rx[50];
char passwd[3]={'1','2','3'};
void LED_Disp(uint8_t dsLED)
{
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_All,GPIO_PIN_SET);//所有LED熄灭(l小写)
HAL_GPIO_WritePin(GPIOC,dsLED<<8,GPIO_PIN_RESET);//左移8位:控制C8-15引脚,值为1的点亮
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_SET);//开锁存器
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);//关锁存器
}
void setup()
{
HAL_ADCEx_Calibration_Start(&hadc2,ADC_SINGLE_ENDED);
HAL_UARTEx_ReceiveToIdle_IT(&huart1,(uint8_t*)usart_rx,50);
HAL_ADCEx_Calibration_Start(&hadc2,ADC_SINGLE_ENDED);
LED_Disp(0x00);//关掉所有LED
LCD_Init();//LCD初始化
LCD_Clear(Black);
LCD_SetBackColor(Black);
LCD_SetTextColor(White);
}
void loop()
{
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{ char old_pswd[10];
char new_pswd[10];
sscanf(usart_rx,"%3s-%3s",old_pswd,new_pswd);
if(strcmp(old_pswd,passwd)==0)
{ for(int i=0;i<3;i++)passwd[i]=new_pswd[i];
sprintf(text,"new:%s ",passwd);
LCD_DisplayStringLine(Line4,(uint8_t *)text);//局部刷新
}
else
{ sprintf(text,"Failed! ");
LCD_DisplayStringLine(Line4,(uint8_t *)text);//局部刷新
}
HAL_UARTEx_ReceiveToIdle_IT(&huart1,(uint8_t*)usart_rx,50);
}