aboutsummaryrefslogtreecommitdiff
path: root/embassy-stm32/src/lptim/pwm.rs
blob: 96af9f4d9e335efa77cae94c22079f9390317063 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! PWM driver.

use core::marker::PhantomData;

use embassy_hal_internal::Peri;

use super::timer::Timer;
#[cfg(not(any(lptim_v2a, lptim_v2b)))]
use super::OutputPin;
#[cfg(any(lptim_v2a, lptim_v2b))]
use super::{channel::Channel, timer::ChannelDirection, Channel1Pin, Channel2Pin};
use super::{BasicInstance, Instance};
#[cfg(gpio_v2)]
use crate::gpio::Pull;
use crate::gpio::{AfType, AnyPin, OutputType, Speed};
use crate::time::Hertz;

/// Output marker type.
pub enum Output {}
/// Channel 1 marker type.
pub enum Ch1 {}
/// Channel 2 marker type.
pub enum Ch2 {}

/// PWM pin wrapper.
///
/// This wraps a pin to make it usable with PWM.
pub struct PwmPin<'d, T, C> {
    _pin: Peri<'d, AnyPin>,
    phantom: PhantomData<(T, C)>,
}

/// PWM pin config
///
/// This configures the pwm pin settings
pub struct PwmPinConfig {
    /// PWM Pin output type
    pub output_type: OutputType,
    /// PWM Pin speed
    pub speed: Speed,
    /// PWM Pin pull type
    #[cfg(gpio_v2)]
    pub pull: Pull,
}

macro_rules! channel_impl {
    ($new_chx:ident, $new_chx_with_config:ident, $channel:ident, $pin_trait:ident) => {
        impl<'d, T: BasicInstance> PwmPin<'d, T, $channel> {
            #[doc = concat!("Create a new ", stringify!($channel), " PWM pin instance.")]
            pub fn $new_chx(pin: Peri<'d, impl $pin_trait<T>>) -> Self {
                critical_section::with(|_| {
                    pin.set_low();
                    set_as_af!(pin, AfType::output(OutputType::PushPull, Speed::VeryHigh));
                });
                PwmPin {
                    _pin: pin.into(),
                    phantom: PhantomData,
                }
            }
            #[doc = concat!("Create a new ", stringify!($channel), " PWM pin instance with config.")]
            pub fn $new_chx_with_config(pin: Peri<'d, impl $pin_trait<T>>, pin_config: PwmPinConfig) -> Self {
                critical_section::with(|_| {
                    pin.set_low();
                    #[cfg(gpio_v1)]
                    set_as_af!(pin, AfType::output(pin_config.output_type, pin_config.speed));
                    #[cfg(gpio_v2)]
                    set_as_af!(
                        pin,
                        AfType::output_pull(pin_config.output_type, pin_config.speed, pin_config.pull)
                    );
                });
                PwmPin {
                    _pin: pin.into(),
                    phantom: PhantomData,
                }
            }
        }
    };
}

#[cfg(not(any(lptim_v2a, lptim_v2b)))]
channel_impl!(new, new_with_config, Output, OutputPin);
#[cfg(any(lptim_v2a, lptim_v2b))]
channel_impl!(new_ch1, new_ch1_with_config, Ch1, Channel1Pin);
#[cfg(any(lptim_v2a, lptim_v2b))]
channel_impl!(new_ch2, new_ch2_with_config, Ch2, Channel2Pin);

/// PWM driver.
pub struct Pwm<'d, T: Instance> {
    inner: Timer<'d, T>,
}

#[cfg(not(any(lptim_v2a, lptim_v2b)))]
impl<'d, T: Instance> Pwm<'d, T> {
    /// Create a new PWM driver.
    pub fn new(tim: Peri<'d, T>, _output_pin: PwmPin<'d, T, Output>, freq: Hertz) -> Self {
        Self::new_inner(tim, freq)
    }

    /// Set the duty.
    ///
    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
    pub fn set_duty(&mut self, duty: u16) {
        assert!(duty <= self.get_max_duty());
        self.inner.set_compare_value(duty)
    }

    /// Get the duty.
    ///
    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
    pub fn get_duty(&self) -> u16 {
        self.inner.get_compare_value()
    }

    fn post_init(&mut self) {}
}

#[cfg(any(lptim_v2a, lptim_v2b))]
impl<'d, T: Instance> Pwm<'d, T> {
    /// Create a new PWM driver.
    pub fn new(
        tim: Peri<'d, T>,
        _ch1_pin: Option<PwmPin<'d, T, Ch1>>,
        _ch2_pin: Option<PwmPin<'d, T, Ch2>>,
        freq: Hertz,
    ) -> Self {
        Self::new_inner(tim, freq)
    }

    /// Enable the given channel.
    pub fn enable(&mut self, channel: Channel) {
        self.inner.enable_channel(channel, true);
    }

    /// Disable the given channel.
    pub fn disable(&mut self, channel: Channel) {
        self.inner.enable_channel(channel, false);
    }

    /// Check whether given channel is enabled
    pub fn is_enabled(&self, channel: Channel) -> bool {
        self.inner.get_channel_enable_state(channel)
    }

    /// Set the duty for a given channel.
    ///
    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
    pub fn set_duty(&mut self, channel: Channel, duty: u16) {
        assert!(duty <= self.get_max_duty());
        self.inner.set_compare_value(channel, duty)
    }

    /// Get the duty for a given channel.
    ///
    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
    pub fn get_duty(&self, channel: Channel) -> u16 {
        self.inner.get_compare_value(channel)
    }

    fn post_init(&mut self) {
        [Channel::Ch1, Channel::Ch2].iter().for_each(|&channel| {
            self.inner.set_channel_direction(channel, ChannelDirection::OutputPwm);
        });
    }
}

impl<'d, T: Instance> Pwm<'d, T> {
    fn new_inner(tim: Peri<'d, T>, freq: Hertz) -> Self {
        let mut this = Self { inner: Timer::new(tim) };

        this.inner.enable();
        this.set_frequency(freq);

        this.post_init();

        this.inner.continuous_mode_start();

        this
    }

    /// Set PWM frequency.
    ///
    /// Note: when you call this, the max duty value changes, so you will have to
    /// call `set_duty` on all channels with the duty calculated based on the new max duty.
    pub fn set_frequency(&mut self, frequency: Hertz) {
        self.inner.set_frequency(frequency);
    }

    /// Get max duty value.
    ///
    /// This value depends on the configured frequency and the timer's clock rate from RCC.
    pub fn get_max_duty(&self) -> u16 {
        self.inner.get_max_compare_value() + 1
    }
}