/* ******************************************************************************* * INCLUDE ******************************************************************************* */ #include "GPIO.h" #include #include #include #include #include namespace Hardware { /* ******************************************************************************* * CLASS DEFINE ******************************************************************************* */ GPIO::GPIO(int pinno): _pinno(pinno) { std::string s = std::to_string(_pinno); writeFile("/sys/class/gpio/export", s.c_str(), s.length()); _fd = ::open(Poco::format("/sys/class/gpio/gpio%d/value", _pinno).c_str(), O_RDWR); if (_fd < 0) throw Poco::InvalidAccessException("Open FAIL"); } GPIO::~GPIO() { ::close(_fd); std::string s = std::to_string(_pinno); writeFile("/sys/class/gpio/unexport", s.c_str(), s.length()); } void GPIO::direction(Direction dir) { switch (dir) { case Direction::OUT: default: writeDirection("out"); break; case Direction::IN: writeDirection("in"); break; } } void GPIO::write(unsigned level) { if (level) ::write(_fd, "1", 1); else ::write(_fd, "0", 1); } unsigned GPIO::read() { char value; ::read(_fd, &value, 1); return value != '0'; } void GPIO::writeFile(const std::string& path, const void* pData, int len) { int fd = ::open(path.c_str(), O_WRONLY); if (fd < 0) throw Poco::InvalidAccessException("Open FAIL"); ::write(fd, pData, len); ::close(fd); } void GPIO::writeDirection(const std::string& value) { writeFile(Poco::format("/sys/class/gpio/gpio%d/direction", _pinno), value.c_str(), value.length()); } }