gpt4 book ai didi

c++ - 如何为多个模拟引脚编写函数? (阿杜伊诺)

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:44 24 4
gpt4 key购买 nike

所以我正在为一些锅针编写这个小函数。锅只有在转动时才会发送一个值,在静止时,它什么都不发送。这就是我希望它发挥作用的方式。

用一根针就可以正常工作。

我已经达到了它可以与多个引脚一起工作一半的程度。因此,如果我在循环中用两个引脚调用它两次,我会在这两个引脚上取回正确的值。但是我失去了 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

最佳答案

这使用 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);
}

关于c++ - 如何为多个模拟引脚编写函数? (阿杜伊诺),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21116241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com