need for client.connect to not effect millis blink pattern

The code in the attachment is pretty much a replica of the code generously provided by Robin2

The reason for the modification is to address an issue that came up in one of my experiments where if the client is not able to connect to the server, everything goes to…

I would like for the if ( client.connect(serverName, 80) )

void Thomas499CodePart2(){

if (LedOn == HIGH)
{ digitalWrite(15,LOW);
if ( client.connect(serverName, 80) )

to not interfere with the millis timer, regardless how long it takes for the connection to happen, or if the connection happens at all, but would ideally continue trying to connect. It would be acceptable to slow the led blinks to every 3 or 4 seconds, but preferably no more than that, but they must stay in sync. It should be assumed that the client (the arduino) may not make a connection to the server (another arduino) ServerName but the led blinks must not be thrown out of sync. Is this possible?

If so, how should it be approached? Would that be some form of While statement?

----------------------------------edit----------------------------------
Did I upload the file correctly? First time uploading code like this (forced due to size of file) . I can’t figure out how to open it myself

ConnectQuitMessingWithMillis_.ino (9.38 KB)

To start, you must reduce the number of retries the w5100 attempts. The default is 8. This takes about 1.6 seconds to complete if the connection is not established. You can reduce that to 200ms.

#include <utility/w5100.h>

// add this to setup after Ethernet.begin()
W5100.setRetransmissionCount(1);

I am using WiFi. does the provided code need to change because it isn’t Ethernet?

Here is where I put the added code

#include <SPI.h>
#include <WiFi.h>
#include <utility/w5100.h>

// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);

// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// add this to setup after Ethernet.begin()
W5100.setRetransmissionCount(1);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the web server on port 80

printWifiStatus(); // you’re connected now, so print out the status
}

I am getting an error message that says This report would have more information with
“Show verbose output during compilation”
enabled in File > Preferences.
Arduino: 1.0.6 (Windows NT (unknown)), Board: “Arduino Uno”
ConnectQuitMessingWithMillis_.ino: In function ‘void setup()’:
ConnectQuitMessingWithMillis_:100: error: ‘W5100’ was not declared in this scope

I've been playing around with this mod that SuferTim Suggested.

I have concluded the Ethernet client.connect will last 1.6 seconds as Tim mentioned. However, the WiFi client.connect will last 10 seconds to my understanding at least.

I was about to get the mod working for the Ethernet version but not the WiFi version.

Am I missing something? In my experience sometimes you have to add things to the WiFi versions like WiFi.config(ip); where as you wouldn't have to in the Ethernet versions.

What am I missing?

I’ve been looking into options to address this. As I now understand #include <utility/w5100.h> was written only to work with the Ethernet Shield, and not the WiFi shield. I have not been able to find anything similar to this that will work with the WiFi shield.

The only option I have been able to come up with that will allow the arduino client to attempt to connect to the server without messing with the millis blink pattern is to attach a second arduino via wire to the first arduino. The first arduino will send a message to the second arduino, and that arduino attempts to connect to the server.

Is there any other way of doing this that would not require me to purchase a second arduino?

Have you ever looked into Timer Interrupts?

good tutorial here

I did try to use a while statement combined with a (blinkwithoutdelay) format, before the client.connect function, but that didn't seem to work.

I did experiment with an Interrupt function (button press, not timer) before, but concluded if the button was pressed at the wrong time, when things are flipping themselves on and off, if the interrupt went off in the middle of a void( whatever) section, and it didn't complete the loop and that last (turn this on/off) boolean wasn't tripped, the whole program was effected and I could only correct it by restarting the arduino.

Is it possible to write the program so the timer interrupt function is only valid during the (client.connect) stage? If the time is up at any other part of the code, I would rather the loop be completed which may take a fraction more of a second, but this way the code wouldn't be effected if it's in the wrong spot at the wrong time.

Thomas499:
Is it possible to write the program so the timer interrupt function is only valid during the (client.connect) stage? If the time is up at any other part of the code, I would rather the loop be completed which may take a fraction more of a second, but this way the code wouldn't be effected if it's in the wrong spot at the wrong time.

It is cool to be able to blink unaffected by the rest of the code... as you have experienced, millis() timers are not immune to blocking.

Did you read the article? short answer is 'it depends'

So, it depends on what other things you are doing in your sketch... Tone, Delay, etc.

I would recommend that you create a blinking LED with a interrupt timer, just like in the example. Mess around with it so you understand how it works. Once you go through the exercise you can will likely be able to answer the question based on what your program does.

If you have blocking code, like what you are experiencing, than the timer interrupt may be your solution.

hint:

ISR(TIMER1_COMPA_vect)
{
    if (myConditionIsTrue) digitalWrite(LEDPIN, !digitalRead(LEDPIN));
    else digitalWrite(LEDPIN, LOW);
}

That's probably not too much for an ISR...
:wink:

I did read the example you provided a dozen times or so. The formulas/logic behind them just aren’t clicking. It reminds me a lot of shake spear. I never could figure out what they were trying to say in that book.

Here is the example I put together based on the reference you provided, with the client.connect added in, along with my notes that I made for quick reference.

// Arduino timer CTC interrupt example
// www.engblaze.com
 
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>
 
#define LEDPIN 6 // saves trouble of writing stuff below, and in setup. 
 #include <SPI.h>
#include <WiFi.h>

  char ssid[] = "mynetwork";  //  your network SSID (name)
char pass[] = "mypassword";       // your network password
int keyIndex = 0;                 // your network key Index number (needed only for WEP)

IPAddress ip(192,168,1,177); // first 3 spaces need to match your internet settings, the last space needs to be a number not currently used on the system
int status = WL_IDLE_STATUS;
WiFiServer server(80);
WiFiClient client;
byte serverName[] = { 192, 168, 1, 174 }; // first 3 spaces need to match your internet settings, the last space needs to be a number not currently used on the system and must be different than IpAdress number 


void setup()
{
    pinMode(LEDPIN, OUTPUT);
    pinMode(3,INPUT);
    
    WiFi.config(ip);
  Serial.begin(9600);      // initialize serial communication
  pinMode(2,INPUT);        // button 1 (led on)
  pinMode(3,INPUT);        // button 2 (led off)
  pinMode(6,OUTPUT);       // led
  pinMode(15, OUTPUT);      // set the LED pin mode
  while(Serial.available()>0) Serial.read(); // clear out any sloppy leftovers

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);       // don't continue
  }

  String fv = WiFi.firmwareVersion();
  if ( fv != "1.1.0" )
    Serial.println("Please upgrade the firmware");

  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) {

    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection:
    delay(10);
  }
  server.begin();                           // start the web server on port 80
  printWifiStatus();                        // you're connected now, so print out the status
}
    

 
    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0 TCCRIA stands for 
    TCCR1B = 0;     // same for TCCR1B
 
    // set compare match register to desired timer count:
    OCR1A = 15624;                      /* as far as I can tell 
                                           (target time) = (timer resolution) * (# timer counts + 1)
                                           (# timer counts + 1) = (target time) / (timer resolution)
                                           (# timer counts + 1) = (1 s) / (6.4e-5 s) //--------pretty sure (1 s) means one second, 6.4e-5 s refer to (Note: Complicated mess)
                                           (# timer counts + 1) = 15625
                                           (# timer counts) = 15625 - 1 = 15624
                                           
                                           (Note: Complicated mess)
                                           If we set CS10 and CS12 using TCCR1B |= (1 << CS10); and TCCR1B |= (1 << CS12);, we divide our clock source by 1024. 
                                           This gives us a timer resolution of 1/(16*10^6 / 1024), or 6.4e-5 seconds.
                                           
                                           So I think this means whatever CS12 is supposed to be, you take it and shift it right to 2^(1) which equals 1. That must be where the first 1 comes from
                                           I give up.... 
                                        */   


    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);             // TCCR1B stands for Timer/Counter Control Register (WGM12 = ???)
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR1B |= (4 << CS10);              // TCCR1B stands for Timer/Counter Control Register (CS10 is how fast the clock is commanded to run... I think) So you take 4 and shift it right to 2^(4) ??? What? 
    TCCR1B |= (4 << CS12);              // TCCRIB stands for Timer/Counter Control Register (CS12 is how fast the clock is commanded to run... I think) So you take 4 and shift it right to 2^(4)??? What?
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);            // TIMSK1 stands for Timer/Counter1 Interrupt Mask Register (OCIE1A = ???) 
    // enable global interrupts:
    sei();
}
 
