From e7a6466a6f59c1ac30da6dfe266972e4ad421047 Mon Sep 17 00:00:00 2001 From: cxh Date: Thu, 5 Jun 2025 16:36:58 +0800 Subject: [PATCH] first commit --- .vscode/settings.json | 5 +++++ GPIOcontrol.h | 51 +++++++++++++++++++++++++++++++++++++++++++ main.cpp | 23 +++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 .vscode/settings.json create mode 100644 GPIOcontrol.h create mode 100644 main.cpp diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..5e09a03 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "chrono": "cpp" + } +} \ No newline at end of file diff --git a/GPIOcontrol.h b/GPIOcontrol.h new file mode 100644 index 0000000..e8793ab --- /dev/null +++ b/GPIOcontrol.h @@ -0,0 +1,51 @@ +#ifndef GPIO_CONTROL_H +#define GPIO_CONTROL_H + +#include +#include +#include +#include + +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 diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..49565ab --- /dev/null +++ b/main.cpp @@ -0,0 +1,23 @@ +#include "GPIOControl.h" +#include +#include + +int main() +{ + GPIOControl relay(42); // 继电器接在 GPIO42 + + if (!relay.exportGPIO()) + return 1; + usleep(100000); // 确保 sysfs 完全准备好 + if (!relay.setDirection("out")) + return 1; + + // 打开继电器 + relay.setValue(true); + std::this_thread::sleep_for(std::chrono::seconds(2)); + + // 关闭继电器 + relay.setValue(false); + + return 0; +}