一、Cubemx配置
1.ADC配置
PB15、PB12分别对应R37和R38,在配置adc时记得勾上Rank里的Sampling time(采样时间)选择640.5 Cycles。
unsigned int adc_value;
HAL_ADCEx_Calibration_Start(&hadc2,ADC_SINGLE_ENDED); //校准adc
double adc_get_volt(void)
{
HAL_ADC_START(&hadc2); //开adc
adc_value=HAL_ADC_GetValue(&hadc2);
return adc_value*3.3/4096;
}
二、串口配置
在配置串口的时候我们要单独在PA9、PA10里直接配置,在选择串口模式时勾选Asynchronous,选择波特率9600,然后记得开中断使能。
#include "stdio.h"
unsigned char rxdata;//所读到的数据
unsigned char rx_p;//指针
char rec[30];//接收数据的数组
char tx[30];//发送数据的数组
HAL_UART_Receive_IT(huart,&rxdata,1);//开接收中断
//接收函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)//重写中断回调函数
{
if(huart->Instance==USART1)
{
rec[rx_p++]=rxdata;
HAL_UART_Receive_IT(huart,&rxdata,1);
}
}
//发送函数
HAL_UART_Transmit(&huart1,tx,strle(tx),50);
三、PWM输出配置
在配置PWM时候通常选择TIM17_CH1或者其他定时器(注意:不可选带有N的通道),为了方便计算,我们通常将Count Period设置为100-1,模式选择PWM。
void output_pa7(void)
{
__HAL_TIM_SET_COMPARE(&htim17,TIM_CHANNEL_1,pa7_duty);
}
四、配置led
led.h
#ifndef _LED_H_
#define _LED_H_
#include "main.h"
#endif
led.c
#include "led.h"
void led_disp(unsigned char dsled)
{
HAL_GPIO_Write(GPIOC,GPIO_PIN_ALL,1);
HAL_GPIO_Write(GPIOC,dsled<<8,0);
HAL_GPIO_Write(GPIOD,GPIO_PIN_2,1);
HAL_GPIO_Write(GPIOD,GPIO_PIN_2,0);
}
五、配置按键
interrupt.h
#ifndef _INTERRUPT_H_
#define _INTERRUPT_H_
#include "main.h"
struct keys
{
unsigned int key_long;//记录长按键的flag
unsigned int key_short;//记录短按键的flag
unsigned int key_sta;//记录按键的状态
unsigned int judge_sta;//消抖
unsigned int key_time;//长按键的时间
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim);
#endif
interrupt.c
#include "interrupt.h"
struct keys key[4];
HAL_TIM_Base_Start_IT(&htim16);//开定时器
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM16)
{
key[0].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0);
key[1].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1);
key[2].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2);
key[3].key_sta=HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0);
for(int i=0;i<4;i++)
{
switch(key[i].judge_sta)
{
case 0:
{
if(key[i].key_sta==0)
{
key[i].key_time=0;
key[i].judge_sta=1;
}
}
break;
case 1:
{
if(key[i].key_sta==0)
{
key[i].judge_sta=2;
}
else{key[i].judge_sta=0;}
}
break;
case 2:
{
if(key[i].key_sta==1)
{
key[i].judge_sta=0;
if(key[i].key_time<2000)
{
key[i].key_short=1;
}
}
else
{
key[i].key_time++;
if(key[i].key_time>=2000)
{
key[i].key_long=1;
}
}
}
break;
}
}
}
六、输入捕获(PA1进行输入捕获)
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_2);//开输入捕获的中断
unsigned int ccr_val=0,pa1_frq=0;
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM2)
{
ccr_val=HAL_TIM_ReadCapturedValue(htim,TIM_CHANNEL_2);//获取count
__HAL_TIM_SetCounter(htim,0);
pa1_frq=(80000000/80)/ccr_val;
HAL_TIM_IC_Start_IT(htim,TIM_CHANNEL_2);//再次开启输入捕获
}
}