I am trying to do a project with an ultrasonic sensor. For this I´m using some new programming techniques, like shortening the setup with an array and a loop. But somehow I dont get it to work. I´ve already tried different type of loops but it won´t working. Hopefully you have an idea what could be wrong.
Thank you
/***************************************************************************************************************************************/
const byte calPin = 7;
const byte buzzPin = 6; const byte trigPin = 9; const byte ledPin = 13;
const byte echoPin = 10; const byte gasPin = 11;
const int ButtonPin[] {calPin};
const int OutputPin[] {buzzPin, trigPin, ledPin};
const int InputPin[] {echoPin, gasPin};
/***************************************************************************************************************************************/
void setup() {
Serial.begin(9600);
byte i = 0;
while (ButtonPin[i] != 0 && OutputPin[i] != 0 && InputPin[i] != 0) //It doesn´t work with a for loop as well
{
pinMode(ButtonPin[i], INPUT_PULLUP);
pinMode(OutputPin[i], OUTPUT);
pinMode(InputPin[i], INPUT);
i++;
}
/* With the normal pin variant it works
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
*/
}
/***************************************************************************************************************************************/
int measureDistance() {
digitalWrite(trigPin, LOW); condition
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
int distance = (duration * 0.034 / 2);
return distance;
}
/***************************************************************************************************************************************/
void loop() {
Serial.println(measureDistance());
}
When will ButtonPin[i] ever be 0? You're just going to read out of bounds of the arrays.
If the arrays have different lengths, you need different loops (or additional logic).
Try this:
for (auto pin : ButtonPin)
pinMode(pin, INPUT_PULLUP);
for (auto pin : OutputPin)
pinMode(pin, OUTPUT);
for (auto pin : InputPin)
pinMode(pin, INPUT);