<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Krutarth on Medium]]></title>
        <description><![CDATA[Stories by Krutarth on Medium]]></description>
        <link>https://medium.com/@krutarthpurohit?source=rss-a26f04fe2124------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*em01RJBmzCk0ub0elQVylQ.jpeg</url>
            <title>Stories by Krutarth on Medium</title>
            <link>https://medium.com/@krutarthpurohit?source=rss-a26f04fe2124------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:49:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krutarthpurohit/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is SAE J1939 protocol?]]></title>
            <link>https://krutarthpurohit.medium.com/what-is-sae-j1939-protocol-3e85b2577adc?source=rss-a26f04fe2124------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e85b2577adc</guid>
            <category><![CDATA[volvo]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[can-protocol]]></category>
            <category><![CDATA[automotive-industry]]></category>
            <category><![CDATA[sae-j1939]]></category>
            <dc:creator><![CDATA[Krutarth]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 18:14:37 GMT</pubDate>
            <atom:updated>2025-07-03T18:14:37.697Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why it is widely used communication protocol in automotive industry.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*ZVQ_VV0u4bzGh6HTTKv3Fw.jpeg" /></figure><p>In embedded machines the communication is most important aspect through which different micro-controller and sensors exchange data but they all require some rules and identities to ensure robust communication. This is achieved by protocols- SPI, I2C, CAN, J1939, etc. These protocol has standard set of rules that need to be followed to facilitate data exchange.</p><p>SAE J1939 is one of such communication used in automobile industry (mostly heavy-duty vehicles and trucks).</p><p>It is a higher-layer protocol that utilizes CAN for its physical and data link layers.</p><h3>Stack of J1939</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoUu8Cd_fGCFOurjtdfwKA.png" /><figcaption>Figure: Stack of SAE J1939</figcaption></figure><p><strong>User application:</strong> It the firmware written in embedded C that calls APIs provided by supported J1939 libraries for the specific controllers. With those APIs we can set/read the data.</p><p><strong>Application layer:</strong> This layer encodes/decodes PGNs/SPNs into messages understandable by the application as defined in SAE J1939/71. J1939/73 defines diagnostic messages like DM1 (active DTCs), DM2 (previous DTCs), etc.</p><p><strong>(</strong>SAE J1939/71 and SAE J1939/73 are sub-protocols within the overall SAE J1939 protocol family<strong>)</strong></p><p><strong>Network layer: </strong>This layer manages address claiming, node identification and name management. This ensures that each node connected in the network has unique address as it handles dynamic address claiming process.</p><blockquote><strong><em>Dynamic address claiming</em></strong></blockquote><blockquote><em>Every ECU on a J1939 network must have a Source Address (SA), ranging from 0 to 253. Since J1939 is built on a broadcast CAN network, address collisions must be avoided.</em></blockquote><blockquote><em>To solve this, J1939 defines a way for devices to automatically claim and negotiate their addresses using a special message called Address Claim (PGN 60928).</em></blockquote><blockquote><em>Steps for address claiming:</em></blockquote><blockquote>1. ECU selects an address (often from a preferred list or configuration).</blockquote><blockquote>2. The ECU sends an address claim frame: 29-bit ID<strong> </strong>the Source Address + 8-byte NAME field (NAME = vendor name, device name, etc.)</blockquote><blockquote>3. If another ECU already uses the same address, and it has a lower NAME value, then the ECU with lower NAME wins</blockquote><blockquote>4. Once no conflict is detected, the ECU successfully owns that address. It can now send any J1939 PGNs using that Source Address.</blockquote><p><strong>Data link layer/Transport layer: </strong>This layer converts PGN messages into CAN frames. It handles more then 8 bytes of data using BAM, RTS, CTS command frames as well as handles sequence number, reassembly, and timeout of multi-packet message.</p><p><strong>CAN HAL layer: </strong>It is a Hardware Abstraction Layer that acts as a bridge between protocol stack and hardware.</p><p><strong>CAN network (Physical layer): </strong>The actual physical CAN bus that connects multiple MCUs for message exchange.</p><h3>Why J1939 instead of CAN?</h3><p>What makes J1939 special than CAN? especially when it uses CAN protocol beneath it. So here is the answer.</p><ol><li>To send more than 8 bytes of data. (In CAN2.0, user cannot send more then 8 bytes of data)</li><li>Highly structured data: Uses <strong>PGNs and SPNs</strong>. PGNs (Parameter Group Numbers) are similar to CAN IDs and define the type of message. Each PGN contains one or more SPNs (Suspect Parameter Numbers), which represent specific signals . Every signal has a unique SPN ID, so it can be consistently identified and decoded — as long as you know which PGN it appears in and its position within that PGN.</li><li>Easy Diagnostics: J1939/73 provides messages that carries diagnostic trouble codes (DTCs).</li><li>Dynamic address claiming</li><li>Since it has highly structured data sets, it is now standardized across OEMs. It is adopted by truck, bus, tractor, marine, and heavy equipment manufacturers globally.</li></ol><blockquote>A PGN is like a “message type”</blockquote><blockquote>Example: PGN <em>65262</em> is the &quot;Engine Temperature&quot; message. This PGN contains multiple SPNs, in fixed byte positions.</blockquote><blockquote>Each SPN:</blockquote><blockquote>Has a unique ID (e.g., SPN 110 = Engine Coolant Temperature, SPN 170 = Fuel Temperature, SPN 175 = Engine Oil Temperature). Is assigned a specific byte offset and length within the PGN.</blockquote><p>I hope this article helps you to understand the importance of J1939 protocol against standard CAN communication. This is just the tip of an iceberg, there are many features yet to be covered such as J1939 transport protocol- connection management and J1939 transport protocol- data transfer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e85b2577adc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different ways to provide time delays in C program]]></title>
            <link>https://krutarthpurohit.medium.com/different-ways-to-provide-time-delays-in-c-program-df4cc849b19b?source=rss-a26f04fe2124------2</link>
            <guid isPermaLink="false">https://medium.com/p/df4cc849b19b</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[delay]]></category>
            <category><![CDATA[loops-in-c]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Krutarth]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 06:58:11 GMT</pubDate>
            <atom:updated>2024-10-12T06:58:11.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*9qUrjUPFAkqBEygYTWdXlw.png" /></figure><p>Time delays are essential in embedded programming to ensure proper system operation. They are used to synchronize incoming and outgoing data streams and to execute specific tasks after a defined time interval.</p><p>There are various ways to introduce delays in a C program, each with its own pros and cons. Some methods can halt the entire program, putting the CPU into an idle state, while others efficiently manage delays to prevent the CPU from remaining idle for the entire duration of the delay.</p><h3>1. Using for-loop</h3><p>This is a basic form of delay, where a loop is repeatedly executed until a specified limit is reached. Below is the pseudo-code that can be used in the main program. During this delay, the loop runs continuously, causing the CPU to remain occupied and, as a result, waste valuable resources and energy.</p><pre>for(int i=0 ; i&lt;2000000 ; i++);    //delay</pre><p><strong>Pros:</strong> Easy to implement, simple to understand</p><p><strong>Cons:</strong> High CPU usage, cannot provide an accurate or consistent delay time</p><h3>2. using usleep() function</h3><p>The usleep() function suspends the execution of the calling thread for a specified number of microseconds. However, this method halts the CPU, preventing the program from executing any further tasks until the delay is complete.</p><pre>usleep(500000);        //delay of 500 ms</pre><p>Pros: Easy to implement, useful for synchronisation</p><p>Cons: Halts the CPU, preventing multi-tasking</p><h3>3. Using timers</h3><p>C libraries provide the ability to use timers to execute specific code after the timer expires. While the timer is running, the CPU can continue executing other tasks (in this case while loop). Once the timer expires, a callback function (also known as a handler) is triggered, and it executes the code placed inside that handler.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;signal.h&gt;<br>#include &lt;time.h&gt;<br>#include &lt;unistd.h&gt; <br><br>#define TIMER_SIG1 SIGUSR1<br><br>// Global variables to track timer ticks<br>int timer1_ticks = 0;<br><br>// Timer callback function<br>void timer_callback(int sig) <br>{<br>    printf(&quot;Time handler getting execuited\n&quot;);<br>    if (sig == TIMER_SIG1) <br>    {<br>        printf(&quot;Timer 1 Ticks: %d\n&quot;, ++timer1_ticks);<br>    } <br>}<br><br>void set_timer1(int delay_in_sec, int interval_in_sec)<br>{<br>    // Set up signal handler for timer 1<br>    struct sigaction sa1;<br>    sa1.sa_flags = SA_SIGINFO;<br>    sa1.sa_sigaction = timer_callback;<br>    sigemptyset(&amp;sa1.sa_mask);<br>    if (sigaction(TIMER_SIG1, &amp;sa1, NULL) == -1) {<br>        perror(&quot;sigaction&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    // Create timer 1<br>    timer_t timerid1;<br>    struct sigevent sev1;<br>    struct itimerspec its1;<br>    sev1.sigev_notify = SIGEV_SIGNAL;<br>    sev1.sigev_signo = TIMER_SIG1;<br>    sev1.sigev_value.sival_ptr = &amp;timerid1;<br>    if (timer_create(CLOCK_REALTIME, &amp;sev1, &amp;timerid1) == -1) {<br>        perror(&quot;timer_create&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br>       <br>    // Set timer 1 expiration time and interval<br>    its1.it_value.tv_sec = delay_in_sec; <br>    its1.it_value.tv_nsec = 0;<br>    its1.it_interval.tv_sec = interval_in_sec;<br>    its1.it_interval.tv_nsec = 0;<br><br>    // Start timer 1<br>    if (timer_settime(timerid1, 0, &amp;its1, NULL) == -1) {<br>        perror(&quot;timer_settime&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br>    printf(&quot;Timer 1 started. Waiting for ticks...\n&quot;);<br><br>}<br><br>int main() {<br>    <br>    set_timer1(10,0);       //delay for 10 seconds<br>    <br>    // Print elapsed time every second<br>    int elapsed_seconds = 0;<br>    while (1) {<br>        sleep(1); // Sleep for 1 second<br>        elapsed_seconds++;<br>        printf(&quot;Elapsed time: %d seconds\n&quot;, elapsed_seconds);<br>    }<br><br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*TAFIuNVJBaUJd4XQt7q92Q.png" /><figcaption>Figure 1: Demonstrating the use of timer program in C</figcaption></figure><p>Pros: uses CPU efficiently, can be used in multi-tasking</p><p>Cons: Difficult to implement when code gets more complex, there must be another task that need to get executed in parallel</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df4cc849b19b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate a Square Waveform on an 8051 Microcontroller Using Assembly Language]]></title>
            <link>https://krutarthpurohit.medium.com/how-to-generate-a-square-waveform-on-an-8051-microcontroller-using-assembly-language-9cc11b69d5f1?source=rss-a26f04fe2124------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc11b69d5f1</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[intel]]></category>
            <category><![CDATA[8051-microcontroller]]></category>
            <category><![CDATA[semiconductors]]></category>
            <category><![CDATA[assembly-language]]></category>
            <dc:creator><![CDATA[Krutarth]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 10:14:53 GMT</pubDate>
            <atom:updated>2024-10-16T04:36:19.734Z</atom:updated>
            <content:encoded><![CDATA[<p>8051 microcontroller was designed by Intel in 1981. It is an 8-bit microcontroller, built with 40 pins DIP (dual inline package), 4kb of ROM storage and 128 bytes of RAM storage, 2 (16-bit) timers. It consists of four parallel 8-bit ports, which are programmable as well as addressable.</p><p>We will program the 8051 to generate the simple square wave and direct the output no pin no.5 of port 1. We can also simulate the output on keil uVision software.</p><h3>Assembly program to generate square wave</h3><pre>org 0000H //The program starts execution from this address in memory.<br><br>MOV TMOD, #01H<br><br>HERE: MOV TL0, #0F2H<br>      MOV TH0, #0FFH<br>      CPL P1.5<br>      ACALL DELAY<br>      SJMP HERE<br>DELAY: SETB TR0<br>AGAIN: JNB TF0, AGAIN<br>      CLR TR0 <br>      CLR TF0<br>      RET<br>END</pre><h3>Flow of the program</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*SI9FFFN4eNFIvTiUYFlDaw.png" /><figcaption>Figure 1: General flow of the program</figcaption></figure><h3>Program breakdown</h3><p>This 8051 assembly program generates a square wave on pin P1.5 by toggling its state at regular intervals using Timer 0 in 16-bit mode. The program starts by configuring Timer 0 in Mode 1, which allows it to count up to 65,535 (FFFFH). Each cycle, the lower byte (TL0) is loaded with `0F2H` and the upper byte (TH0) with `0FFH`, setting the timer to count from `FFF2H` to overflow at `FFFFH`. After setting the initial timer values, the state of P1.5 is toggled using the CPL P1.5 instruction, flipping the pin from high to low or vice versa.</p><p>The program then calls the DELAY subroutine to introduce a pause between toggles. The delay is created by starting Timer 0 (using SETB TR0) and waiting for the overflow flag (TF0) to be set. Once the timer overflows, the program clears both TR0 and TF0 to reset the timer and return from the subroutine. This process of toggling P1.5 and waiting via the timer continues in an infinite loop, creating a consistent square wave output on P1.5. The frequency of the wave depends on the delay introduced by the timer, which is determined by the values in TH0 and TL0.</p><h3>Observing waveform on keil simulator</h3><p>We can notice the waveform on the keil simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frq3cdhumpyn2K7yJaxL5A.png" /><figcaption>Figure 2: Output on keil simulator</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc11b69d5f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semaphore in RTOS (Real Time Operating System)]]></title>
            <link>https://krutarthpurohit.medium.com/semaphore-in-rtos-real-time-operating-system-2e062dbecae6?source=rss-a26f04fe2124------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e062dbecae6</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[task-scheduler]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[realtime-operating-system]]></category>
            <dc:creator><![CDATA[Krutarth]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 06:25:01 GMT</pubDate>
            <atom:updated>2024-10-06T10:16:44.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkGH2pkjDJMunc_DilS4iA.jpeg" /></figure><p>RTOS is one of the important topics in embedded system and using semaphore or mutex any engineer can harness the power of real time scheduling and access to critical region amongst the resource.</p><p>Github link to my program:</p><p><a href="https://github.com/krutarthpurohit/RTOS-Progams/blob/main/FreeRTOS/shared_resource_using_semaphore/main/shared_resource.c">RTOS-Progams/FreeRTOS/shared_resource_using_semaphore/main/shared_resource.c at main · krutarthpurohit/RTOS-Progams</a></p><h3><strong>Why we need RTOS?</strong></h3><p>Assume that you want your machine to perform multitasking. And you have two tasks which you would like to perform simultaneously: Task-1 to print “Task-1 is running” and Task-2 to print “Task-2 is running”.</p><p>This can be achieved using RTOS. Task-1 will be executed at time t1 and task-2 will be in hold state then, Task-2 will be executed at time t2 and Task-1 will be in hold state and so on…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*rjPqDKhG1NCtf3VVmyUzRA.png" /><figcaption>Figure-1: Task-1 and Task-2 will be executed simultaneously</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*fhtAhoIockUJLObiSuf0cA.png" /><figcaption>Figure-2: Demonstrating Task-1 and Task-2 getting printed on the terminal simultaneously</figcaption></figure><h3><strong>Why we need Semaphore?</strong></h3><p>Lets understand the concept of Semaphore with an analogy.</p><h3><strong>Analogy</strong></h3><p>Now, assume that there is a room, having a lock on it and in-front of the room there is a desk on which the key of the lock is kept and using that key any person can go through that door.</p><p>Now whenever any person wants to access the room, the person has to make sure that he has the key of the lock.</p><p>Let’s understand the approach to access the room step by step:-</p><p>Step-1: Person-1 first gets the key from the desk which is in-front of the door.</p><p>Step-2: Person-1 unlocks the door.</p><p>Step-3: Person-1 enters the room and the door gets locked again so no other person can access the room until the key is available again on the desk.</p><p>Now, meanwhile Person-1 is inside the room, Person-2 approaches to enter the same room but notices that key is not available so he has to wait until the key is made available by the Person-1 by keeping on it’s original spot- the desk.</p><p>Step-4: Person-1 leaves the room and keeps the key on the desk.</p><p>Step-5: Person-2 takes the key and enters the room.</p><p><strong>Here, the room is the shared resource, key is a semaphore and the person who enters the room is a task (or program).</strong></p><h3>Relating the analogy</h3><p>Any task having the semaphore (key) has a permit to access the shared resource and perform any operation on the shared resource. And the task which do not have the semaphore can not access the shared resource.</p><p>Assume two functions: Task-1 and Task-2. When the task-1 is getting called, before execution it reduces semaphore value by 1, therefore, semaphore value becomes ‘0’ indicating that the semaphore is not available to avail the shared resource. Once the task-1 has completed it’s execution in the end it adds the value of semaphore with 1. Now, the semaphore is available since it’s value is back to 1 and any other task can access the shared resource.</p><p>Now, Let’s create a program:</p><p>Shared resource has value 0</p><pre>int sharedResource = 0;</pre><p>Task-1: Adds 1 to the shared resource with the execution time of 1 seconds</p><pre>xTaskCreate(vTask1, &quot;Task 1&quot;, 2048, NULL, 2, NULL);</pre><pre>void vTask1(void *pvParameters) <br>{<br>    while (1) <br>    {<br><br>        /* Take the semaphore: this will reduce the semaphore to 0 so <br>         * that no-other task can get the access of the shared resource<br>         */<br>        if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) <br>        {<br>            // Access the shared resource<br>            sharedResource++;<br>            printf(&quot;Task 1: Shared resource incremented to %d\n&quot;, sharedResource);<br>            <br>            /* <br>             * Release the semaphore<br>             * <br>             * Once the task is complete, the task will again increment the <br>             * semaphore value with 1 before leaving so that other task <br>             * can access the shared resource and execute its program<br>             */<br>            xSemaphoreGive(xSemaphore); <br>        }<br>        vTaskDelay(1000 / portTICK_PERIOD_MS);<br>    }<br>}</pre><p>Task-2: Subtracts 1 from the shared resource with the execution time of 2 seconds</p><pre>xTaskCreate(vTask2, &quot;Task 2&quot;, 2048, NULL, 2, NULL);</pre><pre>void vTask2(void *pvParameters) <br>{<br>    while (1) <br>    {<br><br>        /* Take the semaphore: this will reduce the semaphore to 0 so <br>         * that no-other task can get the access of the shared resource<br>         */<br>        if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) <br>        {<br>            // Reduce the value of the shared resource<br>            sharedResource = sharedResource - 1;<br>            printf(&quot;Task 2: Shared resource decremented to %d\n&quot;, sharedResource);<br>            <br>            /* <br>             * Release the semaphore<br>             * <br>             * Once the task is complete, the task will again increment<br>             * the semaphore value to 1 before leaving so that other task<br>             * can get access of the shared resource and execute its program<br>             */            <br>              xSemaphoreGive(xSemaphore); <br>        }<br>        /* Higher the delay you give to task-2, more the time it will wait in block state<br>         * till then task-1 will get execuited and increment the shared resource value with 1*/<br>        vTaskDelay(2000 / portTICK_PERIOD_MS);<br>    }<br>}</pre><h3>Result and Observations</h3><p>If you look at the output punctilious, you will observe that the Task-1 is incrementing the value of ‘1’ twice and Task-2 is decrementing the value of shared resource only ‘1’ time. This is because of the delay we kept in Task-1 which is of 1 seconds and in Task-2 which is of 2 seconds. So, <strong>while</strong> <strong>task-2 is in block state for 2 seconds</strong> <strong>the</strong> <strong>task scheduler will execute task-1 twice</strong> and <strong>when the task-1 is in block state</strong>, <strong>the task scheduler will execute task-2 only once.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*zj5LQYGhVLq260OjnKtFrw.png" /><figcaption>Figure-3: Program Output</figcaption></figure><h3><strong>Entire Program</strong></h3><pre>/* <br> * Author: Krutarth Purohit<br> * <br> * In this program we use binary semaphore to share the resource systematically <br> * between two tasks: Task-A and Task-B to perforam their operation on it.<br> * <br> * Try to change the values of vTaskDelay() in Task 1 and Task 2 and then observe the output.<br> *  <br> */<br>#include &lt;stdio.h&gt;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;freertos/semphr.h&quot;<br><br>// Define a binary semaphore<br>SemaphoreHandle_t xSemaphore;<br><br>// Shared resource variable<br>int sharedResource = 0;<br><br>// Task 1 function<br>void vTask1(void *pvParameters) <br>{<br>    while (1) <br>    {<br>        if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) <br>        {<br>            sharedResource++;<br>            printf(&quot;Task 1: Shared resource incremented to %d\n&quot;, sharedResource);<br>            <br>            xSemaphoreGive(xSemaphore); <br>        }<br>        vTaskDelay(1000 / portTICK_PERIOD_MS);<br>    }<br>}<br><br>// Task 2 function<br>void vTask2(void *pvParameters) <br>{<br>    while (1) <br>    {<br>        if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) <br>        {<br>            sharedResource--;<br>            printf(&quot;Task 2: Shared resource decremented to %d\n&quot;, sharedResource);<br>            <br>            xSemaphoreGive(xSemaphore); <br>        }<br>        vTaskDelay(2000 / portTICK_PERIOD_MS);<br>    }<br>}<br><br>void app_main() <br>{<br>    // Create a binary semaphore<br>    xSemaphore = xSemaphoreCreateBinary(); <br><br>    //Giving the value (assume &#39;1&#39;) to the semaphore so it is filled<br>    xSemaphoreGive(xSemaphore);<br>    <br>    /* since the semaphore is filled, the condition will become TRUE.<br>     * Task 1 and Task 2 will be execuited<br>     */<br>    if (xSemaphore != NULL) <br>    {<br>        // Create Task 1<br>        xTaskCreate(vTask1, &quot;Task 1&quot;, 2048, NULL, 2, NULL);<br>        // Create Task 2<br>        xTaskCreate(vTask2, &quot;Task 2&quot;, 2048, NULL, 2, NULL);<br>    }<br>}</pre><p>GitHub link to my program:</p><p><a href="https://github.com/krutarthpurohit/RTOS-Progams/blob/main/FreeRTOS/shared_resource_using_semaphore/main/shared_resource.c">RTOS-Progams/FreeRTOS/shared_resource_using_semaphore/main/shared_resource.c at main · krutarthpurohit/RTOS-Progams</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e062dbecae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SPI Protocol on ESP32 (IDF 5.1 version)]]></title>
            <link>https://krutarthpurohit.medium.com/implementing-spi-protocol-on-esp32-idf-5-1-version-6f2383af1c22?source=rss-a26f04fe2124------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f2383af1c22</guid>
            <category><![CDATA[esp-idf]]></category>
            <category><![CDATA[spi]]></category>
            <category><![CDATA[esp32-programming]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Krutarth]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 09:35:44 GMT</pubDate>
            <atom:updated>2024-03-13T10:42:56.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*SgLVPzNyqCIz9Q-Zp4qKyw.png" /></figure><blockquote>GitHub link:- <a href="https://github.com/krutarthpurohit/spi_protocol">https://github.com/krutarthpurohit/spi_protocol</a></blockquote><pre>/* Author: Krutarth Purohit */<br><br>/* Including required library files */<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;inttypes.h&gt;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;esp_system.h&quot;<br>#include &quot;driver/spi_master.h&quot;<br>#include &quot;driver/gpio.h&quot;<br>#include &quot;esp_log.h&quot;<br><br>/* Defining pins for ESP32 which uses MISO, MOSI, CS, SCLK */<br>#define ESP_HOST     VSPI_HOST                              // Selecting host(ESP32) to work in VSPI mode<br>#define PIN_NUM_MISO GPIO_NUM_32                            // MISO pin is present at GPIO_NUM_32<br>#define PIN_NUM_MOSI GPIO_NUM_23                            // MOSI pin is present at GPIO_NUM_23<br>#define PIN_NUM_CLK  GPIO_NUM_18                            // SCLK pin is present at GPIO_NUM_18<br>#define PIN_NUM_CS   GPIO_NUM_5                             // CS&#39; pin is present at GPIO_NUM_5<br><br>/* Declaring the funtions which are used in the program */<br>void vSpiInit(void);<br>void spi_read_data(uint8_t addr);<br>void spi_write_data(uint8_t addr, uint8_t data);<br><br>#define SPI_TAG &quot;spi_protocol&quot;<br><br>esp_err_t ret;<br>spi_device_handle_t spi;<br><br>void vSpiInit(void)<br>{<br>    gpio_set_direction(PIN_NUM_CS, GPIO_MODE_OUTPUT);                   // Setting the CS&#39; pin to work in OUTPUT mode<br><br>    spi_bus_config_t buscfg = {                                         // Provide details to the SPI_bus_sturcture of pins and maximum data size<br>        .miso_io_num = PIN_NUM_MISO,<br>        .mosi_io_num = PIN_NUM_MOSI,<br>        .sclk_io_num = PIN_NUM_CLK,<br>        .quadwp_io_num = -1,<br>        .quadhd_io_num = -1,<br>        .max_transfer_sz = 512 * 8                                      // 4095 bytes is the max size of data that can be sent because of hardware limitations<br>    };<br><br>    spi_device_interface_config_t devcfg = {<br>        // configure device_structure<br>        .clock_speed_hz = 12 * 1000 * 1000,                             // Clock out at 12 MHz<br>        .mode = 0,                                                      // SPI mode 0: CPOL:-0 and CPHA:-0<br>        .spics_io_num = PIN_NUM_CS,                                     // This field is used to specify the GPIO pin that is to be used as CS&#39;<br>        .queue_size = 7,                                                // We want to be able to queue 7 transactions at a time<br>    };<br><br>    ret = spi_bus_initialize(ESP_HOST, &amp;buscfg, SPI_DMA_CH_AUTO);       // Initialize the SPI bus<br>    ESP_ERROR_CHECK(ret);<br><br>    ret = spi_bus_add_device(ESP_HOST, &amp;devcfg, &amp;spi);                  // Attach the Slave device to the SPI bus<br>    ESP_ERROR_CHECK(ret);<br>}<br><br>void spi_write_data(uint8_t addr, uint8_t data)     // Function to write data at given address<br>{<br>    /*If MSB of addr is set the host will read data from slave.<br>     *If MSB of addr is clear the host will write data on slave.<br>     */<br>    spi_transaction_t trans_desc = {<br>        // Configure the transaction_structure<br>        .flags = SPI_TRANS_USE_TXDATA,                                  // Set the Tx flag<br>        .tx_data = {addr, data},                                        // The host will sent the address first followed by data we provided<br>        .length = 16,                                                   // Length of the address + data is 16 bits<br>    };<br>    gpio_set_level(PIN_NUM_CS, 0);                                      // Lower the CS&#39; line to select the slave<br>    printf(&quot;Writing &#39;0x%x&#39; data at 0x%x\n&quot;, data, addr);<br>    ret = spi_device_polling_transmit(spi, &amp;trans_desc);                // spi_device_polling_transmit starts to transmit entire &#39;trans_desc&#39; structure.<br>    if (ret != ESP_OK)<br>    {<br>        ESP_LOGE(SPI_TAG, &quot;SPI write operation failed\n&quot;);<br>    }<br>    vTaskDelay(1 / portTICK_PERIOD_MS);                                 // Once data is transferred, we provide the delay and then higher the CS&#39;<br>    gpio_set_level(PIN_NUM_CS, 1);                                      // After CS&#39; is high, the slave sill get unselected<br>    printf(&quot;Writing operation completed\n\n&quot;);<br>}<br><br>void spi_read_data(uint8_t addr)               // Function to read data at given address<br>{<br>    /*If MSB of addr is set the host will read data from slave.<br>     *If MSB of addr is clear the host will write data on slave.<br>     */<br>    uint8_t instruction_to_read_data[2] = {0x80 | addr, 0xFF};             // This line sets the MSB of addr vatiable, as a command to read the loaction.<br>    spi_transaction_t trans_desc = {                                       // Configure the transaction_structure<br>                                    .flags = SPI_TRANS_USE_RXDATA,         // Set the Rx flag<br>                                    .tx_buffer = instruction_to_read_data, // Host need to first transmit the (command + address) to slave which the host wants to read<br>                                    .rxlength = 16,                        // 8*2 = 16 bit data transfer (MAX)<br>                                    .length = 16};<br>    gpio_set_level(PIN_NUM_CS, 0);<br>    ret = spi_device_polling_transmit(spi, &amp;trans_desc);<br>    if (ret != ESP_OK)<br>    {<br>        ESP_LOGE(SPI_TAG, &quot;SPI read operation failed\n&quot;);<br>    }<br>    printf(&quot;Data Read 0x%x- 0x%x\n&quot;, addr, trans_desc.rx_data[1]);              // Host can fetch the data that received from the slave from inbuild structure member- rx_data directly<br>    vTaskDelay(1 / portTICK_PERIOD_MS);<br>    gpio_set_level(PIN_NUM_CS, 1);<br>}<br><br>int app_main(void)<br>{<br>    vSpiInit();<br><br>    uint8_t addr = 0x22; // address = 0x22<br>    uint8_t data = 0xAA; // data = 0xAA<br><br>    spi_read_data(uint8_t addr); // Read the value present at address (0x22)<br>    spi_write_data(uint8_t addr, uint8_t data); // Write the value &#39;0xAA&#39; at the location 0x22<br>  <br>    return 0;<br>}</pre><h3>Hardware Connections</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBaKkoeEjl9rHijkr_pi9g.png" /><figcaption>Figure 1</figcaption></figure><h3>Including Header File</h3><p>Include the header files that are necessary for the SPI program on ESP IDF.</p><p><em>Note: Make sure you also include necessary components in your CMakeList.txt file else it will generate an error.</em></p><p>My CmakeList.txt content:</p><pre>set (srcs &quot;Source/spi_protocol.c&quot;)<br><br>idf_component_register(SRCS ${srcs}<br>                    INCLUDE_DIRS include<br>REQUIRES driver                    )</pre><p>Header Files Included in my source file:</p><pre>/* Including required library files */<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;inttypes.h&gt;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;esp_system.h&quot;<br>#include &quot;driver/spi_master.h&quot;<br>#include &quot;driver/gpio.h&quot;</pre><h3>Define the GPIO pins that are used in SPI Protocol</h3><p><em>Note: Change the GPIO pins as per the board you are using. Different board has different GPIO pins used for spi interface.</em></p><p>I am using wESP32 board (Figure 2) that has different pin configured to spi pins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuY4chmnscuKETM93baO4Q.png" /><figcaption>Figure 2: wESP32 Board</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*WSZRJmpHCTl4tGP8tMdCFQ.png" /><figcaption>Figure 3: Pins of wESP32 board that can be used for SPI- HSPI and VSPI</figcaption></figure><p>We are using host to interface with slave using<strong> VSPI</strong>.</p><ol><li>GPIO_32 used for MISO (Master In Slave Out)</li><li>GPIO_23 used for MOSI (Master Out Slave In)</li><li>GPIO_18 used to provide clock to the slave</li><li>GPIO_5 is used for Chip Select the slave</li></ol><pre>/* Defining pins for ESP32 which uses MISO, MOSI, CS&#39;, SCLK */<br>#define ESP_HOST     VSPI_HOST                              // Selecting host(ESP32) to work in VSPI mode<br>#define PIN_NUM_MISO GPIO_NUM_32                            // MISO pin is present at GPIO_NUM_32<br>#define PIN_NUM_MOSI GPIO_NUM_23                            // MOSI pin is present at GPIO_NUM_23<br>#define PIN_NUM_CLK  GPIO_NUM_18                            // SCLK pin is present at GPIO_NUM_18<br>#define PIN_NUM_CS   GPIO_NUM_5                             // CS&#39; pin is present at GPIO_NUM_5</pre><h3>Main Function</h3><pre>int main(void)<br>{<br>    vSpiInit();<br><br>    uint8_t addr = 0x22;               // address = 0x22<br>    uint8_t data = 0xAA;               // data = 0xAA<br><br>    spi_read_data(addr);               // Read the value present at address (0x22)<br>    spi_write_data(addr, data);        // Write the value &#39;0xAA&#39; at the location 0x22<br>}</pre><p>At first, we initialize the SPI function in which we have defined necessary details such as clock frequency, maximum data transfer size, spi mode, pins used for MOSI, MISO, CS’ and SCLK purpose.</p><p>Now, initialize the variable addr and data that represents address and data.</p><p>Here, I have initialized addr with 0x22 and data with 0xAA.</p><p><em>Note: Provide the address that has Read/Write access (R/W) in your slave. If your slave (sensor) has registers having Read Only (RO) then you can only perform read operation and NOT write operation. Also note that the address you define in addr has to be a valid address of a register to a corresponding sensor, for that I recommend to refer the register map present in the data sheet.</em></p><p>The sensor that I have used as a slave is ADS1293 i.e., the heart rate monitoring sensor which supports SPI protocol. (Figure 4)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*QdXbaNQ6XnqXZd-XITRZoQ.png" /><figcaption>Figure 4: ADS1293 sensor</figcaption></figure><p>Below is the register map of ADS1293 snippet taken from the datasheet. (Figure 5)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5O4IJrNgKZuOM-ykoRCQKQ.png" /><figcaption>Figure 5: Register map of ADS1293 sensor</figcaption></figure><p><em>Note: Choose the register wisely because some of it has reserved bits so in case you try to write data on that register the operation will only change the bits that are unreserved and not change the entire value of the data stored in the register.</em></p><blockquote>Link to the datasheet of ads1293: <a href="https://www.ti.com/lit/ds/symlink/ads1293.pdf">https://www.ti.com/lit/ds/symlink/ads1293.pdf</a></blockquote><p>Now call <em>spi_read_data() </em>and <em>spi_write_data() </em>functions to perform read and write operation.</p><p>spi_read_data only takes ‘addr’ as the parameter to pass because it has the address from which we have to read the data from the sensor.</p><p>spi_write_data take ‘addr’ and ‘data’ as the parameters to select the address on the sensor and then overwrite the data we provided in the arguments of the write function.</p><h3>SPI Initializing Function</h3><p>We need to first initialize SPI bus with the GPIO pins that are used as MOSI, MISO and SCLK. Then, initialize the device in which we have to define the mode of spi (spi mode- 0,1, 2 or 3), clock frequency and chip select pin (CS’). (Figure 6)</p><p><em>Note: There are other parameters that you can configure, such as bit order or queue size if you wish to. For that refer the espressif website.</em></p><blockquote><strong>spi_bus_config_t details</strong>- <a href="https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_master.html#_CPPv416spi_bus_config_t">https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_master.html#_CPPv416spi_bus_config_t</a></blockquote><blockquote><strong>spi_device_interface_config_t</strong> <strong>details</strong>- <a href="https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_master.html#_CPPv429spi_device_interface_config_t">https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_master.html#_CPPv429spi_device_interface_config_t</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*ydJjwbLIoDfWqMzI2QO1Mw.png" /><figcaption>Figure 6: Define SPI bus and device</figcaption></figure><pre>void vSpiInit(void)<br>{<br>    gpio_set_direction(PIN_NUM_CS, GPIO_MODE_OUTPUT);                   // Setting the CS&#39; pin to work in OUTPUT mode<br><br>    spi_bus_config_t buscfg = {                                         // Provide details to the SPI_bus_sturcture of pins and maximum data size<br>        .miso_io_num = PIN_NUM_MISO,<br>        .mosi_io_num = PIN_NUM_MOSI,<br>        .sclk_io_num = PIN_NUM_CLK,<br>        .quadwp_io_num = -1,<br>        .quadhd_io_num = -1,<br>        .max_transfer_sz = 512 * 8                                      // 4095 bytes is the max size of data that can be sent because of hardware limitations<br>    };<br><br>    spi_device_interface_config_t devcfg = {                            // configure device_structure<br>        .clock_speed_hz = 12 * 1000 * 1000,                             // Clock out at 12 MHz<br>        .mode = 0,                                                      // SPI mode 0: CPOL:-0 and CPHA:-0<br>        .spics_io_num = PIN_NUM_CS,                                     // This field is used to specify the GPIO pin that is to be used as CS&#39;<br>        .queue_size = 7,                                                // We want to be able to queue 7 transactions at a time<br>    };<br><br>    ret = spi_bus_initialize(ESP_HOST, &amp;buscfg, SPI_DMA_CH_AUTO);       // Initialize the SPI bus<br>    ESP_ERROR_CHECK(ret);<br><br>    ret = spi_bus_add_device(ESP_HOST, &amp;devcfg, &amp;spi);                  // Attach the Slave device to the SPI bus<br>    ESP_ERROR_CHECK(ret);<br>}</pre><h3>SPI Read Function</h3><p>Read frame structure (Figure 7):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*ORUiXGhqMQ4zFK_iny5zwQ.png" /><figcaption>Figure 7: Read frame structure</figcaption></figure><blockquote><strong>Control byte = R/W bit + 7-bit address of the register</strong></blockquote><blockquote>For Read Operation, R/W’ must be 1 (set)</blockquote><blockquote>For Write Operation, R/W’ must be 0 (clear)</blockquote><p>From the read frame structure, we can notice that we need to first lower the CS’ to select the slave connected with the host.</p><p>The control byte is the value of present in the ‘addr’ which is sent to the slave. Make sure that MSB of ‘addr’ is set to ‘1’ which gives the instruction to the slave that the host want to perform read operation on the address (7-bit value) provided in ‘addr’.</p><p>Setting the MSB of ‘addr ’ to ‘1’ is performed using masking OR operation.</p><p>For example, 0x22 in binary is 0010 0010 and 0x80 in binary is 1000 0000.</p><p>So, 0x80 | 0x22 = A2 (1010 0010 in binary)</p><pre>uint8_t instruction_to_read_data[2] = {0x80 | addr, 0xFF};</pre><blockquote>Transmitting ‘0xFF’ during a read operation in SPI serves as a “dummy” value when the slave doesn’t have meaningful data to send back to the master immediately. It helps maintain the synchronization and integrity of the communication protocol.</blockquote><p>The control byte is sent over MOSI line.</p><p>After sending the control bytes over MOSI line, the slave will sent the data fetched from the address (0x22) over MISO line.</p><pre>void spi_read_data(uint8_t addr)               // Function to read data at given address<br>{<br>    /*If MSB of addr is set the host will read data from slave.<br>     *If MSB of addr is clear the host will write data on slave.<br>     */<br>    uint8_t instruction_to_read_data[2] = {0x80 | addr, 0xFF};             // This line sets the MSB of addr vatiable, as a command to read the loaction.<br>    spi_transaction_t trans_desc = {                                       // Configure the transaction_structure<br>                                    .flags = SPI_TRANS_USE_RXDATA,         // Set the Rx flag<br>                                    .tx_buffer = instruction_to_read_data, // Host need to first transmit the (command + address) to slave which the host wants to read<br>                                    .rxlength = 16,                        // 8*2 = 16 bit data transfer (MAX)<br>                                    .length = 16};<br>    gpio_set_level(PIN_NUM_CS, 0);<br>    ret = spi_device_polling_transmit(spi, &amp;trans_desc);<br>    if (ret != ESP_OK)<br>    {<br>        ESP_LOGE(SPI_TAG, &quot;SPI read operation failed\n&quot;);<br>    }<br>    printf(&quot;Data Read %x- %x\n&quot;, addr, trans_desc.rx_data[1]);              // Host can fetch the data that received from the slave from inbuild structure member- rx_data directly<br>    vTaskDelay(1 / portTICK_PERIOD_MS);<br>    gpio_set_level(PIN_NUM_CS, 1);<br>}</pre><p><em>Note: We are not required to lower the CS’ using gpio_set_level() since “spi_device_polling_transmit()” API automatically lowers the CS’ before transmitting the data and higher the CS’ after the data is send. I have intentionally inserted gpio_set_level() to demonstrate the flow control of the program, if you wish you can remove or comment it out.</em></p><h3>SPI Write Function</h3><p>Write frame structure (Figure 8):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZdHqvepK2wiqZS6qSraTQ.png" /><figcaption>Figure 8: Write frame structure</figcaption></figure><pre>void spi_write_data(uint8_t addr, uint8_t data)     // Function to write data at given address<br>{<br>    /*If MSB of addr is set the host will read data from slave.<br>     *If MSB of addr is clear the host will write data on slave.<br>     */<br>    spi_transaction_t trans_desc = {<br>        // Configure the transaction_structure<br>        .flags = SPI_TRANS_USE_TXDATA,                                  // Set the Tx flag<br>        .tx_data = {addr, data},                                        // The host will sent the address first followed by data we provided<br>        .length = 16,                                                   // Length of the address + data is 16 bits<br>    };<br>    gpio_set_level(PIN_NUM_CS, 0);                                      // Lower the CS&#39; line to select the slave<br>    printf(&quot;Writing &#39;%x&#39; data at %x\n&quot;, data, addr);<br>    ret = spi_device_polling_transmit(spi, &amp;trans_desc);                // spi_device_polling_transmit starts to transmit entire &#39;trans_desc&#39; structure.<br>    if (ret != ESP_OK)<br>    {<br>        ESP_LOGE(SPI_TAG, &quot;SPI write operation failed\n&quot;);<br>    }<br>    vTaskDelay(1 / portTICK_PERIOD_MS);                                 // Once data is transferred, we provide the delay and then higher the CS&#39;<br>    gpio_set_level(PIN_NUM_CS, 1);                                      // After CS&#39; is high, the slave sill get unselected<br>    printf(&quot;Writing operation completed\n\n&quot;);<br>}</pre><p>From the write frame structure, we can notice that we need to first lower the CS’ to select the slave connected with the host.</p><p>The control byte is the value of present in the ‘addr’ which is sent to the slave. Make sure that MSB of ‘addr’ is set to ‘0’ which gives the instruction to the slave that the host want to perform write operation on the address (7-bit value) provided in ‘addr’. The control byte is sent over MOSI line.</p><p>After sending the control bytes over MOSI line, the host will send the next frame of data that we have specified in the main function (0xAA). This data will be overwritten at the location 0x22 of the slave. Here, both- the control byte and data byte are sent over MOSI line.</p><p><em>Note: We are not required to lower the CS’ using gpio_set_level() since “spi_device_polling_transmit()” API automatically lowers the CS’ before transmitting the data and higher the CS’ after the data is send. I have intentionally inserted gpio_set_level() to demonstrate the flow control of the program, if you wish you can remove or comment it out.</em></p><h3>Modified Main Function</h3><pre>int app_main(void)<br>{<br>    vSpiInit();<br><br>    uint8_t addr = 0x22;               // address = 0x22<br>    uint8_t data = 0xAA;               // data = 0xAA<br><br>    spi_read_data(addr);               // Read the value present at address (0x22)<br>    spi_write_data(addr, data);        // Write the value &#39;0xAA&#39; at the location 0x22<br>    spi_read_data(addr);<br>    return 0;<br>}</pre><p>In order to verify that all functions are performing as we determined, first perform read operation at some address of the slave. Then, overwrite the value at that address using write function and finally again use read function and read the value at that address again to check that whether the value is modified or not.</p><h3>Observation on Log Window</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*eDPVLgmG35Q6d4tqAw5FbA.png" /><figcaption>Figure 9: Output on ESP IDF Log window</figcaption></figure><p>As per the register mag provided in the datasheet of ADS1293, the address 0x22 holds the value 0x80.</p><p>Initially, we first read the data present at 0x22 and then modified it to 0xAA. After modifying, we again called the spi_read_data() function to verify the change we wanted in data at the location 0x22.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f2383af1c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>