FSM thermostat
port_thermostat.c
Go to the documentation of this file.
1 
11 /* Standard C includes */
12 #include <stdlib.h>
13 #include <math.h>
14 
15 /* Project includes */
16 #include "port_thermostat.h"
17 
18 /* Private functions ---------------------------------------------------------*/
20 {
21 
22  if (THERMOSTAT_MEASUREMENT_TIMER == TIM2)
23  {
24  // Enable the timer clock
25  RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
26  }
27 
28  // Disable the timer
29  THERMOSTAT_MEASUREMENT_TIMER->CR1 &= ~TIM_CR1_CEN;
30 
31  // Autoreload preload enabled
32  THERMOSTAT_MEASUREMENT_TIMER->CR1 |= TIM_CR1_ARPE;
33 
34  // Reset the values of the timer
36 
37  // Set the timeout value
38  // Compute ARR and PSC to match the duration. Check if the duration is too long and adapt prescaler and ARR
39  double sec = (double)p_thermostat->timer_period_sec;
40  double scc = (double)SystemCoreClock;
41  double psc = round(((scc * sec) / (65535.0 + 1.0)) - 1.0);
42  double arr = round(((scc * sec) / (psc + 1.0)) - 1.0);
43 
44  // Adjust psc and arr if necessary
45  if (arr > 0xFFFF)
46  {
47  psc += 1.0;
48  arr = round((scc * sec) / (psc + 1.0) - 1.0);
49  }
50 
51  // Load the values
52  THERMOSTAT_MEASUREMENT_TIMER->ARR = (uint32_t)(round(arr));
53  THERMOSTAT_MEASUREMENT_TIMER->PSC = (uint32_t)(round(psc));
54 
55  // Clean interrupt flags
56  THERMOSTAT_MEASUREMENT_TIMER->SR &= ~TIM_SR_UIF;
57 
58  // Enable the update interrupt
59  THERMOSTAT_MEASUREMENT_TIMER->DIER |= TIM_DIER_UIE;
60 
61  if (THERMOSTAT_MEASUREMENT_TIMER == TIM2)
62  {
63  // Enable the interrupt in the NVIC
64  NVIC_SetPriority(TIM2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 2, 0));
65  NVIC_EnableIRQ(TIM2_IRQn);
66  }
67 
68  THERMOSTAT_MEASUREMENT_TIMER->EGR |= TIM_EGR_UG; // 6) Update generation: Re-inicializa el contador y actualiza los registros. IMPORTANTE que estĂ© lo Ășltimo
69 
70 
71  // Enable the timer
72  THERMOSTAT_MEASUREMENT_TIMER->CR1 |= TIM_CR1_CEN;
73 }
fsm_thermostat_t
Structure to define the thermostat FSM.
Definition: fsm_thermostat.h:53
SystemCoreClock
uint32_t SystemCoreClock
Definition: port_system.c:18
THERMOSTAT_MEASUREMENT_TIMER
#define THERMOSTAT_MEASUREMENT_TIMER
Definition: port_thermostat.h:22
fsm_thermostat_t::timer_period_sec
uint32_t timer_period_sec
Definition: fsm_thermostat.h:63
port_thermostat.h
Header file for the thermostat system port layer.
port_thermostat_timer_setup
void port_thermostat_timer_setup(fsm_thermostat_t *p_thermostat)
Initializes the timer of the thermostat.
Definition: port_thermostat.c:19