Search code examples
arduinoarduino-c++

Arduino fuction outside loop


im trying to use a func inside Loop in Arduino. It wont work; Params are numeroPin, sonido and delay. I tried everything but it seems like im not able to fix this

void setup() {


 for(int i = 2 ; i<=9; i++){
   pinMode(i, OUTPUT);
 }


}


 int C4 = 262; // LED 4
 int D4 = 294; // LED 5
 int E4 = 330; // LED 6
 int F4 = 349; // LED 7
 int G4 = 392; // LED 8
 int C5 = 523; // LED 9


void sonar(numeroPin, sonido, delay) {
 tone(2, sonido);
 digitalWrite(numeroPin, HIGH);
 delay(delay);
 digitalWrite(numeroPin, LOW);
}




void loop() {


 sonar(4, C4, 1000);
 sonar(5, D4, 1000);
 sonar(6, F4, 167);
 sonar(7, E4, 167);
 sonar(5, D4, 167);
 sonar(8, C5, 1000);
 sonar(9, G4, 500);




}

I tried it and it fails to compile.


Solution

  • declare parameters type in your function : void sonar(int numeroPin, int sonido, int mydelay) and avoid 'delay' as variable name as it is system reserved.

    void setup() {
    
      for (int i = 2 ; i <= 9; i++) {
        pinMode(i, OUTPUT);
      }
    }
    
    int C4 = 262; // LED 4
    int D4 = 294; // LED 5
    int E4 = 330; // LED 6
    int F4 = 349; // LED 7
    int G4 = 392; // LED 8
    int C5 = 523; // LED 9
    
    void sonar(int numeroPin, int sonido, int mydelay) {
      tone(2, sonido);
      digitalWrite(numeroPin, HIGH);
      delay(mydelay);
      digitalWrite(numeroPin, LOW);
    }
    
    void loop() {
      sonar(4, C4, 1000);
      sonar(5, D4, 1000);
      sonar(6, F4, 167);
      sonar(7, E4, 167);
      sonar(5, D4, 167);
      sonar(8, C5, 1000);
      sonar(9, G4, 500);
    }