u8g2lib and WiFiesp libraries conflict?

Hello All,
I have had this program on the go for quite a while but as I can’t get it to function properly. I leave it and resolve to sort it later. I’ve decided the program needs better minds than mine to resolve the problem so here it is.

Originally the code came from https://www.arduino.cc/en/Tutorial.WiFi101WeatherAudioNotifier and I modified it to display on an SSD1306 display similar to display.
I am using a Mega with an esp8266-01, connected to Serial1(18&19)via a level shifter, and the display connected to 20&21.
I had the ESP8266 working without the display. I had the display working without the ESP8266, but when I combine the two programs I get the following displayed on the serial monitor and the display remains showing initial values.

At the end of ten minute loop
[WiFiEsp] Disconnecting  3
[WiFiEsp] Connecting to api.openweathermap.org
Host: api.openweathermap.org
User-Agent: ArduinoWiFi/1.1
Connection: close
end of connection for server
[WiFiEsp] TIMEOUT: 853

I have attached the program due to 9000 character limit, but will post the program when the 5 min time restriction is over.

To use openweather.org you need a key, which is available for free.
WiFi security details have been removed from the code.

G

WeatNot5bout.ino (7.99 KB)

attached code from previous message

//display only works correctly
//not picking up website 11/1/18

#include <Arduino.h>
#include <U8g2lib.h>
#include <WiFiEsp.h>
//#include <WiFiEspClient.h>
//#include <WiFiEspServer.h>
//#include <WiFiEspUdp.h>
#include <ArduinoJson.h>
//#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
//#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
#define JSON_BUFF_DIMENSION 2000  //changed from 2500
//U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0);
const unsigned long postingInterval = 10L * 60L * 1000L;  // posting interval of 10 minutes  (10L *60L*1000L; 10 seconds delay for testing)
unsigned long lastConnectionTime = (millis()- postingInterval);

char ssid[] = "??????????";        // your network SSID (name)
char pass[] = "???????????";    // your network password (use for WPA, or use as key for WEP)

int keyIndex = 0;            // your network key Index number (needed only for WEP)
String nameOfCity = "Grantham,UK";   // your city of interest here in format "city,countrycode"
String text;
const char* weatherNow="Lightning";
float dataVar[5] = {0.00, 0.00, 0.00, 000, 0000.00};

int endResponse = 0;
boolean startJson = false;
int status = WL_IDLE_STATUS;
const char server[] = "api.openweathermap.org";    // name address for openweathermap (using DNS)
WiFiEspClient client;

void u8g2_prepare(void)
{
  //initialise display
  u8g2.setFont(u8g2_font_6x10_tf);
  u8g2.setFontRefHeightExtendedText();
  u8g2.setDrawColor(1);
  u8g2.setFontPosTop();
  u8g2.setFontDirection(0);
}
void u8g2_box_frame(uint8_t a)
{
//provides 10 minute countdown on display  
  u8g2.drawBox(0, 60, (a), 2);
}
void drawText()
{
  uint8_t y = 0;
  u8g2.drawStr(0, y * 8, "     Grantham");
  y++;
  u8g2.drawStr(0, y * 8, "Weather");
  y++;
  u8g2.drawStr(18, y * 8, "°C");
  u8g2.drawStr(0, y * 8, "       ");//This removes artifact that appears before ° (alt 0176)
  u8g2.drawStr(0, y * 8, "Temp  ");
  y++;
  u8g2.drawStr(0, y * 8, "W-Speed m/s");
  y++;
  u8g2.drawStr(0, y * 8, "W-Dir deg");
  y++;
  u8g2.drawStr(0, y * 8, "Humidity %");
  y++;
  u8g2.drawStr(0, y * 8, "Pressure hPa");
}
void drawData()
{
  int y = 1;
  u8g2.drawStr(70, y * 8, "                    ");//Clear print area before writing weather.
  u8g2.setCursor(70, (y * 8));
  u8g2.print(weatherNow);
  y++;
  for (int i = 0; i <= 4 ; ++i)
  {
    u8g2.setCursor(84, (y * 8));
    u8g2.print(dataVar[i]);
    y++;
  }
}
void parseJson(const char * jsonString) {
  Serial.println("start of parse");
  DynamicJsonBuffer jsonBuffer(JSON_BUFF_DIMENSION);
  //StaticJsonBuffer<JSON_BUFF_DIMENSION>jsonBuffer;
  Serial.print(F("Buffer size "));
  Serial.println(JSON_BUFF_DIMENSION);
  Serial.println();
  // FIND FIELDS IN JSON TREE
  JsonObject& root = jsonBuffer.parseObject(jsonString);
  delay(10); //without delay program errors.
  if (!root.success()) {
    Serial.println("parseObject() failed");
    Serial.print("Failed");
    Serial.println(jsonString);
    return;
  }
  // Data update area
  //JsonArray& list = root["list"];
  JsonObject& now = root["list"][0];
  dataVar[0] = now["main"]["temp"];
  dataVar[1] = now["wind"]["speed"];
  dataVar[2] = now["wind"]["deg"];
  dataVar[3] = now["main"]["humidity"];
  dataVar[4] = now["main"]["pressure"];
  weatherNow = now["weather"]["main"];
  Serial.print (dataVar[0]);
  
  JsonObject& city = root["city"];
  const char* city_name = city["name"];
  Serial.println(" ");
  Serial.print(F("city  "));
  Serial.println(city_name);
  Serial.print(F("tempNow  "));
  Serial.println(dataVar[0]);
  Serial.print(F("humidityNow  "));
  Serial.println(dataVar[3]);
  Serial.print(F("pressureNow  "));
  Serial.println(dataVar[4]);
  Serial.print(F("windSpeedNow  "));
  Serial.println(dataVar[1]);
  Serial.print(F("windDirNow  "));
  Serial.println(dataVar[2]);
  Serial.println(" ");
  //void ( jsonBuffer.clear());
  Serial.println(F("At the very end"));
  Serial.println();
}
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
   client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    // Serial.println("connecting...");
    // send the HTTP GET request:
    // client.println("GET /data/2.5/forecast?q=" + nameOfCity + "&mode=json&units=metric&cnt=2 HTTP/1.1");
    client.println("GET /data/2.5/forecast?id=2648208&APPID=xxxxxxxxxxxxxxxxxxx&mode=json&units=metric&cnt=1 HTTP/1.1");
    client.println("Host: api.openweathermap.org");
    Serial.println(F("Host: api.openweathermap.org"));
    client.println("User-Agent: ArduinoWiFi/1.1");
    Serial.println(F("User-Agent: ArduinoWiFi/1.1"));

    client.println("Connection: close");
    Serial.println(F("Connection: close"));
    client.println();
    Serial.println(F("end of connection for server"));
  }
  else {
    // if you couldn't make a connection:
    Serial.println(F("connection failed"));
  }
}
void printWifiStatus()
{
  // print the SSID of the network you're attached to:
  Serial.print(F("SSID: "));
  Serial.println(WiFi.SSID());
  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print(F("IP Address: "));
  Serial.println(ip);
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print(F("signal strength (RSSI):"));
  Serial.print(rssi);
  Serial.println(F(" dBm"));
}

