first commit

This commit is contained in:
cxh 2025-06-05 16:36:58 +08:00
commit e7a6466a6f
3 changed files with 79 additions and 0 deletions

5
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"files.associations": {
"chrono": "cpp"
}
}

51
GPIOcontrol.h Normal file
View File

@ -0,0 +1,51 @@
#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

23
main.cpp Normal file
View File

@ -0,0 +1,23 @@
#include "GPIOControl.h"
#include <thread>
#include <chrono>
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;
}