{"id":101595,"date":"2021-02-02T11:35:04","date_gmt":"2021-02-02T11:35:04","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=101595"},"modified":"2021-02-16T14:41:33","modified_gmt":"2021-02-16T14:41:33","slug":"epoch-unix-time-esp32-arduino","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/epoch-unix-time-esp32-arduino\/","title":{"rendered":"Get Epoch\/Unix Time with the ESP32 (Arduino)"},"content":{"rendered":"\n<p>This quick guide shows how to get epoch\/unix time using the ESP32 board with Arduino IDE. Getting the epoch time can be useful to timestamp your readings, give unique names to files, and other applications. We&#8217;ll request the current epoch time from an NTP server, so the ESP32 needs to have an Internet connection.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/Get-Epoch-Unix-Time-ESP32-tutorial-Arduino.jpg.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Get Epoch Unix Time with the ESP32 Arduino\" class=\"wp-image-101604\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/Get-Epoch-Unix-Time-ESP32-tutorial-Arduino.jpg.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/Get-Epoch-Unix-Time-ESP32-tutorial-Arduino.jpg.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/Get-Epoch-Unix-Time-ESP32-tutorial-Arduino.jpg.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/Get-Epoch-Unix-Time-ESP32-tutorial-Arduino.jpg.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n\n<p>If you want to get date and time in a human readable format, we recommend the following tutorial instead: <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-date-time-ntp-client-server-arduino\/\">ESP32 NTP Client-Server: Get Date and Time (Arduino IDE)<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What is epoch time?<\/h2>\n\n\n\n<p>The <strong>Epoch Time<\/strong> (also know as <strong>Unix epoch,<\/strong> <strong>Unix time<\/strong>, <strong>POSIX time<\/strong> or <strong>Unix timestamp)<\/strong> is the number of seconds that have elapsed since January 1, 1970 (midnight UTC\/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">NTP (Network Time Protocol)<\/h2>\n\n\n\n<p>NTP stands for Network Time Protocol and it is a networking protocol for clock synchronization between computer systems. In other words, it is used to synchronize computer clock times in a network.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-style-default\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"564\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-NTP-Client-Server.png?resize=1024%2C564&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 NTP Network Time Protocol Server How it Works\" class=\"wp-image-101607\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-NTP-Client-Server.png?resize=1024%2C564&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-NTP-Client-Server.png?resize=300%2C165&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-NTP-Client-Server.png?resize=768%2C423&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-NTP-Client-Server.png?w=1031&amp;quality=100&amp;strip=all&amp;ssl=1 1031w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>There are NTP servers like <em>pool.ntp.org<\/em> that anyone can use to request time as a client. In this case, the ESP32 is an NTP Client that requests time from an NTP Server (<em>pool.ntp.org)<\/em>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">ESP32 Get Epoch\/Unix Time Function<\/h2>\n\n\n\n<p>To get epoch\/unix time with the ESP32, you can use the following function <span class=\"rnthl rntliteral\">getTime()<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Function that gets current epoch time\nunsigned long getTime() {\n  time_t now;\n  struct tm timeinfo;\n  if (!getLocalTime(&amp;timeinfo)) {\n    \/\/Serial.println(\"Failed to obtain time\");\n    return(0);\n  }\n  time(&amp;now);\n  return now;\n}<\/code><\/pre>\n\n\n\n<p>This function returns the current epoch time. Continue reading for a complete example.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">ESP32 Get Epoch\/Unix Time Example<\/h2>\n\n\n\n<p>Copy the following code to your Arduino IDE. This code connects to the internet and requests the time from an NTP server (<em>pool.ntp.org<\/em>).<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/epoch-unix-time-esp32-arduino\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*\/\n\n#include &lt;WiFi.h&gt;\n#include &quot;time.h&quot;\n\n\/\/ Replace with your network credentials\nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\n\/\/ NTP server to request epoch time\nconst char* ntpServer = &quot;pool.ntp.org&quot;;\n\n\/\/ Variable to save current epoch time\nunsigned long epochTime; \n\n\/\/ Function that gets current epoch time\nunsigned long getTime() {\n  time_t now;\n  struct tm timeinfo;\n  if (!getLocalTime(&amp;timeinfo)) {\n    \/\/Serial.println(&quot;Failed to obtain time&quot;);\n    return(0);\n  }\n  time(&amp;now);\n  return now;\n}\n\n\/\/ Initialize WiFi\nvoid initWiFi() {\n  WiFi.mode(WIFI_STA);\n  WiFi.begin(ssid, password);\n  Serial.print(&quot;Connecting to WiFi ..&quot;);\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  initWiFi();\n  configTime(0, 0, ntpServer);\n}\n\nvoid loop() {\n  epochTime = getTime();\n  Serial.print(&quot;Epoch Time: &quot;);\n  Serial.println(epochTime);\n  delay(1000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_Epoch_Unix_Time.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Insert your network credentials in the following variables and the code will work straight away:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Replace with your network credentials\nconst char* ssid = \"REPLACE_WITH_YOUR_SSID\";\nconst char* password = \"REPLACE_WITH_YOUR_PASSWORD\";<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Let&#8217;s take a quick look on how the code works.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Libraries<\/h4>\n\n\n\n<p>First, you need to include the <span class=\"rnthl rntliteral\">WiFi<\/span> library to connect the ESP32 to your local network; and the <span class=\"rnthl rntliteral\">time<\/span> library to handle time structures.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include &lt;WiFi.h&gt;\n#include \"time.h\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Network Credentials<\/h4>\n\n\n\n<p>Insert your network credentials in the following variables so that the ESP32 can connect to your network.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Replace with your network credentials\nconst char* ssid = \"REPLACE_WITH_YOUR_SSID\";\nconst char* password = \"REPLACE_WITH_YOUR_PASSWORD\";<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">NTP Server<\/h4>\n\n\n\n<p>We\u2019ll request the time from&nbsp;<em>pool.ntp.org<\/em>, which is a cluster of timeservers that anyone can use to request the time.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>const char* ntpServer = \"pool.ntp.org\";<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">getTime() function<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">getTime()<\/span> function gets and returns the current epoch time. If it is not able to get the time, it returns <span class=\"rnthl rntliteral\">0<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Function that gets current epoch time\nunsigned long getTime() {\n  time_t now;\n  struct tm timeinfo;\n  if (!getLocalTime(&amp;timeinfo)) {\n    \/\/Serial.println(\"Failed to obtain time\");\n    return(0);\n  }\n  time(&amp;now);\n  return now;\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">initWiFi()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">initWiFi()<\/span> function initializes Wi-Fi and connects the ESP32 to your local network.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void initWiFi() {\n  WiFi.mode(WIFI_STA);\n  WiFi.begin(ssid, password);\n  Serial.print(\"Connecting to WiFi ..\");\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">setup()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, initialize the Serial Monitor at a baud rate of 115200.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);<\/code><\/pre>\n\n\n\n<p>Call the <span class=\"rnthl rntliteral\">initWiFi()<\/span> function to initialize Wi-Fi:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>initWiFi();<\/code><\/pre>\n\n\n\n<p>Configure the time using the <span class=\"rnthl rntliteral\">configTime()<\/span> function. The first and second arguments correspond to the GMT time offset and daylight saving time. However, because we&#8217;re interested in getting epoch time, these arguments should be <span class=\"rnthl rntliteral\">0<\/span>. The last argument is the NTP server (<span class=\"rnthl rntliteral\">ntpServer<\/span>):<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>configTime(0, 0, ntpServer);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">loop()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span>, get the epoch time and save it in the <span class=\"rnthl rntliteral\">epochTime<\/span> variable:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>epochTime = getTime();<\/code><\/pre>\n\n\n\n<p>Finally, print the epoch time every second:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.print(\"Epoch Time: \");\nSerial.println(epochTime);\ndelay(1000);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Upload the code to your ESP32 board. Then, open the Serial Monitor at a baud rate of 115200. Press the ESP32 on-board RST button. It should connect to Wi-Fi and start printing the current epoch\/unix time every second.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"669\" height=\"445\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-Get-Epoch-Time-Example-Serial-Monitor.png?resize=669%2C445&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Get Epoch Unix Time Serial Monitor \" class=\"wp-image-101596\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-Get-Epoch-Time-Example-Serial-Monitor.png?w=669&amp;quality=100&amp;strip=all&amp;ssl=1 669w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/ESP32-Get-Epoch-Time-Example-Serial-Monitor.png?resize=300%2C200&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 669px) 100vw, 669px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>This was a quick guide showing you how to get epoch\/unix time with the ESP32. The epoch time is the number of seconds elapsed since January 1 1970.  To get time, we need to connect to an NTP server, so the ESP32 needs to have access to the internet.<\/p>\n\n\n\n<p>If you&#8217;re interested in getting date and time in a human readable format, refer to the next tutorial: <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-date-time-ntp-client-server-arduino\/\">ESP32 NTP Client-Server: Get Date and Time (Arduino IDE)<\/a><\/li><\/ul>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. If you want to learn more about the ESP32, check our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/build-web-servers-esp32-esp8266-ebook\/\">Build Web Servers with ESP32 and ESP8266<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32\/\">More ESP32 Projects and Tutorials\u2026<\/a><\/li><\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This quick guide shows how to get epoch\/unix time using the ESP32 board with Arduino IDE. Getting the epoch time can be useful to timestamp your readings, give unique names &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Get Epoch\/Unix Time with the ESP32 (Arduino)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/epoch-unix-time-esp32-arduino\/#more-101595\" aria-label=\"Read more about Get Epoch\/Unix Time with the ESP32 (Arduino)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":101604,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[281,276,277,299,264],"tags":[],"class_list":["post-101595","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32-project","category-esp32","category-esp32-arduino-ide","category-0-esp32","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/01\/Get-Epoch-Unix-Time-ESP32-tutorial-Arduino.jpg.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/101595","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=101595"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/101595\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/101604"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=101595"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=101595"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=101595"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}