Skip to main content

Subsection 13.2.4 Part 4: Reading the Program

The program is Day15_servo_template.c, and it comes with a timer driver in two files, tim.c and tim.h. It also uses your own ADC driver, the adc.c and adc.h you built in Lab 5. The template is complete except for the five #define lines whose values you just chose and one line in the loop, the map from the potentiometer’s reading to a pulse width. Here is the header, tim.h, and the three functions it declares:
#ifndef TIM_H_
#define TIM_H_

#include <stdint.h>

void tim16_ms_interrupt_init(int milliseconds);
void tim14_pa7_pwm_init(uint16_t prescaleFactor, uint16_t timerMax);
void tim14_pwm_set(uint16_t pulse);
#endif /* TIM_H_ */
The TIM14 functions in the timer library, tim.c, are the ones we used (Subsection 11.3.4), with two changes. The prescale factor and the counter’s top value are now parameters, passed in from the program, rather than #define lines at the top of the driver. And tim14_pwm_set() no longer checks its value: it used to check that the value it was given was within the range the counter can represent before writing it to CCR1; here it writes the value it is given. The range check is now in the program, in updateServo(), where the range is SERVO_MIN to SERVO_MAX. Every other register write in tim14_pa7_pwm_init() is the same as before; the whole file is printed in Subsection 13.4.3, and Figure 11.3.13 has the registers. Here are the lines of tim14_pa7_pwm_init() that take the two numbers, and the whole of tim14_pwm_set(). The initialization writes ARR = timerMax-1, so PWM_TIMER_MAX is the number of counts in one period, and tim14_pwm_set() writes CCR1 = value, so the value is the number of counts the pin is HIGH, the same convention as before. SERVO_MID is the middle of the range; the loop does not use it, but it is the number that parks the horn at its center.
void tim14_pa7_pwm_init(uint16_t prescaleFactor, uint16_t timerMax) {
    // ... the pin and the clock setup, as before ...

    // Set prescaler
    TIM14->PSC = prescaleFactor-1;

    // Set autoreload value (counter runs 0..timerMax-1: timerMax counts per period)
    TIM14->ARR = timerMax-1;

    // Set the compare register value - start with a speed of 0
    TIM14->CCR1 = 0;

    // ... the PWM mode, the output enable and the timer enable, as before ...
}
void tim14_pwm_set(uint16_t value) {
    // PWM mode 1: pin is HIGH while CNT < CCR1, i.e. for exactly 'value' counts
    TIM14->CCR1 = value;
}
void updateServo(uint16_t value) {
    if (value>SERVO_MAX) {
        value = SERVO_MAX;
    } else if (value < SERVO_MIN) {
        value = SERVO_MIN;
    }
    tim14_pwm_set(value);
}
The limit in tim14_pwm_set() used to be the timer’s: the largest count the counter can represent. The servo’s safe range, 1 ms to 2 ms, is much narrower than that, and it is a property of the servo, not of the timer. Outside that range the servo drives against its own mechanical stops. So the program, which is written for this servo, applies the limit, in updateServo(), and every value reaches CCR1 through that function.
The program reads the potentiometer on your breadboard (the knob, not the one inside the servo) twice a second. TIM14 is used to create the pulse, so the timing tick for the potentiometer reading comes from a second timer, TIM16 (Reference Manual §18, General-purpose timers (TIM16/TIM17)). tim16_ms_interrupt_init() is the periodic-interrupt setup from Day 8 (Subsection 8.2.6) on a different timer, with the period as a parameter; the listing below follows the Day 8 setup line for line. TIM16’s interrupt is position 21 in the vector table (Subsection 8.3.7), and the startup file’s name for that slot is TIM16_IRQHandler(). The handler raises timerFlag, and the main loop takes one reading and lowers it again.
void tim16_ms_interrupt_init(int milliseconds) {
    /* enable clock access to timer 16 (on APB bus) */
    RCC->APBENR2 |= RCC_APBENR2_TIM16EN;

    /* Set prescaler value */
    TIM16->PSC = TIM16_PSC_FACTOR - 1; // starts counting at 0

    /* Set auto-reload value */
    TIM16->ARR = milliseconds - 1;

    /* Clear counter */
    TIM16->CNT = 0;

    /* Enable update interrupt */
    TIM16->DIER |= TIM_DIER_UIE;

    /* Enable timer interrupt in NVIC */
    NVIC_EnableIRQ(TIM16_IRQn);

    /* Enable timer */
    TIM16->CR1 |= TIM_CR1_CEN;
}
One line of code remains: the map from a potentiometer reading, 0 to 4095, onto a pulse width between SERVO_MIN and SERVO_MAX. One C fact to keep in mind when you write it: / on two integers discards the remainder, so the order in which you multiply and divide matters.

Activity 13.2.7. Map the potentiometer onto the pulse.

Write the expression that maps pot_value onto pwm_value, using the names in the template (MAXADC is 4096). Then check it by hand: what does it give for readings of 0, 2048 and 4095, and are all three inside the servo’s safe range?
Here is the whole program as you download it.
/* servo.c -- Control a servo motor with a potentiometer
 * Potentiometer:   Analog channel PA0
 * Servo PWM input: PA7
 */

#include <stdio.h>
#include "ES28.h"
#include "uart.h"
#include "adc.h"
#include "tim.h"

/* Clock runs at 12MHz */
#define PWM_PSC_FACTOR              // prescaler
#define PWM_TIMER_MAX               // 20 ms
#define SERVO_MIN                   // 1 ms
#define SERVO_MID                   // 1.5 ms
#define SERVO_MAX                   // 2 ms

#define MAXADC          4096        // 12-bit converter

volatile uint8_t timerFlag = 0;     // Do not forget the volatile!

void updateServo(uint16_t value);

// Main program
int main(void) {
    uint16_t pot_value = 0;
    uint16_t pwm_value = SERVO_MIN;

    uart2_init();
    tim14_pa7_pwm_init(PWM_PSC_FACTOR, PWM_TIMER_MAX);
    pa0_adc_init();

    printf("Potentiometer-controlled servo\n\r");

    timerFlag = 0;
    tim16_ms_interrupt_init(500);

    while(1) {
        if(timerFlag==1) {
            pot_value = adc_read();         // Pot value (0 to MAXADC-1)

/*******************/
            pwm_value =                     // Map pot_value to pwm_value
/*******************/

            updateServo(pwm_value);         // Update the PWM
            printf("pot_value=%d, \tpwm_value=%d\n\r", pot_value, pwm_value);
            timerFlag=0;                    // Put the flag down
        }
        // Processor could sleep here
    }
    return 0;                               // never reached
}
void updateServo(uint16_t value) {
    if (value>SERVO_MAX) {
        value = SERVO_MAX;
    } else if (value < SERVO_MIN) {
        value = SERVO_MIN;
    }
    tim14_pwm_set(value);
}

void TIM16_IRQHandler(void) {
    __disable_irq();
    /* Clear UIF in status register */
    TIM16->SR = ~TIM_SR_UIF;
    timerFlag = 1;
    __enable_irq();
}