8

Dependencies:   mbed

main.cpp

Committer:
codebreaker7
Date:
2017-10-29
Revision:
0:e0dc7a04fc82
Child:
1:349234492517

File content as of revision 0:e0dc7a04fc82:

#include "mbed.h"
#include "stm32l0xx.h"
#include "stm32l0xx_hal_tim.h"

TIM_HandleTypeDef timer;
TIM_OC_InitTypeDef octim;
int pulse = 1599;

DigitalOut led(LED1);

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef * handle)
{
    GPIO_InitTypeDef gpio;
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_TIM2_CLK_ENABLE();
    gpio.Mode = GPIO_MODE_AF_PP;
    gpio.Pin = GPIO_PIN_1;
    gpio.Pull = GPIO_PULLUP;
    gpio.Speed = GPIO_SPEED_HIGH;
    gpio.Alternate = GPIO_AF2_TIM2;
    HAL_GPIO_Init(GPIOA, &gpio);
}

void InitTimer(void)
{
    timer.Instance = TIM2;
    timer.Init.CounterMode = TIM_COUNTERMODE_UP;
    timer.Init.ClockDivision = 0;
    timer.Init.Period = 64000 - 1;
    timer.Init.Prescaler = (uint32_t)(SystemCoreClock / 3200000) - 1;
    HAL_TIM_Base_Init(&timer);
    HAL_TIM_PWM_Init(&timer);

    octim.OCMode = TIM_OCMODE_PWM1;
    octim.OCPolarity = TIM_OCPOLARITY_HIGH;
    octim.OCFastMode = TIM_OCFAST_ENABLE;
    octim.Pulse = pulse;

    HAL_TIM_PWM_ConfigChannel(&timer, &octim, TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&timer, TIM_CHANNEL_2);
}

int cur_pw = 500;

int main()
{
    HAL_Init();
    InitTimer();
    int dir = 0;
    int count = 0;
    
    while(1) {
        led = !led;
        wait(0.1f);
        if (dir) {
            pulse -= 100;
            count--;
            if (count == 0) {
                dir = 0;
            }
        } else {
            pulse += 100;
            count++;
            if (count== 58) {
                dir = 1;
            }
        }        
        octim.Pulse = pulse;
        HAL_TIM_PWM_ConfigChannel(&timer, &octim, TIM_CHANNEL_2);
        HAL_TIM_PWM_Start(&timer, TIM_CHANNEL_2);
    }
}