Created
September 27, 2022 07:47
-
-
Save greggjaskiewicz/5cf3637e13375109f835d50629638034 to your computer and use it in GitHub Desktop.
Very simple Rp2040 PWM duty control class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "hardware/pwm.h" | |
class PiPWM { | |
public: | |
explicit PiPWM(uint pin); | |
void start(); | |
void stop(); | |
~PiPWM(); | |
// duty 0-100 | |
void setDuty(uint8_t duty); | |
private: | |
uint _pin; | |
uint _slice_num; | |
uint _channel; | |
const uint _maxWrap = 500; | |
}; | |
PiPWM::PiPWM(uint pin): _pin(pin) { | |
gpio_set_function(pin, GPIO_FUNC_PWM); | |
_slice_num = pwm_gpio_to_slice_num(pin); | |
_channel = pwm_gpio_to_channel(pin); | |
} | |
void PiPWM::start() { | |
pwm_set_wrap(_slice_num, 1); | |
pwm_set_chan_level(_slice_num, _channel, 1); | |
pwm_set_enabled(_slice_num, true); | |
pwm_set_wrap(_slice_num, _maxWrap); | |
}; | |
void PiPWM::stop() { | |
pwm_set_enabled(_slice_num, false); | |
}; | |
PiPWM::~PiPWM() { | |
stop(); | |
}; | |
// duty 0-100 | |
void PiPWM::setDuty(uint8_t duty) { | |
if (duty >= 0 && duty <= 100) { | |
uint16_t x = (_maxWrap/100) * duty; | |
pwm_set_chan_level(_slice_num, _channel, x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment