//! Example of using a number of timer channels in PWM mode.
//! Target board: STM32F3DISCOVERY
#![no_std]
#![no_main]

use panic_semihosting as _;

use stm32f3xx_hal as hal;

use cortex_m::asm;
use cortex_m_rt::entry;

//use cortex_m_semihosting::hprintln;
use hal::hal::PwmPin;

use hal::flash::FlashExt;
use hal::gpio::GpioExt;
use hal::pac;
use hal::prelude::*;
#[allow(deprecated)]
use hal::pwm::{tim16, tim2, tim3, tim8};
use hal::rcc::RccExt;

#[entry]
fn main() -> ! {
    // Get our peripherals
    let dp = pac::Peripherals::take().unwrap();

    // Configure our clocks
    let mut flash = dp.FLASH.constrain();
    let mut rcc = dp.RCC.constrain();
    let clocks = rcc.cfgr.sysclk(16.MHz()).freeze(&mut flash.acr);

    // Prep the pins we need in their correct alternate function
    let mut gpiob = dp.GPIOB.split(&mut rcc.ahb);
    let pb10 = gpiob
        .pb10
        .into_af_push_pull(&mut gpiob.moder, &mut gpiob.otyper, &mut gpiob.afrh);

    // TIM2
    //
    // A 32-bit timer, so we can set a larger resolution
    #[allow(deprecated)]
    let tim2_channels = tim2(
        dp.TIM2,
        160000,  // resolution of duty cycle
        50.Hz(), // frequency of period
        &clocks, // To get the timer's clock speed
    );

    let mut tim2_ch3 = tim2_channels.2.output_to_pb10(pb10);
    tim2_ch3.set_duty(tim2_ch3.get_max_duty() / 20); // 5% duty cyle
    tim2_ch3.enable();

    loop {
        for i in 1..=20 {
            tim2_ch3.set_duty(tim2_ch3.get_max_duty() / i);
            asm::delay(8_000_000);
        }
    }
}