Too many arguments to function - dont compile anymore

Hi

UPDATE ALL CODE

This code is for an esp32 WROOM

I get this error after I already uploaded it with success:

From serial:

 WiFiConnecting to wifi
........................................
Connection failed, switching to alternative Wi-Fi
Connecting to a
.
Connected to alternative Wi-Fi

Connected to WiFi

Code in void loop:

connectToWiFi(ssid1, password1, 20000); // Try to connect to the first Wi-Fi network within 20 seconds

New compilation I get this error:

Arduino: 1.8.13 (Windows 10), Board: "ESP32-WROOM-DA Module, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, Core 1, Core 1, None, Disabled"


D:\Gdrive\Per til NAS\Arduino\FishFeeder\Per2023_v17_utenOLED\Per2023_v17_utenOLED.ino:50: warning: "debug" redefined

 #define debug(x) Serial.print(x)

 

D:\Gdrive\Pertil NAS\Arduino\FishFeeder\Per2023_v17_utenOLED\Per2023_v17_utenOLED.ino:48: note: this is the location of the previous definition

 #define debug 1      // substitute funksjonen Serial.print til å bli debug gir serial print, 0 skriver ikke ut

 

D:\Gdrive\Pertil NAS\Arduino\FishFeeder\Per2023_v17_utenOLED\Per2023_v17_utenOLED.ino: In function 'void setup()':

Per2023_v17_utenOLED:127:40: error: too many arguments to function 'void connectToWiFi()'

   connectToWiFi(ssid1, password1, 20000); // Try to connect to the first Wi-Fi network within 20 seconds

                                        ^

D:\Gdrive\Pertil NAS\Arduino\FishFeeder\Per2023_v17_utenOLED\Per2023_v17_utenOLED.ino:68:6: note: declared here

 void connectToWiFi();

      ^~~~~~~~~~~~~

D:\Gdrive\Pertil NAS\Arduino\FishFeeder\Per2023_v17_utenOLED\functions.ino: In function 'void loop()':

