Files
Loongson_2k0300_SmartCar_Fr…/hal/pwm.cpp

58 lines
1.3 KiB
C++

#include "pwm.hpp"
#include <fstream>
#include <thread>
#include <chrono>
PWM::PWM(int chip, int channel, unsigned int period_ns)
: _chip(chip), _channel(channel), _period_ns(period_ns), _exported(false)
{
_export();
setPeriod(period_ns);
}
PWM::~PWM() { _unexport(); }
std::string PWM::_basePath() const
{
return "/sys/class/pwm/pwmchip" + std::to_string(_chip) +
"/pwm" + std::to_string(_channel);
}
void PWM::_export()
{
std::ofstream f("/sys/class/pwm/pwmchip" + std::to_string(_chip) + "/export");
if (f.is_open()) { f << _channel; _exported = true; }
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void PWM::_unexport()
{
std::ofstream f("/sys/class/pwm/pwmchip" + std::to_string(_chip) + "/unexport");
if (f.is_open()) f << _channel;
}
void PWM::setDutyCycle(unsigned int duty_ns)
{
std::ofstream f(_basePath() + "/duty_cycle");
if (f.is_open()) f << duty_ns;
}
void PWM::setPeriod(unsigned int period_ns)
{
_period_ns = period_ns;
std::ofstream f(_basePath() + "/period");
if (f.is_open()) f << period_ns;
}
void PWM::enable(bool on)
{
std::ofstream f(_basePath() + "/enable");
if (f.is_open()) f << (on ? 1 : 0);
}
void PWM::setPolarity(const char* pol)
{
std::ofstream f(_basePath() + "/polarity");
if (f.is_open()) f << pol;
}