在if条件中使用gpio的状态

Using the state of a gpio in an if condition

本文关键字:gpio 状态 if 条件      更新时间:2023-10-16

我有一个函数,在这个函数中我使用usleep()。然而,我只想在某个gpio的值为零的条件下使用usleep()。这是我迄今为止的代码:

const char *const amplifierGPIO = "/sys/class/gpio/gpio107/value";
const char *const hardwareID = "/sys/class/gpio/gpiox/value";
bool isWM8750()
{
std::ifstream id(hardwareID);
if (id.is_open())
{
const char *const value;
id >> value;
if (value == "0")
{
return true;
}
}
return false;
}
void amplifierUnmute()
{
std::ofstream amp(amplifierGPIO);
if (amp.is_open())
{
amp << "1";
amp.close();
}
if(isWM8750())
{
usleep(50000);
}
}

我得到了一个错误,我不知道如何解决:

sound_p51.cpp:38: error: no match for 'operator>>' in 'id >> value'
sound_p51.cpp:40: warning: comparison with string literal results in unspecified behaviour

您正试图将数据放入const char*const变量中。const char*const是指向一个字符串的指针,在该字符串中,指针不能更改,并且所指向的字符串数据也不能更改,因此是const。

该警告是因为const char*没有重载==运算符。对于这种类型的比较,通常使用strcmp()

然而,由于您使用的是c++,您可能希望使用std::string,它应该解决两个引用的编译器消息,如:

#include <string>
// ...
bool isWM8750()
{
std::ifstream id(hardwareID);
if (id.is_open())
{
std::string value;
id >> value;
id.close();
if (value == "0")
{
return true;
}
}
return false;
}

这里有更多关于树莓派gpios的例子:http://www.hertaville.com/introduction-to-accessing-the-raspberry-pis-gpio-in-c.html