void loop()
{
  if (digitalRead(3) == HIGH)
  Serial.println("trying to connect"); // Don't know what to expect so I would like for Serial.print to tell me it's trying to connect. 
          { if ( client.connect(serverName, 80) ) // Should try to connect for 10 seconds, which would freeze blink function if the ISR doesn't do it's job. We shall see
            { Serial.println("connected");
        // Do stuff
            client.println("Connection: close");
            client.println();
            } else { // if you didn't get a connection to the server:
                     Serial.println("connection failed");
                     client.stop();
                   }

}
}
 

ISR(TIMER1_COMPA_vect)  // Interrupt Service Routine
{
    if (!client.connected()) 
    {digitalWrite(LEDPIN, !digitalRead(LEDPIN)); // if not connected, pin 6 should turn on.... I think
  Serial.println("timer interupted"); 
client.stop();}
    else digitalWrite(LEDPIN, LOW);              // if connected, pin 6 should be off
}


    void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);

That is about the most poorly structured code posted toady. The indenting is piss-poor, and the code on the same line as the { violates every coding style.

Chuck Norris, compared to your work I would agree everyone elses work is by definition "Piss Poor".

the code on the same line as the { violates every coding style.

I didn't know but now I do. Until a month ago I had never seen a line of code in my life. To me, putting the { and then a space followed by code made it easier to see where the brackets begun, and ended. The examples all had the { at the end of a line, but you couldn't tell where they ended easily. My way, shows where they end very clearly.

It won't happen again.

To me, putting the { and then a space followed by code made it easier to see where the brackets begun, and ended.

The two usual style are

if(something) {
   // Do something
}

or

if(something)
{
   // Do something
}

My preference is the latter, where it is very clear where the block starts and ends.

Your style

if(something)
{  // Do something
}

is unconventional, and doesn't contribute much to legibility that I can see. YMMV.

I agree with Paul that your formatting needs work. It makes it impossible to follow.

that being said, you want to do something like this:

#define LEDPIN 5
// do your variable initialization and create your WiFi instances
boolean myCondition = false;

void setup()
{
  // do all of your other setup stuff
  //
  // then do all of your timer setup instructions that go in setup()
}

void loop()
{
  // do your normal loop() stuff
  //
  // when you get to your blocking code... *** if you put WiFi calls here...
  myCondition = true;
  // do blocking code
  myCondition = false;
}

ISR(TIMER1_COMPA_vect)
{
    if (myCondition) digitalWrite(LEDPIN, !digitalRead(LEDPIN));
    else digitalWrite(LEDPIN, LOW);
}

*** This will flash your led during your WiFi communications

is unconventional, and doesn't contribute much to legibility that I can see. YMMV.

As you said (YMMV) "your millage may vary"

In my experience, it's hard to judge the overall millage of a car until you've driven it for more than a block (or in the case above, 3 lines)

I'm not saying my way should be the universal way of doing things, I just wanted to show an example of why I choice to write this way, before being corrected. I still believe it's better than style 1. It's all about preferences though.

Way 1: notice it's a pain to see where the { begins

if (RunForTheHills == HIGH) { 
  if (OnlyOnce == LOW) { 
    digitalWrite(6,HIGH);
    Serial.println("");
    Serial.println("led should be on");
    Serial.println("--------------------------------");
    if ( client.connect(serverName, 80) ) { 
      Serial.println("connected");
      // Make a HTTP request:
      client.println("GET /H");
      client.println("Host: 192.168.1.174"); 
      client.println("Connection: close");
      client.println();
    } 
      else { 
             // if you didn't get a connection to the server:
             Serial.println("connection failed");
             client.stop(); // needed or program freezes after 3 loops if not able to connect
           }
    Internet = HIGH;
    OnlyOnce = HIGH;
  }      
}

Way 2: (the official Chuck Norris Way) Notice its longer, and take more time to scroll to find things.

if (RunForTheHills == HIGH)
{ 
  if (OnlyOnce == LOW)
  {
    digitalWrite(6,HIGH);
    Serial.println("");
    Serial.println("led should be on");
    Serial.println("--------------------------------");
    if ( client.connect(serverName, 80) ) 
    { 
      Serial.println("connected");
      // Make a HTTP request:
      client.println("GET /H");
      client.println("Host: 192.168.1.174"); 
      client.println("Connection: close");
      client.println();
    } 
      else 
           { 
             // if you didn't get a connection to the server:
             Serial.println("connection failed");
             client.stop(); // needed or program freezes after 3 loops if not able to connect
           } 
    Internet = HIGH;
    OnlyOnce = HIGH;
  }      
}

Way 3: (The Former Thomas Way) More compact, and possibly neater, more organized. (from a beginners view)

if (RunForTheHills == HIGH)
{ if (OnlyOnce == LOW)
  { digitalWrite(6,HIGH);
    Serial.println("");
    Serial.println("led should be on");
    Serial.println("--------------------------------");
    if ( client.connect(serverName, 80) ) 
    { Serial.println("connected");
      // Make a HTTP request:
      client.println("GET /H");
      client.println("Host: 192.168.1.174"); 
      client.println("Connection: close");
      client.println();
    } else { // if you didn't get a connection to the server:
             Serial.println("connection failed");
             client.stop(); // needed or program freezes after 3 loops if not able to connect
           }
    Internet = HIGH;
    OnlyOnce = HIGH;
  }      
}

However, the world was once flat, and to say otherwise meant you would die a very painful death (aka you would meet Chuck Norris).

----------------------------Edit------------------------------------
I agree the post where I posted my code before this example was a cluster (use imagination). I had copied and pasted code together, and it through the brackets out of whack. "Beginner Ignorance" The comments were also poorly constructed. --- Many thanks for pointing it out that made life difficult to the experienced programmers volunteering their time to help new programmers learn the ropes.

*** This will flash your led during your WiFi communications

Thanks BulldogLowell for the reference code. I modified the reference you posted to the following. I'm not sure if I have the MyCondition after the =========WiFi simulator=========== section correct

// do your variable initialization and create your WiFi instances
boolean myCondition = false;
const int ledPin = 6;
const int LEDPIN = 9;

// Variables will change :
int ledState = LOW;             // ledState used to set the LED
boolean delayissue = 0;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 1000;           // interval at which to blink (milliseconds)


void setup()
{
  pinMode(ledPin,OUTPUT);
  pinMode(LEDPIN,OUTPUT); //
  // do all of your other setup stuff
}

void loop()
{ 
  //==============do your normal loop() stuff==================

  // then do all of your timer setup instructions that go in setup()
    unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
    digitalWrite(LEDPIN, ledState);
  }

//==================== WiFi call simulator=======================
  if (delayissue == LOW) // so the block function will work? 
  {
    delay(10000);  // 10 second WiFi call simulator
    delayissue =HIGH; 
  }
  
  
  // when you get to your blocking code... *** if you put WiFi calls here...
  
  if(currentMillis - previousMillis >= interval) // if timer is up and delay isn't over
  {
    myCondition = true;
    delayissue = HIGH;
  }
  // do blocking code
  else
  {
  myCondition = false;
  }
}

ISR(TIMER1_COMPA_vect)
{
    if (myCondition) digitalWrite(LEDPIN, !digitalRead(LEDPIN));
    else digitalWrite(LEDPIN, LOW);
}