void updateData()
{ //>>>>>>>>information here for testing only
  weatherNow = "Snow";
  dataVar[0] = dataVar[0] + 1 ;
  dataVar[1] = dataVar[1] + 2 ;
  dataVar[2] = dataVar[2] + 3 ;
  dataVar[3] = dataVar[3] + 4 ;
  dataVar[4] = dataVar[4] + 5 ;
}
void setup() {
  // put your setup code here, to run once:
  //Initialize serial and wait for port to open:
  Serial.begin(115200);
  Serial1.begin(115200);
  WiFi.init(&Serial1);
  text.reserve(JSON_BUFF_DIMENSION);
  u8g2.begin();
  u8g2_prepare();
  u8g2.clear();
 
  Serial.println(WiFi.status());
  //    while (true);
  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED)
  {
    Serial.print(F("Attempting to connect to SSID: "));
    Serial.println(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(10000);
  }
  // you're connected now, so print out the status:
  printWifiStatus();
}
void loop()
{
 //Serial.println(WiFi.status()); o/ps 1(true)
  // put your main code here, to run repeatedly:
    // if ten minutes have passed since your last connection,
    // then connect again and request data: Openweathermap restriction.
  if (millis() - lastConnectionTime > postingInterval)
  {
    // note the time that the connection was made:
    lastConnectionTime = millis();
    //updateData();//>>>>>>>>>>>>>>testing only.
    Serial.println("At the end of ten minute loop");
    httpRequest();
  }
  char c=0;
  if (client.available())
  {
    c = client.read();
    //Serial.print(c);
    // json contains equal number of open and close curly brackets, therefore by counting
    // the open and close occurences, we can determine when a json is completely received

    // endResponse == 0 means equal number of open and close curly brackets reached
    if (endResponse == 0 && startJson == true)
    {
      parseJson(text.c_str());  // parse c string text in parseJson function
      text = "";                // clear text string for the next time
      startJson = false;        // set startJson to false to indicate that a new message has not yet started
    }
    if (c == '{')
    {
      startJson = true;         // set startJson true to indicate json message has started
      endResponse++;
    }
    if (c == '}')
    {
      endResponse--;
    }
    if (startJson == true)
    {
      text += c;
    }
  }
  //if (startJson == false)
  //  {
      u8g2.firstPage();
     do 
     {
      int a = ((millis() - lastConnectionTime) / 5000);//control for countdown variable.
       u8g2_box_frame(a); //draw countdown box.
       drawText();//Output screen text
       drawData();//Output screen data
    
     }
    while ( u8g2.nextPage() );
//   }
}

G

What’s going on here:

Zardof:

//#ifdef U8X8_HAVE_HW_SPI

#include <SPI.h>
//#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

You have it connected to the I2C pins, so why also include the SPI library?

My advice is to create a minimal test sketch that just does a “hello world” web server using WiFiEsp with a “hello world” printed on the display. That way you can eliminate all the added complexity that’s muddying the issue.

Sorry about that Pert. That's a relic from previous attempt to resolve this problem. I'm already trying other web calls without any success. I was hoping someone else had been down this rabbit hole. I am receiving

HTTP/1.1 200 OK
Server: openresty

from the server but , I believe, the Serial.print is messing timing up. Thanks for your input. G

I was just curious if there was something I wasn't understanding about your setup.

So you got rid of the the SPI.h include and it made no improvement?

Zardof: I believe, the Serial.print is messing timing up.

To test, you can easily switch the ones in your sketch off by just adding these lines to the top of your code:

#define DEBUG false //set to true for debug output, false for no debug ouput
#define Serial if(DEBUG)Serial

Of course that might make it difficult to see what's actually happening in your system but you do have the display to use as an output device.

Unfortunately the WiFiEsp library also spews a bunch of Serial prints by default, which will not be turned off by the code above. You can turn that off by making the change shown here: https://github.com/bportaluri/WiFiEsp/pull/46/files

Removing SPI.h made no improvement. I have in fact taken a step backwards as my non OLED code, has now shown itself not to be consistent. Sometimes gather data and displays on the serial monitor, sometimes not. Back to the drawing board. Pert, thank you for your input. I will investigate the link.

G