【问题标题】:Acessing/Adressing variables with strings and int in Arduino在 Arduino 中使用字符串和 int 访问/寻址变量
【发布时间】:2015-04-27 19:38:44
【问题描述】:

已经有一个关于在 Arduino 中使用字符串寻址变量的问题,但给出的答案不适用于我的问题。

我有多个传感器(大约 14 个,并且数量可能会增加)连接到我的 Arduino,我还有继电器、引擎和 RFID。我正在创建一个函数来检查所有传感器是否活动

基本思路是这样的:

#define Sensor_1 2
#define Sensor_2 3
#define Sensor_3 4
#define Sensor_4 5
#define Sensor_5 6

int checkSensors(){
    int all_active = 0;
    int num_sens = 5; 
    int n;
    int active_sens = 0; 

    for(n= 1; n <= num_sens; n++) {
        if( !digitalRead("Sensor_" + n)) {
            active_sens= active_sens+ 1;    
        }
        else {
            all_active = 0;
            return ( all_active);
        }
    }

    if(active_sens== num_sens) {
        all_active = 1;
        return(all_active);
    }
}

问题是:我想对变量 Sensor_n 进行寻址,但我找不到解决方法。我收到的错误消息是指 digitalRead("Sensor_" + n ) 命令。

错误:从 'const char*' 到 'uint8_t {aka unsigned char}' 的无效转换 [-fpermissive]

我已经尝试在 String = "Sensor_" 中使用 "Sensor_",我尝试强制将类型转换为 uint8_t,但错误消息显示它失去了精度。

我也尝试了 .toCharArray 命令,但也失败了。

有没有办法通过字符串+int来访问变量?

我对 PHP 中的“松散”变量比较熟悉,所以这给我带来了很多麻烦。

【问题讨论】:

  • C++ 不是 PHP。您可能希望将名称和关联的 enum 值填充到 std::map 或其他类型的容器(即使它是静态数组)然后到 find 以根据字符串检索值。跨度>

标签: c++ c string arduino sensors


【解决方案1】:

您的代码存在一些问题。首先,您无法通过动态使用作为变量名称的字符串来获取变量或定义的值。它在 C 中不是这样工作的。最简单的方法是使用一个数组,然后通过它索引。为了使这项工作顺利进行,我将 for 循环更改为从 0 开始计数,因为数组从 0 开始索引。我更改了 all_active 逻辑,假设稍后您将想知道有多少传感器处于活动状态而不是只是它们是否都处于活动状态。如果您不希望那样,那么您的逻辑也比需要的更复杂。它可以只在 for 循环结束时返回 1,因为所有这些都必须通过测试才能到达那里。

#define Sensor_1 2
#define Sensor_2 3
#define Sensor_3 4
#define Sensor_4 5
#define Sensor_5 6
int sensors[] = {Sensor_1, Sensor_2, Sensor_3, Sensor_4, Sensor_5};

int checkSensors(){
    int all_active = 1;
    int num_sens = 5; 
    int n;
    int active_sens = 0; 

    for(n= 0; n < num_sens; n++){
        if( !digitalRead(sensors[n])){
            active_sens= active_sens+ 1;    
        }
        else {
            all_active = 0;
        }
     }
     return all_active;
}

【讨论】:

    【解决方案2】:

    在 C 中这条线将不起作用

    if( !digitalRead("Sensor_" + n))
    

    你不能在 C 中构建这样的字符串。由于你没有发布函数 digitalRead(),我认为它需要一个 char* 类型,这里是一个字符串,在 C 中你可以这样构建

    char senstr[50];
    sprintf(senstr, "Sensor_%d", n);
    ...
    if (!digitalRead(senstr)) { ...
    

    作为一个附带问题,请习惯于从0 迭代循环。您添加1 以与人类交互。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多