So I have some code that pulls an IP via DHCP and in the event that fails it defaults to a simple static IP. Well I am using NTP to stash the updated time in an RTC however, I would like to add something that would skip over the UDP NTP packet in the event that communications are down and then simply have it pull the time from the RTC and move on.
This is what the setup portion of my code looks like now:
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// start the Ethernet connection:
Serial.println("Trying to get an IP address using DHCP");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// initialize the ethernet device not using DHCP:
Ethernet.begin(mac, ip, gateway, subnet);
}
// print your local IP address:
Serial.print("My IP address: ");
ip = Ethernet.localIP();
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(ip[thisByte], DEC);
Serial.print(".");
}
Serial.println();
// ** Get NTP Time
Udp.begin(8888); // Set UDP Port to 8888
setSyncProvider(getNtpTime); // Fetch NTP Data
setSyncInterval(ntpsync); // NTP Sync Timer
//Serial.println( Udp.parsePacket() );
if ( Udp.parsePacket() ) {
tm.Hour = hour();
tm.Minute = minute();
tm.Second = second();
tm.Day = day();
tm.Month = month();
tm.Year = year();
RTC.write(tm);
}
}
time_t getNtpTime()
{
while (Udp.parsePacket() > 0) ;
sendNTPpacket(timeServer);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500)
{
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE)
{
Udp.read(packetBuffer, NTP_PACKET_SIZE);
unsigned long secsSince1900;
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
}
return 0;
}
// NTP Request Transmission
void sendNTPpacket(IPAddress &address)
{
memset(packetBuffer, 0, NTP_PACKET_SIZE); // NTP Packet Buffer
// NTP Packet Payload
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// Send Payload to NTP Server Port 123
Udp.beginPacket(address, 123);
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
So with the above if DHCP is good it will grab the time, stash it and move on. (I Hope anyway... new to RTC usage)
If it defaults to a static IP I do get a print out in the console that it did so and after that it just gets well... stuck! I assume that is due to the NTP packet failing. Any ideas on how to avoid this and move on?