lock_ctrl/GPIOcontrol.h
2025-06-05 16:36:58 +08:00

52 lines
1.1 KiB
C++

#ifndef GPIO_CONTROL_H
#define GPIO_CONTROL_H
#include <string>
#include <fstream>
#include <iostream>
#include <unistd.h>
class GPIOControl
{
public:
GPIOControl(int gpioNum) : gpio(gpioNum) {}
bool exportGPIO()
{
return writeToFile("/sys/class/gpio/export", std::to_string(gpio));
}
bool unexportGPIO()
{
return writeToFile("/sys/class/gpio/unexport", std::to_string(gpio));
}
bool setDirection(const std::string &dir)
{
return writeToFile("/sys/class/gpio/gpio" + std::to_string(gpio) + "/direction", dir);
}
bool setValue(bool high)
{
return writeToFile("/sys/class/gpio/gpio" + std::to_string(gpio) + "/value", high ? "1" : "0");
}
private:
int gpio;
bool writeToFile(const std::string &path, const std::string &value)
{
std::ofstream fs(path);
if (!fs.is_open())
{
std::cerr << "无法访问: " << path << std::endl;
return false;
}
fs << value;
fs.close();
return true;
}
};
#endif // GPIO_CONTROL_H