If your scan function void scan() already gets the data it needs correctly and stores it in an array, Then you can use the array directly in the loop() function without having to call analogRead() again to get the data.
You can declare the scanResults array as a global variable so that it can be accessed in the loop() function. In the loop() function, when the counter scanCounter reaches 3, you can do subsequent operations directly with the data in the scanResults array instead of calling the void scan() function again.
Here is an example of the modified code:
// 定义存储扫描结果的数组和计数器
int scanResults[3];
int scanCounter = 0;
void setup() {
Serial.begin(9600); // 初始化串口通信
}
void loop() {
// 扫描数据并存储到数组中
scan(); // 假设您的扫描函数为 void scan()
scanCounter++;
// 检查是否已经扫描了3次
if (scanCounter == 3) {
scanCounter = 0; // 重置计数器
// 等待按键按下
while (digitalRead(2) == HIGH) {
delay(10);
}
// 按键按下后打印数据
Serial.print("Scan results: ");
for (int i = 0; i < 3; i++) {
Serial.print(scanResults[i]);
Serial.print(" ");
}
Serial.println();
// 等待按键释放
while (digitalRead(2) == LOW) {
delay(10);
}
}
}
Note that in the code example above, the void scan() function needs to be defined and implemented before the loop() function. Also, because the scanResults and scanCounter arrays are global variables, they need to be declared outside of the setup() function.