<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>rtc - Hard Wired</title>
	<atom:link href="https://www.hardwired.dev/tag/rtc/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.hardwired.dev</link>
	<description></description>
	<lastBuildDate>Wed, 01 Mar 2023 18:40:55 +0000</lastBuildDate>
	<language>cs</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://www.hardwired.dev/wp-content/uploads/2022/10/android-chrome-256x256-1-150x150.png</url>
	<title>rtc - Hard Wired</title>
	<link>https://www.hardwired.dev</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>ESP32 RTC DS3231</title>
		<link>https://www.hardwired.dev/2023/02/28/esp32-rtc-ds3231/</link>
		
		<dc:creator><![CDATA[John Doe]]></dc:creator>
		<pubDate>Tue, 28 Feb 2023 22:17:51 +0000</pubDate>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[IOT]]></category>
		<category><![CDATA[at24c32]]></category>
		<category><![CDATA[clock]]></category>
		<category><![CDATA[ds3231]]></category>
		<category><![CDATA[esp32]]></category>
		<category><![CDATA[iot]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rtc]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">https://www.hardwired.dev/?p=988</guid>

					<description><![CDATA[<p>Pokud potřebujete na ESP32 spouštět naplánované úlohy, určitě se nemůžete spoléhat na vnitřní časování. Budete potřebovat nějaký externí modul reálného &#62;&#62;&#62;</p>
<p>The post <a href="https://www.hardwired.dev/2023/02/28/esp32-rtc-ds3231/">ESP32 RTC DS3231</a> first appeared on <a href="https://www.hardwired.dev">Hard Wired</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="bsf_rt_marker"></div><p>Pokud potřebujete na <strong>ESP32</strong> spouštět naplánované úlohy, určitě se nemůžete spoléhat na vnitřní časování. Budete potřebovat nějaký externí modul reálného času (<a href="https://sk.wikipedia.org/wiki/Hodiny_re%C3%A1lneho_%C4%8Dasu">RTC</a>), který vám na vyžádání vrátí přesný čas.</p>
<p>V bastlířské oblasti se hodně často používá <a href="https://lastminuteengineers.com/ds1307-rtc-arduino-tutorial/">DS1307</a>. Vyniká hlavně v tom, že je extrémně levný. Na <a href="https://www.aliexpress.com/item/32585872245.html">Aliexpressu</a> se dá koupit za necelých <strong>14 CZK</strong>. Cena kompenzuje určitou nepřesnost. Udává se zpoždění cca 5 minut za měsíc.</p>
<p>Sice několika násobně dražší, ale pořád směšně levný je <a href="https://lastminuteengineers.com/ds3231-rtc-arduino-tutorial/">DS3231</a>. Na <a href="https://www.aliexpress.com/item/32833136577.html">Aliexpressu</a> se dá pořídit za <strong>60 CZK</strong>.</p>
<p><img decoding="async" src="https://www.hardwired.dev/wp-content/uploads/2023/02/DS3231-AT24C32-aliexpress.jpg" alt="" /></p>
<p>U <a href="https://www.laskakit.cz/arduino-rtc-hodiny-realneho-casu-ds3231-at24c32/">Lásky</a> 128 CZK plus poštovné.</p>
<p><img decoding="async" src="https://www.hardwired.dev/wp-content/uploads/2023/02/DS3231-AT24C32-laskakit.jpg" alt="" /></p>
<p>Tento modul je daleko přesnější a obsahuje tepelně kompenzovaný krystalový oscilátor (TCXO), který odolává změnám teplot. Pro náš testovací projekt použijeme DS3231.</p>
<h1>DS3231</h1>
<p>Modul umí sledovat roky, měsíce, dny, hodiny, minuty a sekundy. Umí dokonce přestupné roky do roku 2100. Dokáže pracovat v 12 hodinovém nebo 24 hodinovém formátu. Obsahuje dva programovatelné alarmy.</p>
<p>Modul má piny pro připojení přes sběrnici I2C. Má také pin INT, který umí produkovat signál přerušení a pin SQW pro generování &quot;square wave&quot; signálu na frekvencích 1Hz, 4kHz, 8kHz nebo 32kHz.</p>
<p>Přesnost modulu je +-2 minuty za rok.</p>
<p>Modul se napájí pomocí knoflíkové baterie CR2032, LIR2032 nebo ekvivalentní o průměru 20mm. Při použití 220mAh baterie je teoretická životnost 8 let.</p>
<p>Modul obsahuje 32 bytový AT24C32 EEPROM paměťový čip s milionem zapisovacích cyklů. Neslouží pro běh hodin, může být použit pro zápis logů nebo libovolných dat.</p>
<p>Vyčerpávající popis modulu najdete na <a href="https://lastminuteengineers.com/ds3231-rtc-arduino-tutorial/">lastminuteengineers.com</a>.</p>
<h1>Zapojení</h1>
<p>Pomocí I2C připojíme k ESP modulu.</p>
<p><img decoding="async" src="https://www.hardwired.dev/wp-content/uploads/2023/02/DS3231-zapojeni.jpg" alt="" /></p>
<h1>Program</h1>
<p>Pokud nejsou hodiny nastaveny nebo mají starší čas, než je čas při kompilaci kódu, přenastaví se na aktuální čas. Po inicializaci modulu se vytvoří naplánovaná úloha pomocí modulu <code>TaskScheduler</code> a každých 10 sekund vypíše aktuální čas modulu do sériové konzole. Zbytek v komentovaném kódu.</p>
<h2>main.cpp</h2>
<pre><code class="language-cpp">/**
 * @file main.cpp
 * @author Hard Wired
 * @brief ESP32 I2C RTC test project.
 * @details
 *      Based on https://github.com/Makuna/Rtc/blob/master/examples/DS3231_Simple/DS3231_Simple.ino example.
 *      Modul tutorial https://lastminuteengineers.com/ds3231-rtc-arduino-tutorial/
 * @version 0.1
 * @date 2023-02-08
 */

#include &lt;Arduino.h&gt;

#include &lt;Wire.h&gt;
#include &lt;RtcDS3231.h&gt;
#include &lt;TaskScheduler.h&gt;

const int SECOND_IN_MILS = 1000;
const int TEN_SECONDS_IN_MILS = SECOND_IN_MILS * 10;

/**
 * @brief Vytvoření plánovače
 *
 */
Scheduler runner;

/**
 * @brief Vytvoření RTC objektu a připojení pomocí I2C sběrnice.
 *
 * @return RtcDS3231&lt;TwoWire&gt;
 */
RtcDS3231&lt;TwoWire&gt; Rtc(Wire);

/**
 * @brief Vytáhne z objektu &quot;Rtc&quot; poslední chybový stav a vypíše chybovou hlášku¨
 *        a dá vědět pomocí true/false.
 * @details see https://www.arduino.cc/reference/en/language/functions/communication/wire/endtransmission/
 *
 * @param errorTopic
 * @return true
 * @return false
 */
bool wasError(const char *errorTopic = &quot;&quot;)
{
    uint8_t error = Rtc.LastError();
    if (error != 0)
    {
        Serial.print(&quot;[&quot;);
        Serial.print(errorTopic);
        Serial.print(&quot;] WIRE communications error (&quot;);
        Serial.print(error);
        Serial.print(&quot;) : &quot;);

        switch (error)
        {
        case Rtc_Wire_Error_None:
            Serial.println(&quot;(none?!)&quot;);
            break;
        case Rtc_Wire_Error_TxBufferOverflow:
            Serial.println(&quot;transmit buffer overflow&quot;);
            break;
        case Rtc_Wire_Error_NoAddressableDevice:
            Serial.println(&quot;no device responded&quot;);
            break;
        case Rtc_Wire_Error_UnsupportedRequest:
            Serial.println(&quot;device doesn&#039;t support request&quot;);
            break;
        case Rtc_Wire_Error_Unspecific:
            Serial.println(&quot;unspecified error&quot;);
            break;
        case Rtc_Wire_Error_CommunicationTimeout:
            Serial.println(&quot;communications timed out&quot;);
            break;
        }
        return true;
    }
    return false;
}

/**
 * @brief Vypíše naformátované datum do sériové konzole.
 *
 * @param dt
 */
void printDateTime(const RtcDateTime &amp;dt)
{
    char buffer[20];

    sprintf(buffer, &quot;%d-%02d-%02d %02d:%02d:%02d&quot;, dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second());

    Serial.println(buffer);
}

void printDateTimeAndTemperature()
{
    if (!Rtc.IsDateTimeValid())
    {
        if (!wasError(&quot;loop IsDateTimeValid&quot;))
        {
            // Common Causes:
            //    1) the battery on the device is low or even missing and the power line was disconnected
            Serial.println(&quot;RTC lost confidence in the DateTime!&quot;);
        }
    }

    RtcDateTime now = Rtc.GetDateTime();
    if (!wasError(&quot;loop GetDateTime&quot;))
    {
        printDateTime(now);
    }

    RtcTemperature temp = Rtc.GetTemperature();
    if (!wasError(&quot;loop GetTemperature&quot;))
    {
        temp.Print(Serial);
        // you may also get the temperature as a float and print it
        // Serial.print(temp.AsFloatDegC());
        Serial.println(&quot;C&quot;);
    }
}

/**
 * @brief Vytvoření naplánované úlohy. Poběží navždy a spustí se každých 10 sekund.
 *
 * @return Task
 */
Task PrintDateTimeAndTemperatureTask(TEN_SECONDS_IN_MILS, TASK_FOREVER, &amp;printDateTimeAndTemperature);

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

    Serial.print(&quot;compiled: &quot;);
    // makro které expanduje datum při kompilaci kódu na &quot;mmm dd yyyy&quot; řetězec
    Serial.print(__DATE__);
    Serial.print(&#039; &#039;);
    // makro které expanduje čas při kompilaci kódu na &quot;hh:MM:ss&quot; řetězec
    Serial.println(__TIME__);

    Rtc.Begin();

#if defined(WIRE_HAS_TIMEOUT)
    Wire.setWireTimeout(3000 /* us */, true /* reset_on_timeout */);
#endif

    /**
     * @brief Vytvoří objekt RtcDateTime a nastaví ho podle času kompilace kódu.
     *
     */
    RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
    printDateTime(compiled);
    Serial.println();

    /**
     * @brief Pokud neni RTC nastaveno nastaví datum a čas.
     *
     */
    if (!Rtc.IsDateTimeValid())
    {
        if (!wasError(&quot;setup IsDateTimeValid&quot;))
        {
            // Common Causes:
            //    1) first time you ran and the device wasn&#039;t running yet
            //    2) the battery on the device is low or even missing

            Serial.println(&quot;RTC lost confidence in the DateTime!&quot;);

            // following line sets the RTC to the date &amp; time this sketch was compiled
            // it will also reset the valid flag internally unless the Rtc device is
            // having an issue

            Rtc.SetDateTime(compiled);
        }
    }

    /**
     * @brief V případě že není RTC spuštěno spustíme ho.
     *
     */
    if (!Rtc.GetIsRunning())
    {
        if (!wasError(&quot;setup GetIsRunning&quot;))
        {
            Serial.println(&quot;RTC was not actively running, starting now&quot;);
            Rtc.SetIsRunning(true);
        }
    }

    /**
     * @brief V případě, že je čas hodin starší než čas kompilace, nastaví se nový čas. Vypíše do sériové konzole informaci o nastavení RTC.
     *
     */
    RtcDateTime now = Rtc.GetDateTime();
    if (!wasError(&quot;setup GetDateTime&quot;))
    {
        if (now &lt; compiled)
        {
            Serial.println(&quot;RTC is older than compile time, updating DateTime&quot;);
            Rtc.SetDateTime(compiled);
        }
        else if (now &gt; compiled)
        {
            Serial.println(&quot;RTC is newer than compile time, this is expected&quot;);
        }
        else if (now == compiled)
        {
            Serial.println(&quot;RTC is the same as compile time, while not expected all is still fine&quot;);
        }
    }

    /*
     * Nastaví RTC modul do požadovaného stavu.
     */
    Rtc.Enable32kHzPin(false);
    wasError(&quot;setup Enable32kHzPin&quot;);
    // The INT/SQW pin on the DS3231 provides either an interrupt signal (due to alarm conditions) or a nice square wave at 1Hz, 4kHz, 8kHz, or 32kHz.
    Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone);
    wasError(&quot;setup SetSquareWavePin&quot;);

    /**
     * @brief Přiřazení naplánované úlohy do plánovače.
     *
     */
    runner.addTask(PrintDateTimeAndTemperatureTask);

    /**
     * @brief Povolení naplánované úlohy.
     *
     */
    PrintDateTimeAndTemperatureTask.enable();
}

void loop()
{
    runner.execute(); // spouštění plánovače
}</code></pre>
<h2>platformio.ini</h2>
<pre><code class="language-ini">[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200

lib_deps =
  makuna/RTC @ ^2.3.6
  arkhipenko/TaskScheduler @ ^3.7.0</code></pre>

<div class="twitter-share"><a href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.hardwired.dev%2F2023%2F02%2F28%2Fesp32-rtc-ds3231%2F&#038;via=hessevalentino" class="twitter-share-button">Tweet</a></div><p>The post <a href="https://www.hardwired.dev/2023/02/28/esp32-rtc-ds3231/">ESP32 RTC DS3231</a> first appeared on <a href="https://www.hardwired.dev">Hard Wired</a>.</p>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
