So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By abishur
#75464 Hello all! I'm just learning how to use the ESP8226. The long and short of what I'm trying to do is to set it up to connect to an Access Point and act as an Access Point itself. Then I want it to periodically check for the current time from an NTP server and update an attached DS3231.

When I run the example of the NTP client everything works fine, however when I implement it in my code, it breaks. I've tracked the problem down to these two lines of code:

Code: Select allWiFi.softAPConfig(ip,gateway,subnet);
WiFi.softAP(localAPSSID, tempPass, apChannel);


My guess about what is going on is that when I send the NTP time request, I'm using the gateway IP (which leads no where) rather than going through the Acess Point I'm connected to that has internet access. How do I specify the connection to use?

Here's the full code, apologies in advance for my sloppy code, I've been copy and pasting to track down where the error occurs and now that I found it immediately came here for some help :lol:

Code: Select all#include <Wire.h>
#include <RtcDS3231.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
// Only needed if storing SSID and Password to EEPROM
#include <EEPROM.h>
#include "mbFunctions.h"
RtcDS3231<TwoWire> Rtc(Wire);
ESP8266WebServer server;

//char ssid[] = "";  //  your network SSID (name)
//char pass[] = "";       // your network password


unsigned int localPort = 2390;      // local port to listen for UDP packets

/* Don't hardwire the IP address or we won't get the benefits of the pool.
 *  Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "north-america.pool.ntp.org";

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;

// Set a static ip address for the Access point mode
// This can be used to directly connect to it instead of having to have a local network
IPAddress ip(172,16,1,1);
IPAddress gateway(172,16,1,1);
IPAddress subnet(255,255,255,0);
int apChannel = 11;

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println();

  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////
  //  This section only needed if storing SSID and Password to EEPROM   //
  //  Delete or comment out if unneded                                  //
  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////

  EEPROM.begin(512);

  // Uncomment the following line to empty EEPROM Values
  //clearEeprom();
 
  // Only need to call the writeEeprom when updating SSID or Password
  //writeEeprom(ssid, password);

  // Read SSID and password from EEPROM
  String setupArray[2];
  readEeprom(&setupArray[0]);

  // Convert Strings to Char Array
  char tempSsid[setupArray[0].length()+1];
  char tempPass[setupArray[1].length()+1];

  setupArray[0].toCharArray(tempSsid,setupArray[0].length()+1);
  setupArray[1].toCharArray(tempPass,setupArray[1].length()+1);

  // Diag Delete when working
  Serial.println(tempSsid);
  Serial.println(tempPass);

  // Local Access point SSID is setup to be the same as the SSID of the network you connect to
  // with the number "2" at the end of it. 
 
  //If not storing data to EEPROM this part will need to be changed
  char localAPSSID[setupArray[0].length()+2];
  strcpy(localAPSSID, tempSsid);
  strcat(localAPSSID, "2");
 
  EEPROM.end();
 
  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////
  //  End of EEPROM section                                             //
  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(tempSsid,tempPass);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
 
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Starting UDP");
  udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(udp.localPort());

    // Diag Needs to be replaced with real code
  server.on("/",[](){server.send(200,"text/plain","Hello World!");});
  server.begin();

  // Turn on local Access Point
  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(localAPSSID, tempPass, apChannel); 
}

void loop()
{
  //get a random server from the pool
  WiFi.hostByName(ntpServerName, timeServerIP);

  sendNTPpacket(timeServerIP); // send an NTP packet to a time server
  // wait to see if a reply is available
  delay(1000);
 
  int cb = udp.parsePacket();
  if (!cb) {
    Serial.println("no packet yet");
  }
  else {
    Serial.print("packet received, length=");
    Serial.println(cb);
    // We've received a packet, read the data from it
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = " );
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);


    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if ( ((epoch % 3600) / 60) < 10 ) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ( (epoch % 60) < 10 ) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address)
{
  Serial.println("sending NTP packet...");
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  udp.beginPacket(address, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
}
User avatar
By abishur
#75488 Finally tacked down what was wrong. As pointed out in a comment over herewhen operating in both station mode and as an access point, then the channel you give the ESP's AP will be overridden by the channel of the access point you are connected to in station mode. When this happens, the ESP's AP will reset causing networking problems.

The immediate fix was for me to hard code the channel to match my home's AP channel. For a more long term goal, I'll look into reading the channel from the connected AP and assigning to the ESP's channel. Another possibility is WiFimulti library. I'm not sure if it can really fix it, but I'll have to check it out.