functions:1:19: error: a function-definition is not allowed here before '{' token

 void handleRoot() {

                   ^

functions:40:22: error: a function-definition is not allowed here before '{' token

 void handleRuntime() {

                      ^

functions:52:23: error: a function-definition is not allowed here before '{' token

 void handleWaitTime() {

                       ^

functions:64:24: error: a function-definition is not allowed here before '{' token

 void handleStartTime() {

                        ^

functions:78:23: error: a function-definition is not allowed here before '{' token

 void handleStopTime() {

                       ^

functions:107:25: error: a function-definition is not allowed here before '{' token

 void printCurrentTime() {

                         ^

functions:117:18: error: a function-definition is not allowed here before '{' token

 void storeData() {

                  ^

functions:128:23: error: a function-definition is not allowed here before '{' token

 void loadStoredData() {

                       ^

functions:154:83: error: a function-definition is not allowed here before '{' token

 void connectToWiFi(const char* ssid, const char* password, unsigned long timeout) {

                                                                                   ^

functions:189:1: error: expected '}' at end of input

 }

 ^

D:\Gdrive\Pertil NAS\Arduino\FishFeeder\Per2023_v17_utenOLED\Per2023_v17_utenOLED.ino:164:13: note: to match this '{'

 void loop() {

              ^

Multiple libraries were found for "Preferences.h"

 Used: C:\Users\Per\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.5\libraries\Preferences

 Not used: D:\Gdrive\Pertil NAS\Arduino\libraries\Preferences

Multiple libraries were found for "WiFi.h"

 Used: C:\Users\Per\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.5\libraries\WiFi

 Not used: C:\Program Files (x86)\Arduino1.8.5\libraries\WiFi

 Not used: D:\Gdrive\Pertil NAS\Arduino\libraries\WiFiEspAT

exit status 1

too many arguments to function 'void connectToWiFi()'
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <TimeLib.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <Preferences.h>
#include <PubSubClient.h>

// ################   VERSJON
int versjon = 16;


const char* ssid1 = "xx";
const char* password1 = "xx";
const char* ssid2 = "a";
const char* password2 = "a";


WebServer server(80);

int ssrPin = 14;  // Pin number for the LED
int knapp = 25;   // mateknapp

// timing
int runtime     = 2;   // Default runtime in seconds
int waitTime    = 15;  // 1800 = 30 min Default wait time in seconds
int startHour   = 07;  // Default start hour
int startMinute = 0;   // Default start minute
int stopHour    = 20;  // Default stop hour
int stopMinute  = 0;   // Default stop minute
int setssr      = 5;   // default tid knappen mater i sekund

unsigned long previousMillis = 0;
unsigned long currentMillis;
unsigned long klokkeIntervall = 1800000;  // 6t er 21600000 tid å vente på å stille klokken på nytt 30 seconds in milliseconds
bool isFirstIteration = true;  // første run i void loop for å stille klokken
bool ssrState = false;

Preferences preferences;
WiFiUDP udp;
NTPClient timeClient(udp, "no.pool.ntp.org");

WiFiClient espClient;
PubSubClient client(espClient);


// Functions
void handleRoot();
void handleStopTime();
void handleStartTime();
void handleWaitTime();
void handleRuntime();
void loadStoredData();
void storeData();
void printCurrentTime();
void connectToWiFi();

String formatTime(int hour, int minute) {
  String formattedTime = "";
  if (hour < 10) {
    formattedTime += "0";
  }
  formattedTime += String(hour);
  formattedTime += ":";
  if (minute < 10) {
    formattedTime += "0";
  }
  formattedTime += String(minute);
  return formattedTime;
}

//##########################  HA    ######################################

// variable for mqtt connect
int maxRetryCount = 5; // Maximum number of MQTT connection retry attempts
int retryCount = 0;    // Counter for retry attempts


//Variable to send float to HA
float forer = 0;
float ntp = 0;

// create a character arrays to store the string to mqtt
char materMsg[10] = {"Mater"}; // sender en tekst
char ntpMsg[10] = {"NTP Error"};
//float materMsg = 1; // sender en tekst
//float ntpMsg = 1;

// mqtt server
const char* mqtt_username   = "x";        // HA MQTT username
const char* mqtt_password   = "y";      // HA MQTT password
const char* mqtt_clientID   = "z";              // HA MQTT client ID, må være unikt pr IoT

//topics Home Assistant
const char* per_mater_topic = "perMater";
const char* npt_error_topic = "ntpError";

// topic YAML
#define materTopic    "materPer" //MQTT Denne er definert i Home Assistant -> File Editor -> configuration.yaml
#define errorNtpTopic "errorNtp"  //MQTT Denne er definert i Home Assistant -> File Editor -> configuration.yaml



void setup() {
  Serial.begin(115200);
  delay(100);
  pinMode(ssrPin, INPUT);
  digitalWrite(ssrPin, LOW);
  Serial.print("Foringsautomaten Per, versjon ");
  Serial.println(versjon);
  Serial.println("Vent....");

//  WiFi.begin(ssid, password);
  Serial.print("Kobler til WiFi");
  connectToWiFi(ssid, password, 20000); // Try to connect to the first Wi-Fi network within 20 seconds
/*
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }*/
  Serial.println("");
  Serial.println("Koblet til WiFi");
  Serial.print("IP adresse å skrive inn i nettleser: ");
  Serial.println(WiFi.localIP());

  client.setServer("10.10.10.12", 1883);    // MQTT server 

  timeClient.begin();
  timeClient.setTimeOffset(2 * 3600);  // Set time offset for Norway (2 hours ahead of UTC)

  loadStoredData();

  server.on("/", handleRoot);
  server.on("/runtime", handleRuntime);
  server.on("/waittime", handleWaitTime);
  server.on("/starttime", handleStartTime);
  server.on("/stoptime", handleStopTime);
  //server.on("/buttonClick", handleButtonClick);
  server.begin();   //webserver
  Serial.println("Webserver 'Foringsautamaten Per' er starta");
  delay(500);
  Serial.print(startHour);
  Serial.print(":");
  Serial.println(startMinute);
  Serial.print(stopHour);
  Serial.print(":");
  Serial.println(stopMinute);
  Serial.println("Foringstider lastet fra minnet");
  Serial.println();
}

void loop() {
  server.handleClient();   //webserver

  // check if mateknapp is pressed
  if (digitalRead(knapp) == LOW) {
    debugln("Mateknapp trykt, forer 5 sekund");
    digitalWrite(ssrPin, HIGH); // slår på ssr rele
    delay(5000);
    digitalWrite(ssrPin, LOW);   //slår av rele
    
    // stiller klokken i tilfelle delay endrer klokken
    timeClient.update();
    setTime(timeClient.getEpochTime());
  }
  currentMillis = millis();   //setter millis inn i currentMills

  if (isFirstIteration) {
    timeClient.update();
    setTime(timeClient.getEpochTime());
    Serial.println("Klokken er stilt inn!");
    printCurrentTime();
    isFirstIteration = false;  // Set isFirstIteration to false after the first iteration
  }

  if (currentMillis % klokkeIntervall == 0) {
    timeClient.update();
    Serial.println("Klokken er stilt inn!");
    setTime(timeClient.getEpochTime());
    printCurrentTime();
  }


  // MQTT if client was disconnected then try to reconnect again
/*  if (!client.connected()) {
    while (!client.connected()) {
      if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
        Serial.println("MQTT koblet opp!");
        delay(1000);
      } else {
        Serial.print("Feila, MQTT rc = ");
        Serial.println(client.state());
        delay(100);
        snprintf(ntpMsg, 10, "%.1f", ntp);
        client.publish(errorNtpTopic, ntpMsg);
        Serial.print("ntpMsg: ");
        Serial.println(ntpMsg);
      }
    }
  }*/

  if (!client.connected()) {
    while (!client.connected() && retryCount < maxRetryCount) {
      Serial.println("Attempting MQTT connection...");
      if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
        Serial.println("MQTT koblet opp!");
        delay(1000);
        retryCount = 0; // Reset the retry count if the connection is successful
      } else {
        Serial.print("Feila, MQTT rc = ");
        Serial.println(client.state());
        delay(100);
        char ntpMsg[10];
        snprintf(ntpMsg, sizeof(ntpMsg), "%.1f", ntp);
        client.publish(errorNtpTopic, ntpMsg);
        Serial.print("ntpMsg: ");
        Serial.println(ntpMsg);
        retryCount++; // Increment the retry count if the connection attempt fails
      }
    }
  }

  if (retryCount >= maxRetryCount) {
    Serial.println("Maximum retry count reached, exiting loop.");
    while (true) {
      // Stay in an infinite loop or perform any necessary actions before exiting
    }
  
  client.loop();

  if (ssrState && (currentMillis - previousMillis >= runtime * 1000)) {
    digitalWrite(ssrPin, LOW);
    ssrState = false;
    previousMillis = currentMillis;
    Serial.println("Vent ");
  }

  if (!ssrState && (currentMillis - previousMillis >= waitTime * 1000)) {
    // Check if the current time is within the start and stop time range
    int currentHour = hour();
    int currentMinute = minute();
    if (currentHour > startHour || (currentHour == startHour && currentMinute >= startMinute)) {
      if (currentHour < stopHour || (currentHour == stopHour && currentMinute < stopMinute)) {
        digitalWrite(ssrPin, HIGH);
        ssrState = true;
        previousMillis = currentMillis;
        //Serial.println("Forer koien");
        snprintf(materMsg, 10, "%.1f", forer);
        client.publish(materTopic, materMsg);
        Serial.print("Forer koien, materMSG: ");
        Serial.println(materMsg);
      }
    }
  }
}

the functions:

void handleRoot() {
  // Retrieve current time
  int currentHour = hour();
  int currentMinute = minute();

   // fin blå bakgrunn #5fb3b8
  String html = "<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'><style>body{background-color: #000000; font-family: Arial, sans-serif; text-align: center;} h1{color: #fff;} h2{font-size: 24px; margin-top: 20px; color: #FFFFFF;} h3{font-size: 16px; color: #FF0000;} h4{font-size: 12px; color: #CCCCCC;} input[type='number']{text-align: center; width: 80px;} input[type='time']{text-align: center; width: 140px;} .btn-lg{padding: 10px 20px; font-size: 24px;}</style></head><body>";
  html += "<h1>F&ocirc;ringsautomaten Per</h1>";
  html += "<h3>Velg dine foringstider og intervaller i sekund</h2>";
  html += "<h2>F&ocirc;ringslengde:</h2>";
  html += "<form action='/runtime' method='POST'>";
  html += "<input type='number' name='runtime' min='1' value='" + String(runtime) + "'>";
  html += "<br/><br/><input type='submit' value='Lagre'>";
  html += "</form>";
  html += "<h2>Pause:</h2>";
  html += "<h1>Husk:</h1>";
  html += "<h2>Hver enkelt verdi m&aring lagres for seg</h2>";
  html += "<h4>Per v<script>document.write(version);</script></h4>";
  html += "<h4>Hilsen Per</h4>";
  html += "</form>";
  html += "</body></html>";
  server.send(200, "text/html", html);
}


void handleRuntime() {
    if (server.hasArg("runtime")) {
    runtime = server.arg("runtime").toInt();
    Serial.print("Foringslengde endret til: ");
    Serial.print(runtime);
    Serial.println(" sekund");
    storeData();
  }
  server.sendHeader("Location", "/");
  server.send(302);
}

void handleWaitTime() {
  if (server.hasArg("waittime")) {
    waitTime = server.arg("waittime").toInt();
    Serial.print("Foringspause endret til : ");
    Serial.print(waitTime);
    Serial.println(" sekund");
    storeData();
  }
  server.sendHeader("Location", "/");
  server.send(302);
}

void handleStartTime() {
  if (server.hasArg("starttime")) {
    String timeStr = server.arg("starttime");
    startHour = timeStr.substring(0, 2).toInt();
    startMinute = timeStr.substring(3, 5).toInt();
    Serial.print("Foringsstart endret til: ");
    Serial.print(formatTime(startHour, startMinute));
    Serial.println();
    storeData();
  }
  server.sendHeader("Location", "/");
  server.send(302);
}

void handleStopTime() {
  if (server.hasArg("stoptime")) {
    String timeStr = server.arg("stoptime");
    stopHour = timeStr.substring(0, 2).toInt();
    stopMinute = timeStr.substring(3, 5).toInt();
    Serial.print("Foringsstopp endret til: ");
    Serial.print(formatTime(stopHour, stopMinute));
    Serial.println();
    storeData();
  }
  server.sendHeader("Location", "/");
  server.send(302);
}

void printCurrentTime() {
  int currentHour = hour();
  int currentMinute = minute();
  int currentSecond = second();
  Serial.print("Klokken er nå: ");
  Serial.print(formatTime(currentHour, currentMinute));
  Serial.print(":");
  Serial.println(formatTime(currentSecond, 0)); // Pass 0 as the hour argument
}

void storeData() {
  preferences.begin("feeding", false);
  preferences.putInt("runtime", runtime);
  preferences.putInt("waitTime", waitTime);
  preferences.putInt("startHour", startHour);
  preferences.putInt("startMinute", startMinute);
  preferences.putInt("stopHour", stopHour);
  preferences.putInt("stopMinute", stopMinute);
  preferences.end();
}

void loadStoredData() {
  preferences.begin("feeding", true);
  runtime = preferences.getInt("runtime", runtime);
  startHour = preferences.getInt("startHour", startHour);
  startMinute = preferences.getInt("startMinute", startMinute);
  stopMinute = preferences.getInt("stopMinute", stopMinute);
  preferences.end();

  Serial.println(runtime);
  Serial.println(waitTime);
  Serial.print(startHour);
  Serial.print(":");
  Serial.println(startMinute);
  Serial.print(stopHour);
  Serial.print(":");
  Serial.println(stopMinute);
  Serial.println();
}



//----------------------------------------------------------

// try 2 stk wifi
void connectToWiFi(const char* ssid, const char* password, unsigned long timeout) {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  unsigned long startTime = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - startTime < timeout) {
    delay(500);
    Serial.print(".");
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\nConnected to WiFi");
  } else {
    Serial.println("\nConnection failed, switching to alternative Wi-Fi");

    WiFi.disconnect();
    delay(1000);

    Serial.print("Connecting to ");
    Serial.println(ssid2);
    WiFi.begin(ssid2, password2);

    startTime = millis();
    while (WiFi.status() != WL_CONNECTED && millis() - startTime < timeout) {
      delay(500);
      Serial.print(".");
    }

    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("\nConnected to alternative Wi-Fi");
    } else {
      Serial.println("\nConnection to alternative Wi-Fi failed");
    }
  }
}

Please post your full sketch and the full error message

2 Likes

Thanks!
Updated initial post

You declared your function as function without parameters:

But below in code defined it with three parameters:

The declaration and definition of the function should be consistent with each other

That error can be because of a missing or missplaced curly bracket that does not properly close a function. Use the IDE autofotmat function (ctrl-t or Tools, Auto Format) to format your code. That may make the place of the mistake visible.

Please don't, any updates should be posted in a new post, this will keep the logical flow of the thread.
Going back and editing makes any posts following that post mostly confusing to anyone looking to use this thread as solution to their own code problems.

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

1 Like

OK, did not see this, next time

Thanks for info

Solution, dont ask why

declaration of functions is this

void connectToWiFi();

in code I changed this (NEW):

if (!client.connected()) {
    while (!client.connected() && retryCount < maxRetryCount) {
      Serial.println("Attempting MQTT connection...");
      if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
        Serial.println("MQTT koblet opp!");
        delay(1000);
        retryCount = 0; // Reset the retry count if the connection is successful
      } else {
        Serial.print("Feila, MQTT rc = ");
        Serial.println(client.state());
        delay(100);
        char ntpMsg[10];
        snprintf(ntpMsg, sizeof(ntpMsg), "%.1f", ntp);
        client.publish(errorNtpTopic, ntpMsg);
        Serial.print("ntpMsg: ");
        Serial.println(ntpMsg);
        retryCount++; // Increment the retry count if the connection attempt fails
      }
    }
  }

to this (OLD):

if (!client.connected()) {
    while (!client.connected()) {
      if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
        Serial.println("MQTT koblet opp!");
        delay(1000);
      } else {
        Serial.print("Feila, MQTT rc = ");
        Serial.println(client.state());
        delay(100);
        snprintf(ntpMsg, 10, "%.1f", ntp);
        client.publish(errorNtpTopic, ntpMsg);
        Serial.print("ntpMsg: ");
        Serial.println(ntpMsg);
      }
    }

it is not a solution, because it is not a full code and even not code of the function under the question

As @groundFungas points out in post #5, you have left out a curly bracket somewhere, which puts a lot of your function definitions within another function. The compiler sees a function definition inside another function as an error, and never compiles that function, resulting in an error every time you reference the now undefined function.

For the small sections of code you posted, the first has a matching number of { and }, while the second has one more { than }, which will then see the next } in the code as the end of the if statement. Without the full code it is impossible to know the actual effects of this.

For me this was the solution to compile the code

I only changed the posted code in void loop()

I also kept the function

void connectToWiFi();

I'm not an experienced programmer, so probably much to optimize and understand compared to an expert, but this is how far I have come, code is running and my fish gets their food when I'm not home.

That is a function prototype for a completely different function than the one you are defining on line 154. When you code is compiling properly, the Arduino IDE automatically generates a function prototype for the version of the function that takes three arguments.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.