/*
 * timers_pwm_user_code.c
 * ARGYNIX Skills (worldskills.blog), lesson "Timers and PWM on the STM32".
 * Board: NUCLEO-F103RB (STM32F103RB, ST-LINK built in), system clock 72 MHz.
 *
 * This is not a whole program. It is what you type into the main.c that STM32CubeMX
 * generates:
 *   1. Set the project up in STM32CubeMX with timers_pwm_cubemx.md and generate the code.
 *   2. Import it into STM32CubeIDE and open Core/Src/main.c.
 *   3. Copy each block below between the two comments of the same name in main.c.
 *      Block 3 goes after "USER CODE BEGIN 3", before the closing brace of while (1).
 * Code outside the USER CODE blocks is deleted when CubeMX generates the code again.
 *
 *   PA0  TIM2_CH1  1 kHz PWM: PSC = 71, ARR = 999. The duty follows the knob.
 *   PA1  ADC1_IN1  the knob: a 10 kOhm potentiometer between 3V3 and GND.
 *   PA5  LD2       the green user LED: toggles every 250 ms, a 2 Hz blink.
 *
 * Nothing waits. HAL_GetTick() counts milliseconds from the SysTick interrupt that
 * HAL_Init() starts, and each job runs when its time has come.
 */

/* USER CODE BEGIN PV */
/* Globals, so Live Expressions in STM32CubeIDE can show them while the program runs. */
volatile uint32_t knob_raw;      /* 0 to 4095 from the 12-bit ADC */
volatile uint32_t duty_permille; /* 0 to 1000: 250 is 25.0 % */
/* USER CODE END PV */

/* USER CODE BEGIN 0 */
/* One conversion of ADC1 channel 1 (PA1). At a 12 MHz ADC clock and 239.5 cycles of
 * sampling it takes about 21 us, so polling it every 10 ms costs almost nothing.
 * If the conversion fails, the last good value is returned. */
static uint32_t knob_read(void)
{
  static uint32_t last;

  HAL_ADC_Start(&hadc1);
  if (HAL_ADC_PollForConversion(&hadc1, 2) == HAL_OK)
  {
    last = HAL_ADC_GetValue(&hadc1);
  }
  HAL_ADC_Stop(&hadc1);
  return last;
}

/* duty = CCR1 / (ARR + 1). ARR is read from the timer, so the duty stays right when you
 * change the frequency in CubeMX. CCR1 = 0 is a true 0 %, and CCR1 = ARR + 1 is 100 %.
 * __HAL_TIM_SET_COMPARE only writes CCR1. With "Output compare preload" enabled, the new
 * value waits in the preload register and starts with the next period: no glitch. */
static void pwm_set_permille(uint32_t permille)
{
  uint32_t steps = __HAL_TIM_GET_AUTORELOAD(&htim2) + 1u; /* 1000 at 1 kHz */
  uint32_t ccr = (permille * steps + 500u) / 1000u;       /* rounded to the nearest step */

  __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, ccr);
}
/* USER CODE END 0 */

/* USER CODE BEGIN 2 */
  HAL_ADCEx_Calibration_Start(&hadc1);       /* once after power-up: better ADC accuracy */
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);  /* CubeMX sets TIM2 up but does not start it */

  uint32_t last_knob = HAL_GetTick();
  uint32_t last_led = last_knob;
/* USER CODE END 2 */

/* USER CODE BEGIN 3 */
    uint32_t now = HAL_GetTick();

    /* Unsigned subtraction: still right when the millisecond counter wraps after
     * about 49.7 days. "+=" keeps the rhythm; "last = now" would drift. */
    if (now - last_knob >= 10u)
    {
      last_knob += 10u;
      knob_raw = knob_read();
      duty_permille = (knob_raw * 1000u + 2047u) / 4095u; /* 0 to 1000, rounded */
      pwm_set_permille(duty_permille);
    }

    if (now - last_led >= 250u)
    {
      last_led += 250u;
      HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); /* LD2 */
    }
/* USER CODE END 3 */
