0

Is it possible to have code running while also listening for local inputs via ip address? I thought it would go in the 'while' portion but I presume that only responses when the ip is loaded.

void loop() {

  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while (!client.available()) {
    delay(1);   
  }
  String query = client.readStringUntil('\r');
  client.flush();

  if (query.indexOf("/open") != -1)  {
    open_fast();
  } else if (query.indexOf("/close") != -1)  {
    close_fast();
  }

  sensor = analogRead(A0);
  sensor = map(sensor, 0, 1023, 0, full);

  Serial.print(sensor);
  Serial.print("  ");
  Serial.println(pos);

  if (sensor > pos) {
    open_slow();
    delay(1000);
  } else if (sensor < pos) {
    close_slow();
    delay(1000);
  }
  delay(100);

}
  • instead ofif (!client) { return; } use if (client) { /* handle client */ }? – Juraj Apr 30 '19 at 4:58
  • @Juraj What does that do? – Vimmy Apr 30 '19 at 19:04
  • take a coding course – Juraj May 1 '19 at 3:55
0

The problem is that at

while (!client.available()) {
  delay(1);
}
// your wifi code

you wait for a wifi event and in that time you obviously can't read the sensor. Just poll for incoming requests by doing it like

if (client.available()) {
  // your wifi code
}

This way your loop skips the wifi-routine if there is nothing to do and proceeds with reading the sensor.

As mikrocontrollers usually don't run a OS, you don't have multitasking which you have to implement yourself. Generally you have to avoid using delay loops when you want several tasks being executed "parallely".

| improve this answer | |
  • The difference between "if" and "while" in this situation, does it negatively effect the wifi or mcu by polling the internet in any different way or are they basically the same? – Vimmy Apr 30 '19 at 19:05
  • client.available() just checks if there are any requests in the esp's input buffer, the actual communication has allready taken place at that time and is handled by the esp's hardware. But there is a fundamental difference between if and while: if is only a single test for wifi activity, while delays your loop until wifi activity and is not what you want. – Sim Son May 2 '19 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.