reflow-oven-control-sw/stm-firmware/rotary-encoder.c

79 lines
2.5 KiB
C

/* Reflow Oven Controller
*
* Copyright (C) 2020 Mario Hüttel <mario.huettel@gmx.net>
*
* This file is part of the Reflow Oven Controller Project.
*
* The reflow oven controller is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* GDSII-Converter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the reflow oven controller project.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <reflow-controller/rotary-encoder.h>
#include <stm-periph/clock-enable-manager.h>
#include <stm-periph/stm32-gpio-macros.h>
static inline void rotary_encoder_setup_pins(void)
{
rcc_manager_enable_clock(&RCC->AHB1ENR, BITMASK_TO_BITNO(ROTARY_ENCODER_RCC_MASK));
ROTARY_ENCODER_PORT->MODER &= MODER_DELETE(ROTARY_ENCODER_PIN1) & MODER_DELETE(ROTARY_ENCODER_PIN2);
ROTARY_ENCODER_PORT->MODER |= ALTFUNC(ROTARY_ENCODER_PIN1) | ALTFUNC(ROTARY_ENCODER_PIN2);
SETAF(ROTARY_ENCODER_PORT, ROTARY_ENCODER_PIN1, ROTARY_ENCODER_PORT_ALTFUNC);
SETAF(ROTARY_ENCODER_PORT, ROTARY_ENCODER_PIN2, ROTARY_ENCODER_PORT_ALTFUNC);
}
void rotary_encoder_setup(void)
{
rcc_manager_enable_clock(&RCC->APB1ENR, BITMASK_TO_BITNO(ROTARY_ENCODER_TIMER_RCC_MASK));
rotary_encoder_setup_pins();
ROTARY_ENCODER_TIMER->ARR = 0xFFFF;
ROTARY_ENCODER_TIMER->CNT = 0;
ROTARY_ENCODER_TIMER->CR2 = 0;
ROTARY_ENCODER_TIMER->SMCR = TIM_SMCR_SMS_0 | TIM_SMCR_SMS_1;
ROTARY_ENCODER_TIMER->CCMR1 = TIM_CCMR1_CC1S_0 | TIM_CCMR1_CC2S_0;
ROTARY_ENCODER_TIMER->CCER = TIM_CCER_CC1P | TIM_CCER_CC2P;
ROTARY_ENCODER_TIMER->PSC = 0;
ROTARY_ENCODER_TIMER->CR1 = TIM_CR1_CEN;
}
uint32_t rotary_encoder_get_abs_val(void)
{
return (uint32_t)ROTARY_ENCODER_TIMER->CNT;
}
int32_t rotary_encoder_get_chage_val(void)
{
static uint32_t last_val = 0;
uint32_t val;
int32_t diff;
val = rotary_encoder_get_abs_val();
diff = val - last_val;
if (diff > 0xEFFF) {
diff = 0xFFFF - diff;
}
return diff;
}
void rotary_encoder_stop(void)
{
ROTARY_ENCODER_TIMER->CR1 = 0;
ROTARY_ENCODER_TIMER->CR2 = 0;
ROTARY_ENCODER_TIMER->ARR = 0;
rcc_manager_disable_clock(&RCC->APB1ENR, BITMASK_TO_BITNO(ROTARY_ENCODER_TIMER_RCC_MASK));
rcc_manager_disable_clock(&RCC->AHB1ENR, BITMASK_TO_BITNO(ROTARY_ENCODER_RCC_MASK));
}