【问题标题】:Using the state of a gpio in an if condition在 if 条件下使用 gpio 的状态
【发布时间】:2019-07-06 14:29:35
【问题描述】:

我有一个函数,在这个函数中我使用的是 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 value;更改为std::string value;
  • @πάντα ῥεῖ 啊,我明白了,这是因为 hardwareID 被声明为指针?这么说: const char *const value;只是另一个指针,我不能只比较两个指针?
  • 通常很难写入常量。
  • @Rob 除了@user4581301 说的,是的。
  • 比较两个指针实际上是比较指针。左边的地址是否与右边的地址匹配?如果是这样,那就是真的。它根本不考虑指针引用的内容。

标签: c++ fstream iostream gpio


【解决方案1】:

您正试图将数据放入 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

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2019-09-13
    • 2014-08-12
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多