Files

44 lines
1010 B
C++

#include "gpio.hpp"
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <sstream>
GPIO::GPIO(int pin) : _pin(pin), _exported(false) { _export(); }
GPIO::~GPIO() { _unexport(); }
void GPIO::_export()
{
std::ofstream exp("/sys/class/gpio/export");
if (exp.is_open()) { exp << _pin; _exported = true; }
}
void GPIO::_unexport()
{
std::ofstream unexp("/sys/class/gpio/unexport");
if (unexp.is_open()) unexp << _pin;
}
void GPIO::setDirection(const std::string& dir)
{
std::string path = "/sys/class/gpio/gpio" + std::to_string(_pin) + "/direction";
std::ofstream f(path);
if (f.is_open()) f << dir;
}
void GPIO::setValue(int val)
{
std::string path = "/sys/class/gpio/gpio" + std::to_string(_pin) + "/value";
std::ofstream f(path);
if (f.is_open()) f << val;
}
int GPIO::getValue() const
{
std::string path = "/sys/class/gpio/gpio" + std::to_string(_pin) + "/value";
std::ifstream f(path);
int v = 0; if (f.is_open()) f >> v;
return v;
}