There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example pool.ntp.org, but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the How do I use pool.ntp.org
page, but it doesn't seem to say anything about finding IP-addresses.
Questions
- Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
- All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?
The code I currently find the easiest to understand is from the Arduino forum, and has an IP address hard coded.
I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard
libray. I do know of existence of RTC devices but I would prefer NTP.
1 Answer 1
The EtherCard
library offers a method called ether.dnsLookup(host)
where you ask it to look up the IP address for you.
etherCard.dnsLookup("pool.ntp.org");
...only that might fail, so it returns a false
:
if (!etherCard.dnsLookup("pool.ntp.org")) {
// Error! Do something!
return;
} // if
But if it works...
if (!etherCard.dnsLookup("pool.ntp.org")) {
// Error! Do something!
return;
} // if
// At this stage, dnsLookup() worked...
// Can now connect to IP adress in etherCard.hispip
Now: please note that ntp.org
would prefer you to use a more precise locale than pool.ntp.org
. If you're going to distribute your application worldwide, then that's fine. But I always use au.pool.ntp.org
because I'm in the Australian region. There are others that you can/should use instead.
-
Thanks for writing Edgar's suggestion into an answer, the locale is a nice addition!PHPirate– PHPirate2016年07月05日 14:56:46 +00:00Commented Jul 5, 2016 at 14:56
if (!ether.dnsLookup(website)) { Serial.println("DNS failed"); } ether.printIp("Server: ", ether.hisip);
but I'm new to the ethernet connections so I need to find out how to get an ip address out of that to use later in the code...ether.hisip
is not a string, it's an array of 4 bytes.ether.hisip
printed to, but now I see that's whyether.printIP
was used.