如何为多个模拟引脚编写功能? (Arduino的)

时间:2014-01-14 14:38:46

标签: c++ function arduino

所以我正在为一些锅针写这个小功能。只有当它被转动时,它才会发送一个值,在静止时,它不发送任何内容。这就是我希望它发挥作用的方式。

一针很好用。

我已经达到了一半可以使用多个引脚。因此,如果我在两个引脚的循环中调用它两次,我会在这两个引脚上找回正确的值。但是我放弃了if语句的功能。基本上我无法弄清楚这一半的后半部分。已经建议使用数组我只是不确定如何继续。

连连呢?谢谢。

    byte pots[2] = {A0, A2};


int lastPotVal = 0;


void setup(){
  Serial.begin(9600);

}


void loop(){

  // get the pin out of the array
  rePot(pots[0]); 
  rePot(pots[1]); 
  delay(10);

}

void rePot(const int potPin){


  // there is probably an issue around here somewhere...


  int potThresh = 2;
  int potFinal = 0; 
  int potVal = 0; 

  // set and map potVal

  potVal = (analogRead(potPin));         
  potVal = map(potVal, 0, 664, 0, 200);  

    if(abs(potVal - lastPotVal) >= potThresh){

      potFinal = (potVal/2);       
      Serial.println(potFinal);

      lastPotVal = potVal; 



     }   // end of if statement

} // end of rePot

1 个答案:

答案 0 :(得分:1)

这使用struct来管理一个底池以及与之关联的数据(它所在的引脚,最后一个读数,阈值等)。然后,rePot()函数被更改为将其中一个结构作为输入,而不仅仅是引脚编号。

struct Pot {
    byte pin;
    int threshold;
    int lastReading;
    int currentReading;
};

// defining an array of 2 Pots, one with pin A0 and threshold 2, the
// other with pin A2 and threshold 3. Everything else is automatically
// initialized to 0 (i.e. lastReading, currentReading). The order that
// the fields are entered determines which variable they initialize, so
// {A1, 4, 5} would be pin = A1, threshold = 4 and lastReading = 5
struct Pot pots[] = { {A0, 2}, {A2, 3} };

void rePot(struct Pot * pot) {
    int reading = map(analogRead(pot->pin), 0, 664, 0, 200);

    if(abs(reading - pot->lastReading) >= pot->threshold) {
        pot->currentReading = (reading/2);
        Serial.println(pot->currentReading);
        pot->lastReading = reading;
    }
}

void setup(){
    Serial.begin(9600);
}

void loop() {
    rePot(&pots[0]);
    rePot(&pots[1]);
    delay(10);
}

稍微不同的是将rePot()更改为将整个数组作为输入的函数,然后只更新整个事物。像这样:

void readAllThePots(struct Pot * pot, int potCount) {
    for(int i = 0; i < potCount; i++) {
        int reading = map(analogRead(pot[i].pin), 0, 664, 0, 200);

        if(abs(reading - pot[i].lastReading) >= pot[i].threshold) {
            pot[i].currentReading = (reading/2);
            Serial.println(pot[i].currentReading);
            pot[i].lastReading = reading;
        }
    }
}

void loop() {
    readAllThePots(pots, 2);
    delay(10);
}