<?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 Ajay Rajan on Medium]]></title>
        <description><![CDATA[Stories by Ajay Rajan on Medium]]></description>
        <link>https://medium.com/@Bluehell?source=rss-4c704295382a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vbAlM97PAa8gmJcb6MJnog.png</url>
            <title>Stories by Ajay Rajan on Medium</title>
            <link>https://medium.com/@Bluehell?source=rss-4c704295382a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 13:56:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Bluehell/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[The Ultimate High-Protein Breakfast: 50g+ Protein, 20g+ Fiber, Under 750 Calories!]]></title>
            <link>https://medium.com/@Bluehell/the-ultimate-high-protein-breakfast-50g-protein-20g-fiber-under-750-calories-7f5c352e70b2?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f5c352e70b2</guid>
            <category><![CDATA[breakfast]]></category>
            <category><![CDATA[gym]]></category>
            <category><![CDATA[nutrition]]></category>
            <category><![CDATA[meal-planning]]></category>
            <category><![CDATA[muscle-building]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 04:48:08 GMT</pubDate>
            <atom:updated>2025-03-16T07:47:11.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmVuKYxnlS2YLzR__cwerg.png" /></figure><p>(P=Protein : C=Carbs : F=Fats : Fib=Fiber : TotalCal=Total Calories)</p><p><strong>50gm Rolled oats </strong><br>P=6 : C=33 : F=4 : Fib=5 : TotalCal=195</p><p><strong>200ml Skimmed milk</strong><br>P=7 : C=10 : F=0.2 : Fib=0 : TotalCal=70</p><p><strong>100ml Yogurt</strong><br>P=8 : C=4 : F=2 : Fib=0 : TotalCal=60</p><p><strong>2 tbsp Chia Seeds (28gm)</strong><br>P=5 : C=12 : F=9 : Fib=10 : TotalCal=138</p><p><strong>1 tbsp Flax Seeds (10gm)</strong><br>P=2 : C=3 : F=4.5 : Fib=2.5 : TotalCal=55</p><p><strong>60gm Blueberries</strong><br>P=0.5 : C=9 : F=0 : Fib=1.5 : TotalCal=35</p><p><strong>7 Cashews</strong><br>P=2 : C=3 : F=4.5: Fib=0.3 : TotalCal=55</p><p><strong>1 Scoop Whey isolate Raw Unflavoured</strong><br>P=25 : C=1 : F=0 : Fib=0 : TotalCal=100</p><p><strong>1 tbsp Honey</strong><br>P=0 : C=17 : F=0 : Fib=0 : TotalCal=60</p><p><strong><em>Optional — 5gm Creatine (add just before consumption) ^_^</em></strong></p><p>Refrigerate overnight, consume for breakfast.</p><p><strong>Total Macros</strong>:<br>Calories=750kcal, Protein=55gm, Carbs=90gm, Fats=24gm, Fiber=20gm</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f5c352e70b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Undefined Behaviour in C]]></title>
            <link>https://medium.com/@Bluehell/understanding-undefined-behaviour-in-c-043dbdd40ab4?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/043dbdd40ab4</guid>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 07:35:24 GMT</pubDate>
            <atom:updated>2024-02-03T17:02:56.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxUmbdixkNMzQga1JMIWSA.jpeg" /></figure><p>UB: Undefined Behaviour.</p><p>In this article I have attached some of the most valuable literature links that will help you understand the C compiler as well as the C implementation better, which in-turn will (hopefully)make sure your code doesn’t act in an unpredictable way.</p><ol><li>Understanding why any language would even have a concept of UB:<br><a href="https://langdev.stackexchange.com/questions/481/why-would-a-language-have-a-concept-of-undefined-behavior-instead-of-raising-an">https://langdev.stackexchange.com/questions/481/why-would-a-language-have-a-concept-of-undefined-behavior-instead-of-raising-an</a></li><li>Intro to UB: <br><a href="https://en.wikipedia.org/wiki/Undefined_behavior">https://en.wikipedia.org/wiki/Undefined_behavior</a></li><li>A simple test before you get started:<br><a href="https://wordsandbuttons.online/so_you_think_you_know_c.html">https://wordsandbuttons.online/so_you_think_you_know_c.html</a></li><li><a href="https://blog.regehr.org/archives/213">https://blog.regehr.org/archives/213</a></li><li><a href="https://blog.regehr.org/archives/226">https://blog.regehr.org/archives/226</a></li><li><a href="https://blog.regehr.org/archives/232">https://blog.regehr.org/archives/232</a></li><li><a href="https://www.youtube.com/watch?v=w3_e9vZj7D8">https://www.youtube.com/watch?v=w3_e9vZj7D8</a></li></ol><p>Last but not the least, read the official C standard (23 is the latest), as much as you can. There is plethora of information related to what the implementation defines as undefined, how and when you can fall into unforeseeable traps &amp; much more.<br>Link to the doc: <br><a href="https://open-std.org/JTC1/SC22/WG14/www/docs/n3096.pdf">https://open-std.org/JTC1/SC22/WG14/www/docs/n3096.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=043dbdd40ab4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CMOS Inverter: Simplified]]></title>
            <link>https://medium.com/@Bluehell/cmos-inverter-simplified-6f99fb26aa7?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f99fb26aa7</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[transistor]]></category>
            <category><![CDATA[inverter]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 08:59:26 GMT</pubDate>
            <atom:updated>2023-04-14T08:59:26.104Z</atom:updated>
            <content:encoded><![CDATA[<p>I would start this post with an assumption that you are already a bit familiar with the CMOS circuit and have a basic overview of its operation.</p><p>An in-depth working of the N_CHANNEL and P_CHANNEL 3 terminal MOSFET(as ‘source’ and ‘body’ terminals are assumed to be connected together so as the ‘body effect’ is eliminated)(<em>I’ll be posting a detailed explanation of body effect in another post)</em> is required to understand this post.</p><p>This is the CMOS logic circuit for a basic NOT gate (Inverter).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*BhayDhVkl5Ueu9fAReFeZQ.png" /></figure><p>We will talk about two extreme cases.<br>1. When Vin is at 0 volts. (as in NOT gate logical 0)<br>2. When Vin is at Vdd volts. (as in NOT gate logical 1)</p><p>For the ease of exposition, in both the cases the<em> N channel MOS will be considered the driving transistor</em> and the <em>P channel MOS will be considered the load.</em> (Note that the circuit is symmetric and if we reverse this assumption the results then obtained will still be identical.)</p><p>To understand the concept of “load driving capability” please refer to this link:<br><a href="https://electromaniaweb.wordpress.com/2018/09/27/what-does-load-driving-capability-actually-mean/">What does “load-driving” capability actually mean?</a></p><p>Consider this graph between drain current(Id) and Vout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*4Lw-TS_XYqj8yxJ8_u28LA.png" /></figure><p>The black curve is the characteristic curve of the NMOS transistor.<br>The region before the bending of the curve(before the drain current saturates) is called the <strong><em>‘triode region’(Vds &lt; Vgs — Vt)</em></strong><em> </em>and the constant linear line after the bending at (Vd = Vgs — Vt) is known as the ‘<strong><em>saturation region’(Vds &gt; Vgs — Vt).</em></strong></p><p>This implies the ‘Drain to source’ voltage must be greater than the ‘Effective voltage’(Vgs — Vt) to form a channel between the two n-wells.</p><p>This can also be represented as:<br>=&gt; Vd — Vs — (Vg — Vs) &gt; Vt<br>=&gt; Vd — Vs — Vg + Vs &gt; Vt<br>=&gt; Vd — Vg &gt; Vt<br>=&gt; Vdg &gt; Vt or as may be visualized after reversing the sign on LHS and RHS i.e <strong><em>Vgd &lt; Vt</em></strong></p><p>( I’m assuming you are already familiar with these characteristics of a basic NMOS transistor, the signs reverse in case of a PMOS(the only difference)).</p><p>Superimposed on the characteristic curve of the NMOS is the <em>Load curve</em> of the PMOS in red color.</p><p>Now as I mentioned before, for the PMOS, Vsg will be 0 volts.</p><p>Since <strong>Vsg &lt; |Vt|</strong>, the load curve will be a horizontal straight line with zero current as shown in the graph.</p><p>The “Operating point” of the circuit will be the point at which the two curves intersect, where we can see that the Vout is nearly zero.(approximately 10mV).</p><p>Simultaneously, the current through the two devices will also be approximately zero as shown in the graph above.<br>Due to low value of the current, the power dissipation through the circuit will also be very very small! <strong>(One of the benefits of using a CMOS inverter).</strong></p><p>Now the most interesting part about this circuit is,<br>As the NMOS is operating at nearly zero voltage and current, it provides a low resistance path from the OUTPUT terminal towards the GND. <br>(The value can be calculated by dividing Vds and drain current).</p><p><strong>To summarize. Due to the low resistive path provided by the N- Channel MOSFET, the output corresponding to Vdd will be ZERO.</strong></p><p>Now exact opposite will be case corresponding to Vin = 0V, instead of Vdd.</p><p>Here is the graph which shows the operating point between the characteristic curve of the PMOS(Load curve) and Vgs(NMOS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*GiQFjNflmJby83y9I007SQ.png" /></figure><p>From this graph you have to understand and interpret the results in the exact same fashion as I had done above.</p><p>Form the above discussion we can consider the CMOS inverter to behave as an ideal inverter but there are some key points to be noted here.</p><ul><li><em>There will be wide noise margins due to maximum signal swing.</em></li><li><em>As the inverter does not operate until we provide a Vdd, the static power dissipation in the inverter will be zero. But however this is the ideal case. In real conditions there will be dissipation due to ‘Leakage currents’) To read and know more about Leakage currents in a diode please visit my post on </em><strong><em><br></em></strong><a href="https://electromaniaweb.wordpress.com/2018/09/29/origins-and-effects-of-leakage-current-in-a-diode/"><strong><em>ORIGINS AND EFFECTS OF LEAKAGE CURRENT IN A DIODE</em></strong></a></li><li><em>The active PULL-UP and PULL-DOWN devices provide the inverter with high output driving capability in both direction. This speeds up the operation considerably.</em></li><li><em>The most appreciable fact about the inverter is that the input resistance of the inverter is infinite. (I(gate) == 0). Therefore the inverter is capable of driving a large number of arbitrary inverters with no loss in signal level.( Although each additional inverter increases the load capacitance on the driving inverter and slows down the operation.(drop a comment for detailed explanation).</em></li></ul><p><strong>What about the pull-up &amp; pull-down network? <br></strong>The current in the device(CMOS INVERTER), in the state of inactivity is zero. A very essential and notable feature of the CMOS.</p><p>In spite of this fact, <em>the load-driving capability of the CMOS inverter is high</em>.</p><p>For example, with a high input(Vdd) the CMOS is able to sink a relatively large load current!</p><p>Because of its action of sinking the load current and pulling the output voltage(Vout) down towards the GND, The NMOS transistor in the CMOS inverter circuit is known as a PULL-DOWN device.<br>Similarly, with the input LOW, the PMOS is able to source a large load current.<br>Thus, pulling the output voltage up to Vdd.(PULL-UP).</p><p>A general representation of PUN and PDN:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*-rrqQXw9ZeD5PDdfZP6SPQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f99fb26aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BitWise Kung-Fu]]></title>
            <link>https://medium.com/@Bluehell/bitwise-kung-fu-using-c-d6fbe419ae81?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6fbe419ae81</guid>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 15:04:23 GMT</pubDate>
            <atom:updated>2026-09-14T04:08:17.576Z</atom:updated>
            <content:encoded><![CDATA[<p>A collection of some interesting problems that can be efficiently solved using bitwise operations in C.</p><p>This article gets updated on a regular basis &amp; the level of difficulty might or might not increase linearly as you read through the article but rest assured — every problem will be easy for you to comprehend assuming you have a bit of a background in math or low-level programming in general.</p><p>(<strong>NOTE</strong>: Please make sure to read from the beginning towards the end, as some of the questions are extensions of the previous questions with a little tweak in the problem statement yielding an entirely newer approach)</p><p>(<strong>NOTE</strong>: I dont cover edge/corner cases in the code. This code shouldn’t be deployed in production &amp; can cause serious loss/harm, please add your own sanity checks before using the functions; one of the examples is Q2 in which I have added sanity checks in detail — exactly how you should be doing for the rest of them)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*b4XI7zAosaZhJR264rM3Lw.png" /></figure><pre>/* We check if the given number if odd or even */<br>void oddEven(int n)<br>{<br>    (n&amp;1) ? printf(&quot;Odd&quot;) : printf(&quot;Even&quot;);<br>}</pre><pre>/* We delete the last K bits in a given unsigned integer */<br>uint32_t clearLastKBits(uint32_t value, uint32_t K)<br>{<br>    // check for undefined behavior<br>    // shifting the variable with the available bits(32) is UB in C<br>    // Having K &gt; 31 is also UB<br>    if (K &gt;= 32) <br>        return 0;<br><br>    //uint32_t mask = (~0 &lt;&lt; K); -&gt; Not completely accurate as the type promotion<br>    //can/will happen to int for ~0 -&gt; which may or may not yield correct result<br>    <br>    // this is accurate (Y) :)<br>    uint32_t mask = (~(uint32_t)0 &lt;&lt; K);<br>    value &amp;= mask;  <br>    return value;<br>}</pre><pre>/* We zero the bits in a given range */<br>uint32_t clearRangeOfBits(uint32_t n, uint32_t l, uint32_t h)<br>{<br>  uint32_t a = ~0 &lt;&lt; (h+1);<br>  uint32_t b = (1&lt;&lt;l) -1;<br>  n &amp;= a|b;<br>return n;<br>}</pre><pre>/* We check if the given number is a power of 2 or not */<br>void powerOf2(uint32_t n)<br>{<br>  if(n &amp;(n-1) == 0)<br>  {<br>    printf(&quot;Yes\r\n&quot;);<br>  }<br>}</pre><pre>/* Counting the number of set bits in a given unsigned integer */<br>uint32_t count_SetBits(uint32_t n)<br>{<br>    uint32_t count = 0;<br>    while(n &gt; 0)<br>    {<br>        uint8_t last_bit = (n&amp;1);<br>        count += last_bit;<br>        n &gt;&gt;= 1;<br>    }<br>    return count;<br>}</pre><pre>/* Faster method to count set bits: <br>We are counting the number of set bits here as well but we are iterating<br>only that number times as the number of set bits in the number */ <br>uint32_t count_SetBitsFaster(uint32_t n)<br>{<br>    int count = 0;<br>    while(n &gt; 0)<br>    {<br>        n &amp;= (n-1);<br>        count++;<br>    }<br>    return count;<br>}</pre><pre>/* Returning the binary equivalent integer of a given decimal number */<br>uint32_t convertToBinaryFromDecimal(uint32_t val)<br>{<br>    uint32_t res = 0;<br>    uint32_t pow = 1;<br><br>    while(val &gt; 0)<br>    {<br>        uint32_t last_bit = (val &amp; 1);<br>        res += pow*last_bit;<br>        pow *= 10;<br>        val &gt;&gt;= 1;<br>    }<br><br>    return res;<br>}</pre><pre> /* Given an array of 2N+1 numbers, find the only non-recurring number */<br>uint32_t findNonRepeatingNumber(uint32_t *A, uint32_t len)<br>{<br>    uint32_t xor = 0;<br><br>    for(uint32_t i=0 ; i&lt;len ; i++)<br>    {<br>        xor ^= A[i];<br>    }<br>    return xor;<br>}</pre><pre>/* Given an array of 2N+2 numbers, find the only 2 non-recurring number */<br>void findTwoNonRepeatingNumbers(uint32_t *A, uint32_t len)<br>{<br>    uint32_t xor = 0;<br>    for(uint32_t i=0 ; i&lt;len ; i++)<br>    {<br>        xor ^= A[i];<br>    }<br><br>    // We got the XOR of two unique numbers, others got cancelled<br><br>    // Let&#39;s find the position in this reult where atleast 1 bit is set.<br><br>    uint32_t pos = 0;<br>    uint32_t temp = xor;<br>    while((temp&amp;1) == 0)<br>    {<br>        pos++;<br>        temp &gt;&gt;= 1;<br>    }<br><br>    // Now we have the position where atleast 1 bit is set.<br><br>    // Now let&#39;s filter out the numbers in the array which have bit set at the particular position we calculated<br>    uint32_t Ai=0, Bi=0;<br>    uint32_t mask = (1 &lt;&lt; pos);<br>    for(uint32_t  i=0 ; i&lt;len ; i++)<br>    {<br>        if((A[i] &amp; mask) &gt; 0)<br>        {<br>            Ai ^= A[i];<br>        }else<br>        {<br>            Bi ^= A[i]; <br>        }<br>    }<br><br>    printf(&quot;Ai = %ul &amp; Bi = %ul \r\n&quot;, Ai, Bi);<br>}</pre><pre>/*<br>    Find unique number in the array with 3N+1 numbers<br>    <br>    2,3,4,2,5,2,4,4,5,5<br>    <br>    So, 3 is the unique number here and we need to find it.<br>*/<br><br>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;<br><br>/* Helper method for returning the number from the binary equivalent */<br>uint32_t numBits(uint32_t *sumArr)<br>{<br>    uint32_t number = 0;<br>    for(uint32_t i=0 ; i&lt;32 ; i++)<br>    {<br>        number += (sumArr[i] * (1&lt;&lt;i));<br>    }<br>    return number;<br>}<br><br><br>uint32_t uniqueNumber(uint32_t *arr, uint32_t len)<br>{<br>    uint32_t sumArr[32] = {0};<br>    <br>    for(uint32_t j=0 ; j&lt;len ; j++)<br>    {<br>        for(int i=0 ; i&lt;32 ; i++)<br>        {<br>            uint32_t ith_bit = arr[j] &amp; (1&lt;&lt;i);<br>            if(ith_bit != 0)<br>            {<br>                sumArr[i]++;    <br>            }<br>        }      <br>    }<br>    <br>    for(uint32_t i=0 ; i&lt;32 ; i++)<br>    {<br>        /* Modulo with 3 gives us either 3N or 3N+1 form */<br>        sumArr[i] = sumArr[i] % 3;<br>    }<br>    return numBits(sumArr);<br>}<br><br><br>int main(void)<br>{<br>    uint32_t arr[] = {2,9,4,5,4,5,4,2,5,2};<br>    uint32_t len = sizeof(arr)/sizeof(arr[0]);<br>    <br>    printf(&quot;The unique digit is %d &quot;, uniqueNumber(arr, len));<br>    return 0;<br>}<br><br><br>/*<br>  NOTE:<br>  This method is applicable to all kinds of problems involving odd digits<br>  such as 3N+1, 5N+1, 7N+1 etc.<br>   <br>  For the problems of the type 4N+1 you may simply do an XOR of all the <br>  elements.<br>  <br>  I have already covered the method to find the unique digit for the <br>  problem of the type 2N+2 or 4N+2 etc.<br>*/</pre><pre>/* Generate all possible substrings of a given string using bit masking.<br><br>Pointers to keep in mind:<br>For a string &quot;xyz&quot;, there are 8 possible permutations:<br>&quot; &quot; -&gt; NULL string (which is in itself a valid string).<br>x, y, z, xy, yz, zx, xyz -&gt; 7<br>Which equates to total 8 permutations.<br>Which can further be represented in binary as:<br><br>&quot; &quot; -&gt; 000<br>x   -&gt; 001<br>y   -&gt; 010<br>z   -&gt; 100<br>xy  -&gt; 011<br>yz  -&gt; 110<br>zx  -&gt; 101<br>xyz -&gt; 111<br><br>Similarly, if we consider a string of length 4, there will be 16 permutations.<br>So we know for any given string of N characters, <br>there are 2^N total possible permutations. <br><br>*/<br><br>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br><br>void generateSubStrings(char *str, uint32_t len)<br>{<br>    if(str == NULL)<br>    {<br>        printf(&quot;Empty string \r\n&quot;);<br>        return;<br>    }<br>    <br>    for(uint32_t i=0 ; i&lt; (1&lt;&lt;len) ; i++)<br>    {<br>        uint32_t temp = i;<br>        uint32_t stringIndex=0;<br>        while(temp &gt; 0)<br>        {<br>            uint32_t last_bit = (temp &amp; 1);<br>            if(last_bit != 0)<br>            {<br>                printf(&quot;%c&quot;, str[stringIndex]);<br>            }<br>            stringIndex++;<br>            temp &gt;&gt;= 1;<br>        }<br>        printf(&quot;\r\n&quot;);<br>    }<br>}<br><br>int main(void)<br>{<br>    char *s = &quot;abcde&quot;;<br>    generateSubStrings(NULL, strlen(s));<br>    return 0;<br>}<br><br></pre><pre>/*<br>Given an integer array A, return the number of AND triples.<br><br>An AND triple is a triple of indices (i, j, k) such that:<br><br>0 &lt;= i &lt; nums.length<br>0 &lt;= j &lt; nums.length<br>0 &lt;= k &lt; nums.length<br>nums[i] &amp; nums[j] &amp; nums[k] == 0, where &amp; represents the bitwise-AND operator.<br><br>Input: nums = [2,1,3]<br>Output: 12<br>Explanation: We could choose the following i, j, k triples:<br>(i=0, j=0, k=1) : 2 &amp; 2 &amp; 1<br>(i=0, j=1, k=0) : 2 &amp; 1 &amp; 2<br>(i=0, j=1, k=1) : 2 &amp; 1 &amp; 1<br>(i=0, j=1, k=2) : 2 &amp; 1 &amp; 3<br>(i=0, j=2, k=1) : 2 &amp; 3 &amp; 1<br>(i=1, j=0, k=0) : 1 &amp; 2 &amp; 2<br>(i=1, j=0, k=1) : 1 &amp; 2 &amp; 1<br>(i=1, j=0, k=2) : 1 &amp; 2 &amp; 3<br>(i=1, j=1, k=0) : 1 &amp; 1 &amp; 2<br>(i=1, j=2, k=0) : 1 &amp; 3 &amp; 2<br>(i=2, j=0, k=1) : 3 &amp; 2 &amp; 1<br>(i=2, j=1, k=0) : 3 &amp; 1 &amp; 2<br><br>*/<br><br>int countTriplets(int* A, int ASize){<br>    int cnt[1 &lt;&lt; 16] = { 0 };<br>    for (int i = 0; i &lt; ASize; i++) {<br>        cnt[A[i]]++;<br>        for (int j = i + 1; j &lt; ASize; j++) {<br>            cnt[A[i] &amp; A[j]] += 2;<br>        }<br>    } <br><br>    int res = cnt[0] * ASize;<br>    for (int i = 0; i &lt; ASize; ++i) {<br>        const int t = (~A[i]) &amp; 0xFFFF;<br>        for (int j = t; j != 0; j = (j - 1) &amp; t)<br>            res += cnt[j];<br>    }<br>    return res;<br>}<br>int main(void)<br>{<br>    uint32_t A[3] = {1,2,3};<br>    printf(&quot;%d&quot;, countTriplets(A, 3));<br>    return 0;<br>}</pre><pre>/*<br>Given 4 values &#39;m&#39;, &#39;n&#39;, &#39;x&#39; &amp; &#39;a&#39;, where:<br>&#39;a&#39; represents 32-bit hexadecimal number.<br>&#39;m&#39; &amp; &#39;n&#39; represents bit-positions in &#39;a&#39; where n &gt; m.<br>&#39;x&#39; represents a number smaller than 2^(n-m).<br><br>Your task is to -<br>Set m to the n&#39;th bit position in &#39;a&#39; with value &#39;x&#39;<br>*/<br><br>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;<br><br>uint32_t funk(uint32_t a, uint32_t m, uint32_t n, uint32_t x)<br>{<br>    uint32_t mask_m = ((1 &lt;&lt; m) - 1);<br>    printf(&quot;mask_m = %x\r\n&quot;, mask_m);<br>    uint32_t mask_n = ((1 &lt;&lt; (n+1)) - 1);<br>    printf(&quot;mask_n = %x\r\n&quot;, mask_n);<br>    <br>    //removes the unnecessary f&#39;s.<br>    uint32_t mask_n_m = mask_m ^ mask_n;<br>    printf(&quot;cumulative_mask_val = %x\r\n&quot;, mask_n_m);<br>    <br>    /*<br>        Optimal way:<br>        ((1 &lt;&lt; ((n-m) + 1)) - 1) &lt;&lt; m<br>    */<br>    <br>    //the bit-places in the new mask should have the value of x.<br>    uint32_t new_val = (x &lt;&lt; m) &amp; mask_n_m;<br>    printf(&quot;new_mask_val = %x\r\n&quot;, new_val);<br><br>    uint32_t updated_a = ((a &amp; (~mask_n_m)) | new_val);<br>    <br>    return updated_a;<br>}<br><br>int main(void)<br>{<br>    uint32_t res = funk(0xedededed, 4, 11, 0xbc);<br>    printf(&quot;%x&quot;, res);<br>    return 0;<br>}</pre><pre>/* Some fun hacks (Courtesy of Hacker&#39;s Delight) */<br><br>/* Turn off the rightmost 1-bit in a given word, producing all 0&#39;s if none. <br>For eg: 01011000 ==&gt; 01010000<br>*/<br>x &amp; (x - 1)<br><br>/* Turn on the rightmost 0-bit in a given word, producing all 1&#39;s if none. <br>For eg: 10100111 ==&gt; 10101111<br>*/<br>x | (x + 1)<br><br>/* A formula to turn off the trailing 1&#39;s in a word, producing x if none<br>For eg: 10100111 ==&gt; 10100000<br>*/<br>x &amp; (x + 1)<br><br>/* A formula to turn on the trailing 0&#39;s in a word, producing x if none<br>For eg: 10101000 ==&gt; 10101111<br>*/<br>x | (x - 1)</pre><pre>/*<br>Given any string, invert the case. If it is small case, make it upper<br>and vice versa.<br><br>Example: <br>Ajay   =&gt; aJAY<br>RaJaN  =&gt; rAjAn<br>medium =&gt; MEDIUM<br>*/<br><br>int main(void)<br>{<br>    char arr[] = &quot;Ajay&quot;;<br>    uint32_t x = (1 &lt;&lt; 5); //32 :)<br>    <br>    for (char *ptr = arr; *ptr; ptr++)<br>    {<br>        *ptr ^= x;<br>    }<br>   <br>    printf(&quot;%s&quot;, arr);<br>    return 0;<br>}</pre><pre>bool isPowerOfFour(int n) {<br>    if (n ==0)<br>    {<br>        return false;<br>    }<br>    <br>    //check if a power of 2 becz pwoer of 4 must be power of two<br>    //only 1 bit set also confirmed<br>    if ((n &amp; (n-1)) != 0)<br>    {<br>        return false;<br>    }<br>    <br>    //0x55555555 is a mask where only even positions of power of 4 are active<br>    if (((n &amp; 0x55555555)) != 0)<br>    {<br>        return true;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6fbe419ae81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The forbidden .git folder]]></title>
            <link>https://medium.com/@Bluehell/the-forbidden-git-folder-12f42470e48d?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f42470e48d</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 09:04:10 GMT</pubDate>
            <atom:updated>2024-06-17T05:17:37.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>The forbidden .git folder</h3><p>A deep dive inside the .git folder that emerges when you run the git init command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XD2Mt7aOazkgTRPemSVJ8Q.png" /></figure><p>To set the momentum, we’ll simply scroll into a folder and initialise an empty git repository and try to analyse the files that come with the initialisation process. So here’s what I did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IF1oqAMJCW_4Qp99Jq_Dwg.png" /></figure><p>Inside the folder I already had 2 files as you can observe: <br>array.exe and array.c <br>Wherein, I initialised an empty git repository using the command:</p><h3><strong>git init</strong></h3><p>This creates a hidden folder inside the current directory named <strong>.git</strong></p><p>I ventured inside this folder and tried to look at the different directories &amp; files that this folder contains:</p><p><strong>(file)HEAD: </strong>This contains a single line of text, over the course of this blog, I’ll explain exactly what this means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*_hfZy7lj3uUPvL7nCW9uDA.png" /></figure><p><strong>(file)config: </strong>A default configuration of the initialised empty git repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*HcyH8vC-rDgORKk2KAVaHg.png" /></figure><p><strong>(file)description: </strong>Simply a description of your current repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*elouFV4dKEadtmwd9UTMSA.png" /></figure><p><strong>(folder)objects: </strong>Git stores information in the form of objects in its own file-system. <br>If you look inside this folder you will not see any objects as this is an empty git repository. It has 4 object types. These Objects allows git to store all the necessary information for file changes/tracking. We can say that this is where all the heavy-lifting happens.</p><ol><li>BLOB:<br>Git stores any type of file with any extension(pictures/music/code or whatever), in the form of blobs.</li><li>TREE: <br>As it is evident with any File-system, with the help of tree object types, git stores information about Directories.</li><li>ANNOTATED TAG:<br>This is simply a persistent text pointer towards a specific commit.</li><li>COMMIT:<br>Using this object type, we are able to store different versions of our project.</li></ol><blockquote>In this post, we’ll focus mostly on blob and tree objects in git.</blockquote><p>An Overview of some Low-Level Git commands:</p><p><strong>git hash-object:<br></strong>Helps in creation of a new blob object and write it into the git repository.</p><p><strong>git cat-file:<br></strong>Used to read the information about the object contents</p><p>Next we are going to create a blob type object inside the git repository using the above mentioned low-level git command. Let’s see how this goes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*-7zOQwRtvvISs45hdo5TbQ.png" /></figure><p>As you can see, first I echoed “Hello” as a standard input to the git hash-object command. This in-turn generated a hash (Hash is nothing but a string of unique jumbled characters that are probabilistically not supposed to repeat).</p><p>Second, I echoed Hello but without the quotation marks. This also spit out the same Hash that we had seen in the first case.</p><p>Third, I echoed a different string “BYE”, which resulted in a different HASH as well.</p><p>This goes to show that for similar inputs, the computed Hash will remain the same. We will delve deeper into the hash function used by git in some time.</p><p><em>Summary of git hash-object command:</em><br>In its simplest form, git hash-object would take the content you handed to it and merely return the unique key that would be used to store it in your Git database. <br>The -w option then tells the command to not simply return the key, but to write that object to the database. <br>Finally, the --stdin option tells git hash-object to get the content to be processed from stdin; otherwise, the command would expect a filename argument at the end of the command containing the content to be used.</p><p>Let’s take a look at it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*Wo9wS4AKG-R8foOQW4XKww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*juZqkYre9V5QH0MI0tyybQ.png" /></figure><p>Just to clarify, after running the last command, the string we saw on the terminal was:<br><em>df5437a32226b4557b041f2ca1012009c7003483</em></p><p>Which is the same thing when you put together the names of the new folder inside the objects directory called “df” and the file that lies inside the df<em> </em>folder.</p><p>This goes to show that the names of the folders and the files inside the folders inside the git-fileSystem is generated based on the computed hash of the object. <br>The computed HASH is always based on the input. Just as we saw in our little experiment. When we change the input, the generated hash string changes.</p><h4><strong>Understanding Hash-Functions in detail:</strong></h4><p>Hash is generated based on any variable length input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*3ZryesYsmbk07uoLx-JPXg.png" /></figure><p>The hash value changes based on the input. As we observed before, after changing the string in the input I was able to generate a completely different hash value. The hash is generated using a Hash-Function based on the contents of the input provided.</p><p>This is a ONE-WAY function. That means you cannot trace back to the INPUT after the Hash-Function has generated the Hash based on the input.</p><p>Second thing to remember: Same I/P will result in the same Hash.</p><p>Once you have content in your object database, you can examine that content with the git cat-file command. This command is sort of a Swiss army knife for inspecting Git objects. <br>Passing -p to cat-file instructs the command to first figure out the type of content, then display it appropriately.</p><p>But remembering the SHA-1 key for each version of your file isn’t practical; plus, you aren’t storing the filename in your system — just the content. This object type is called a <strong>blob</strong>. You can have Git tell you the object type of any object in Git, given its SHA-1 key, with git cat-file -t</p><p>Some popular Hash Functions:</p><ol><li>MD5: <br>128 bit</li><li>SHA-1: <br>160 bit</li><li>SHA-256: <br>256 bit</li><li>SHA-384: <br>384 bit</li><li>SHA-512: <br>512 bit</li></ol><p>You can try out some cool hash generators online as well, such as this one:<br><a href="https://www.md5hashgenerator.com/">https://www.md5hashgenerator.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMXsp7fAFR8rGwL9qBzzJA.png" /></figure><p>You can generate SHA-1 Hash also, using the above linked online tool.</p><p>Git internally uses SHA-1 hash function.</p><p>As you noticed in all the SHA-1 hashes that we generated using the low-level git command, all the strings were represented in hexadecimal format (40 Hex characters). Which is a concise way to represent long strings. <br>SHA-1 originally is, 160 bits long.</p><p>The most relevant piece of information that we need to remember is:<br><strong>Folder name + File name = File’s SHA-1 Hash <br>(</strong>As demonstrated earlier in blog post<strong>)</strong></p><p>This paves the way for 2 important questions:</p><p><strong>#1 How many files can git store in the same repository?<br>Ans: </strong>Based on the discussion related to hash functions we have had till now, the answer is pretty straightforward: <strong>2¹⁶⁰</strong></p><p><strong>#2 What is the probability of producing same hash for 2 different files? (Also known as Hash collision probability)<br>Ans: </strong>What is the probability of getting the same number on 2 dice rolled simultaneously? It’s 1/6 * 1/6 = 1/32, i.e ~3% <br>Further, what will the probability of obtaining 2 distinct numbers on 2 simultaneously rolled dice? (1/6 * 1/6)*2 = 1/16, i.e ~6%</p><p>Let’s apply this theory in SHA1 calculations:</p><p>What is the probability of each SHA-1 hash?<br>Ans: 1/2¹⁶⁰.<br>Now just as we did before, what would be the probability of each SHA-1 hash being the same in two different SHA-1 Hash?<br>Ans: (1/2¹⁶⁰ * 1/2¹⁶⁰) = 1/2³²⁰, this would surely be one the rarest events ever to occur in the multiverse.</p><p>Therefore, the probability of a hash collision occurring while we are in the process of updating our git database is 1/2³²⁰.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — —</p><h4><strong>Tree objects:</strong></h4><p>With the help of tree object types, git stores information about directories.</p><p>As mentioned before, git file system is independent of the file system used by your OS. It has its own file system, therefore it is essential for us to peruse the permissions associated with git objects once:</p><p><strong>040000: </strong>Directory<br><strong>100644: </strong>Regular non-executable file<br><strong>100664: </strong>Regular non-executable group writeable file<br><strong>100755: </strong>Regular executable file<br><strong>120000: </strong>Symbolic link<br><strong>160000: </strong>Git-Link</p><p>Now let’s create a tree object in our database using another low level git command.</p><p>Before creating that, let me just confirm the blob object that I have already inside my objects folder in the .git folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*cqKR3KsTfZr22B1gb3U99w.png" /></figure><p>If you read though the documentation of<strong> git mktree</strong> command, you’ll notice it accepts a standard input which is further created as a tree object inside the git database. That is exactly what we are going to do as well, we will pipe the contents of a pre-created file on to, mktree.</p><p>Also keep in mind, we will not be creating this file inside the folder where initialized our git repository. Because then git will take care of creating the tree object itself for the newly created file.</p><p>I’ll create the file just 1 level above the Git-tutorial folder and then add some interesting contents inside the text file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vdt_68cN2GM7b6ortwt_4w.png" /></figure><p>First I added the permission for the file, then the file type and lastly the SHA-1 hash of the first object that we had earlier created.</p><p>Let’s see how the new tree object gets created, please go through the commands listed below step by step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jnjqrp0P1GMxJHWa-892fg.png" /></figure><p>As you can see, the new tree object got created inside the objects folder with the folder name starting with 65: which is the starting 2 hex characters of the corresponding SHA-1 hash generated when we just created the tree object.</p><p>We will again use the git-cat command to examine the contents of the git tree object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gCPiHyRBK-rPgY96_F2RA.png" /></figure><p>This is the same as the file which we created and edited just one directory level above our current directory. This confirms that the tree object was accurately created with a link to the blob object in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orAiloqK4acoHnSA-D8boQ.png" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Summary:</h3><p>We delved pretty deep inside the .git folder and made sense of the various low level git commands that can be used to inspect and troubleshoot various things, but most of the time, getting this involved is not usually worth the time spent. Therefore, consider this post simply as a learning activity that helped you to understand the hidden shenanigans that happen inside the .git folder. <br>Come to think of it, I believe this folder is hidden due to 2 major reasons:</p><p>1. You must not make any changes inside this folder without being absolutely sure of what you are trying to accomplish.</p><p>2. It is pretty complex, better to keep it out of plain sight :)</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — —</p><h4>Resources:</h4><p><a href="https://git-scm.com/docs">https://git-scm.com/docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f42470e48d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A crash course on Advanced Function() Concepts in C]]></title>
            <link>https://medium.com/@Bluehell/a-crash-course-on-advanced-function-concepts-in-c-750c82840332?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/750c82840332</guid>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[firmware]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 10:26:17 GMT</pubDate>
            <atom:updated>2020-07-06T13:52:39.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*H3HcpfHugAA_fcI-mOiHXQ.png" /><figcaption>Maximum arguments according to C99 standards are 127 not infinite :)</figcaption></figure><p>This article assumes you have basic knowledge of functions - such as void/return functions, pass by value, pass by reference as well as, are well versed with usage of pointers, bit math and structures in C.</p><ol><li><strong>VARIADIC FUNCTIONS</strong><br> — The word variadic indicates that there is some sort of change or variation involved than a normal function.<br> — The change here is that we are dealing with unknown number of arguments for a function.<br> — We typically use variadic function when we do not know the number of arguments that we passed on to the function.</li></ol><p>One famous example is the printf() function.</p><p>Now, if you look inside stdio.h, you’ll notice printf() was implemented using variadic functions (we’ll do that shortly once we cover implementation of a variadic function).</p><p>We may need to come up with such functions time to time during an application development, so the rescue library for us here is the <strong>stdarg.h</strong><br>This library provides us with routines that can help us come up with our own variadic functions.</p><p>So, by the mid of this article you’ll be equipped with tools to understand the code that makes up printf()-like functions, as well as create your own variadic functions (further along in the article, we’ll be referring to variadic functions as V.F).</p><p><strong>Understanding the components that make up a V.F</strong></p><p>V.F technically come in two parts<br>1. Mandatory arguments — at least one argument is required.<br>2. Optional arguments — listed after mandatory arguments.</p><p>A common practice, is to have some number that tells us how many arguments there actually are.</p><p><strong>Creating a V.F</strong></p><p>There are a couple of things that we need to do before we create a full fledged variadic function-</p><ol><li>We must understand how to reference the variable, the number of arguments used inside the function — because we do not know how many variables there are and we cannot possibly give them names.. right?</li><li>But this problem is indirectly solvable using <strong>pointers.</strong></li><li>stdarg.h library header provides us with routines that have been implemented as <a href="https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html#:~:text=Function-like%20macros%20can%20take,by%20commas%20and%20optionally%20whitespace.">macros</a>.</li><li>We need to use these macros when implementing our own function which is capable of accepting variable number of arguments.</li></ol><p><strong>Understanding those MACROS we were talking about</strong></p><ol><li><strong>va_list<br></strong> — Used in situation when we need to access optional parameters.<br> — Represents a data object used to hold the parameter corresponding to the <strong>ellipsis </strong>(ellipsis means … (3 dots) we’ll look more closely at this in some time)part of the parameter list.</li><li><strong>va_start<br></strong> — Will connect our argument list to some argument pointer.<br> — The list specified in va_list is the 1st argument &amp; the 2nd argument is the last fixed parameter.</li><li><strong>va_arg<br></strong> — Will be fetching the current argument connected to the argument list<br> — We need to know the type of argument that we are reading</li><li><strong>va_end</strong><br> — Used when we would like to stop using the variable argument list, also referred to as “cleanup”.</li><li><strong>va_copy<br></strong> — Used only in situation when we would like to save our current location</li></ol><p><strong>Getting on with the implementation details</strong></p><ol><li>Provide a function prototype using an ellipsis (…) — Should have at least one fixed argument, at most can be any number of fixed arguments.<br>For eg. void fun1(int x, …);<br>or int fun2(float *x, double **ptr, …);</li><li>Create a va_list type variable in the function definition.</li><li>Initialize the variable to an argument list. (here we will need to copy the argument list to the va_list variable by making use of va_start). For example -</li></ol><pre>float average(float v1, float v2, …)<br>{</pre><pre>va_list ptr_to_arg; //ptr to variable argument list</pre><pre>//Some more code goes here, discussed ahead in article</pre><pre>va_start(ptr_to_arg , v2);</pre><pre>//Some more code goes here, discussed ahead in article<br>}<br></pre><p>4. The cumulative effect of calling va_start is to set the variable ptr_to_arg to point to the first variable argument that is passed to the function when it is called.</p><p>5. Now we need to access the content of the argument list using va_arg()</p><p>6. va_arg() takes two arguments — 1. A type va_list variable, a type name<br> — The first time it is called it returns the first argument in the list.<br>— The second time it is called it returns the second argument in the list.<br> — The type argument specifies the type of value returned ( which has to obviously match the specification ) .</p><pre>float some_function(int line, …)<br>{<br>va_list(ap); //declare object to hold arguments</pre><pre>va_start(ap, line); //initialise ap to argument list</pre><pre>float goat = va_arg(ap, float);</pre><pre>int cow = va_arg(ap, int);<br>}</pre><p>7. The last step is cleaning up the routine by using the va_end() command.<br> — It technically tidies up the loose ends.<br> — takes va_list variable as an argument.<br> — resets the above mentioned pointer to NULL.<br> — <strong>Do not OMIT this call</strong>, else there would be undesirable repercussions in your code behavior.</p><p>These were the steps and a lot to remember details for implementing a variadic function! Now we’ll be implementing one, practically.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdarg.h&gt;</pre><pre>double average(double v1, double v2, ... );</pre><pre>int main(void)<br>{<br>double v1 = 10.5, v2 = 2.5;<br>int num1 = 6, num2 = 5;<br>long num3 = 12L, num4 = 20L;<br>printf(&quot;Average is %.2lf\n&quot;, average(v1, 3.5, v2, 4.5, 0.0) );<br>printf(&quot;Average is %.2lf\n&quot;, average(1.0, 2.0, 0.0) );<br>printf(&quot;Average is %.2lf\n&quot;, average((double)num2, v2, (double)num1, (double)num3 ));</pre><pre>return 0;<br>}</pre><pre>//Implementing our variadic function<br>double average(double v1, double v2, ...)<br>{</pre><pre>va_list ptr_to_arg;</pre><pre>double sum  = v1 + v2;<br>double value = 0.0;</pre><pre>int count = 2;</pre><pre>va_start(ptr_to_arg, v2);</pre><pre>while((value = va_arg(ptr_to_arg, float)) != 0.0 )<br>{<br>sum +=value;<br>++count;<br>}</pre><pre>va_end(ptr_to_arg);</pre><pre>return sum/count;</pre><pre>}</pre><p>This was a pretty straight forward program that calculates average of all the arguments passed onto the average function.</p><p>The code above is intentionally not commented, I did not want to make this walk in the park for you, I want you to follow the steps for creating V.F and match them with the code so that it is concretely set in your mind and you will be henceforth able to create your own V.F’s.</p><p><strong>2. INLINE FUNCTIONS</strong></p><p>The usage of inline functions are completely optional and not even necessary in some and most cases, but it is good to know what they represent and how they are used to increase performance of the code, and some scenarios where using an inline function may not be completely optimal.</p><p>Whenever you invoke a function call, it comes with a overhead along with it, the execution takes time to set up the call, pass the corresponding arguments, jump to function call and then return.</p><p>The main reason C99 standard added inline functions in their specs is to try and avoid the amount of overhead that comes along in invoking a function.</p><p>It seems logical to think that we put in some extra effort in invoking the function which infact should be giving us some performance benefits as compared to otherwise.</p><p><strong>NOTE — The inline declaration is only an advice to the compiler which can decide to ignore it altogether if it wants to!</strong></p><p>And for people who are from have the view point that inline functions improve the performance of your code <br>1. This is not at all guaranteed<br>2. Whether an inline function serves your function in a +ve or in a -ve way depends purely on your code design and is largely debatable.</p><p><strong>NOTE — If there are many lines in an inline function or there are a lot of calls then using an inline function can cause wastage of space.</strong></p><p>It is suggested to use inline function only and only if they are short &amp; called frequently.<br>For a long function, time spent in calling the function is short as compared to the time spent while executing the body of the function.</p><p>An example of an inline function —</p><pre>inline int random();</pre><p>The inline function has to be in the same file as the function call — this is called internal linkage.</p><p>For the same file you may also declare it as —</p><pre>static inline void foo(int *i)</pre><pre>{</pre><pre>//Doing something short</pre><pre>}</pre><p>That was all you’d need to know about inline functions!</p><p>Now you can go ahead and look at more constructs by referring to the C11 or C99 standard and compare them with one another or compare the older ones with newer replacements as an exercise.</p><p>Talking of an exercise you can contrast a difference between <strong>sprintf() </strong>&amp; <strong>snprintf(), </strong>why did we need <strong>snprintf()</strong> ? Do a quick google search, read some documentation and let’s discuss it in the comments.</p><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750c82840332" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SYSTICK-TIMER with a bare-metal application]]></title>
            <link>https://medium.com/@Bluehell/understanding-systick-timer-with-a-bare-metal-application-baaa2f47bc5b?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/baaa2f47bc5b</guid>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 06:56:24 GMT</pubDate>
            <atom:updated>2024-07-20T05:03:47.557Z</atom:updated>
            <content:encoded><![CDATA[<p>What is Systick and why do we need it?</p><p>A simple answer for this question would be — It is simply a 24-bit down-counting timer inside the ARM-CortexM4 processor. <br>It is integrated inside the Nested vector interrupt controller and is capable of generating the famous “systick exception” which is handled by its ISR - <strong>SysTick Handler. </strong>This timer can run on processor clock frequency or external clock frequency.</p><p>The reason for this timer to be inside the processor is for software portability.</p><p>How?</p><p>Well, In modern operating systems, a periodic interrupt is needed to make sure that the kernel can invoke regularly. For example, when you context switch between two tasks, an interrupt is fired by the down-counting systick timer, which technically is responsible for telling your task that its time slice is over, and now it is time for the next task to take over.</p><p>But how did that help in software portability?</p><p>Since all Cortex-M3/M4 processors have the same 24-bit down counting Systick timer inside them, an OS written for one Cortex-M3/M4 microcontroller can be easily reused for other Cortex-M3/M4 microcontrollers.</p><p>It is understandable if you do not need an RTOS running on your microcontroller, you can still use the SysTick as a general timer peripheral for generating delays as well as SysTick interrupts &amp; even measure time.</p><p>Now, if you create a project in KEIL-MDK, using only the CMSIS-core and the startup file, in the core_cm4.h header, you will notice this struct -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoFCUMeW6mZj5qRhf0iymA.png" /></figure><p>When the counter is enabled by setting the bit 0 of the control status register, the current value register decrements at every processor clock cycle/every rising edge of the reference clock. If this reaches zero — It will then load the value from the reload value register and then continue.</p><p>Additionally a systick_calibration register is also available to provide calibration information to the software but in CMSIS_Core the use of calibration register is not required (This is handled by the software itself and we don’t need to go into the calibration handling details for now).</p><p>So, what we’ll be doing in this article is to generate interrupts using Systick and create delays in our software routine and we’ll be blinking some beautiful patterns on the on-board as well as external RGB-LED module.</p><p>We only need to generate a periodic interrupt, the best way moving forward is to use the CMSIS-Core function called “Systick_Config”<br><strong>uint32_t SysTick_Config(uint32_t ticks)</strong></p><p>This function sets the systick interrupt interval to ticks, enables the counter using processor clock as well as enables systick exception with lowest systick priority.<br>For eg. If you have a clk freq of 50Mhz and you want to trigger a systick exception of 1Khz, you should use -<br>SysTick_Config(SystemCoreClock / 1000);</p><p>The SystemCoreClock holds the current frequency value of 50x10⁶ .</p><p>If you do not want to include SystemCoreClock here, you can simply make a calculation and do it this way-</p><p>SysTick_Config( 50x10⁶ / 1000);<br>Which will be equal to — Systick_Config(50000);</p><p>Great, you have successfully configured SysTick_handler to trigger at the rate of 1Khz.</p><p>Further configurations for the ISR will be discussed shortly in the article.</p><p>Now let us look at some code for STM32F411VET6 Discovery</p><pre>#include&lt;stm32f411xe.h&gt;<br>#include&lt;stdint.h&gt;</pre><pre>//Defining the ODR bits (Output data register)<br>#define RED (1U &lt;&lt; 14)<br>#define BLUE (1U &lt;&lt; 15)<br>#define GREEN (1U &lt;&lt; 12)<br>#define ORANGE (1U &lt;&lt; 13)</pre><pre>//define the GPIOD clock bit<br>#define GPIOD_CLOCK (1U &lt;&lt; 3)</pre><pre>//#define the GPIO MODER register<br>#define RED_BIT (1U &lt;&lt; 28)<br>#define BLUE_BIT (1U &lt;&lt; 30) <br>#define GREEN_BIT (1U &lt;&lt; 24)<br>#define ORANGE_BIT (1U &lt;&lt; 26)</pre><pre>//Prototypes<br>void GPIO_Init(void);<br>void SysTick_Handler(void);<br>uint32_t get_tick(void);<br>void delay_sec(uint32_t seconds);<br>void blue_on(void);<br>void blue_off(void);<br>void orange_on(void);<br>void orange_off(void);<br>void green_on(void);<br>void green_off(void);<br>void red_on(void);<br>void red_off(void);<br>void blue_main(void);<br>void orange_main(void);<br> <br>volatile static uint32_t tick;<br>volatile static uint32_t _tick;</pre><pre>int main(void)<br>{<br> <br> GPIO_Init();</pre><pre>while(1)<br> {<br>//blinking blue LED<br> blue_on();<br> delay_sec(1);<br> blue_off();<br> delay_sec(1);</pre><pre>//blinking red LED <br> red_on();<br> delay_sec(1);<br> red_off();<br> delay_sec(1);<br> <br> orange_on();<br> delay_sec(1);<br> orange_off();<br> delay_sec(1);<br> <br> //LED blinking combinations<br> GPIOD-&gt;ODR |= BLUE | ORANGE;<br> delay_sec(1);<br> GPIOD-&gt;ODR &amp;= ~(BLUE | ORANGE);<br> delay_sec(1);<br> <br> GPIOD-&gt;ODR |= BLUE | RED;<br> delay_sec(1);<br> GPIOD-&gt;ODR &amp;= ~(BLUE | RED);<br> delay_sec(1);<br> <br> GPIOD-&gt;ODR |= RED | ORANGE;<br> delay_sec(1);<br> GPIOD-&gt;ODR &amp;= ~(RED | ORANGE);<br> delay_sec(1);<br> <br> GPIOD-&gt;ODR |= BLUE | ORANGE | RED;<br> delay_sec(2);<br> GPIOD-&gt;ODR &amp;= ~(BLUE | ORANGE | RED);<br> delay_sec(2);<br> }<br> <br>}</pre><pre>//Some necessary GPIO Initialization<br>void GPIO_Init(void)<br>{<br>//Enabling peripheral clock<br>RCC-&gt;AHB1ENR |= GPIOD_CLOCK;<br></pre><pre> GPIOD-&gt;MODER |= RED_BIT | BLUE_BIT | GREEN_BIT | ORANGE_BIT;</pre><pre> SystemCoreClockUpdate();<br> SysTick_Config(SystemCoreClock/100U);<br> <br> <br> __enable_irq();<br> <br>}</pre><p>At the last line of the code we enable the interrupt request line for Systick using the API provided in CMSIS core.</p><p>Additionally, these are the routines to follow to turn on and off the on-board LED’s</p><pre>void blue_on(void)<br>{<br>GPIOD-&gt;ODR |= BLUE;<br>}</pre><pre>void blue_off(void)<br>{<br>GPIOD-&gt;ODR &amp;= ~BLUE;<br>}</pre><pre>void orange_on(void)<br>{<br>GPIOD-&gt;ODR |= ORANGE;<br>}</pre><pre>void orange_off(void)<br>{<br>GPIOD-&gt;ODR &amp;= ~ORANGE;<br>}</pre><pre>void red_on(void)<br>{<br>GPIOD-&gt;ODR |= RED;<br>}</pre><pre>void red_off(void)<br>{<br>GPIOD-&gt;ODR &amp;= ~RED;<br>}</pre><pre>void green_on(void)<br>{<br>GPIOD-&gt;ODR |= GREEN;<br>}</pre><pre>void green_off(void)<br>{<br>GPIOD-&gt;ODR &amp;= ~GREEN;<br>}</pre><p>We had declared two global variables <br>volatile static uint32_t tick;<br>volatile static uint32_t _tick;</p><p>These will be used to increment the tick value inside the ISR and then provide it to the get_tick() method which will be further used for generating the required delay of 1 seconds.. As we require the delay in seconds we also need to multiply seconds with 100.</p><pre>//ISR implementation<br>void SysTick_Handler(void)<br>{<br>++tick;<br>}<br></pre><pre>uint32_t get_tick(void)<br>{<br>__disable_irq();<br>_tick = tick;<br>__enable_irq();<br> return _tick;<br>}</pre><pre>//Delay generation<br>void delay_sec(uint32_t seconds)<br>{<br> seconds *= 1000;<br> uint32_t temp = get_tick();<br> while((get_tick() — temp) &lt; seconds){} <br>}</pre><p>This is the firmware required to generate a delay of 1 second using the SysTick interrupt.</p><p>Let’s take a brief look at the Discovery board and RGB LED Module connection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*hE1a771Gzk48URDPe9bpMQ.jpeg" /><figcaption>STM32F411VET6 DISCOVERY KIT</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UXLwd0u7gky1G3RXlwCkmQ.jpeg" /><figcaption>RGB LED module</figcaption></figure><p>The last pin is <strong>GND</strong>, connect that pin to the <strong>GND</strong> of your MCU and Since we are configuring the on-board LED’s in our code, we have pin-outs for those respective GPIO’s too i.e <strong>PB12, PB13, PB14, PB15</strong>.</p><p>Connect 3 of those pin-outs to the RGB LED Module pin-outs and connect the board to your PC to upload the firmware.</p><p>The firmware is designed in such a way that after seeing the three primary colors on the module you’ll additionally see yellow, pink, aqua and Magenta(R+G+B) colors.</p><p>Here is the demo video for reference</p><p><a href="https://www.youtube.com/watch?v=ayocTZ7VSaI"><strong>RGB module with STM32F411VET6</strong></a></p><p>In the coming article, we’ll be configuring the SyTick registers and configuring the timer in more fun ways.</p><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baaa2f47bc5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wifi-Controlled LED Matrix Display System using NodeMCU]]></title>
            <link>https://medium.com/@Bluehell/wifi-controlled-led-matrix-display-system-using-nodemcu-6bcf130af687?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bcf130af687</guid>
            <category><![CDATA[display-build]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 04:48:13 GMT</pubDate>
            <atom:updated>2020-06-29T04:48:13.649Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a year old project, but I randomly tested it yesterday on my hardware; it still works just as fine!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*bG5YFBWhEiDJ1cSZlBsk9g.png" /></figure><p><strong>Components required:</strong><br>1. NodeMCU (ESP-8266)<br>2. A 4-in-1 8×8 LED Matrix(FC_16, Parola, GENERIC or IC_Station)<br>3. A Laptop with Arduino IDE</p><p>In this project, I have used a max72xx library(The download links will be given at the end of the post). The source code will need to be edited according to the module that you will be using<br>(FC_16, Parola, GENERIC or IC_Station).</p><p>Earlier this needed to be set inside the library file, but with the updated library you can make some changes in the source code and make it running for any kind of module.</p><p><strong>Circuit Connections:</strong></p><p>Vcc — — — — 3v3<br>GND — — — — GND Ground<br>DIN — — — — D7 HSPID or HMOSI<br>CS or LD — — — — D8 HSPICS or HCS<br>CLK — — — — D5 CLK or HCLK</p><p>Download and include this libraries before starting<br>1.<a href="https://github.com/MajicDesigns/MD_MAX72XX"> https://github.com/MajicDesigns/MD_MAX72XX</a></p><p><strong>CODE</strong></p><pre>// IP address for the ESP8266 is displayed on the scrolling display<br><br><br>#include &lt;ESP8266WiFi.h&gt;<br>#include &lt;MD_MAX72xx.h&gt;<br>#include &lt;SPI.h&gt;<br><br>#define  PRINT_CALLBACK  0<br>#define DEBUG 0<br>#define LED_HEARTBEAT 0<br><br>#if DEBUG<br>#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }<br>#define PRINTS(s)   { Serial.print(F(s)); }<br>#else<br>#define PRINT(s, v)<br>#define PRINTS(s)<br>#endif<br><br><br>#if LED_HEARTBEAT<br>#define HB_LED  D2<br>#define HB_LED_TIME 500 // in milliseconds<br>#endif<br><br>// Define the number of devices we have in the chain and the hardware interface<br>// NOTE: These pin numbers will probably not work with your hardware and may<br>// need to be adapted<br>#define MAX_DEVICES 4<br><br>#define CLK_PIN   D5 // or SCK<br>#define DATA_PIN  D7 // or MOSI<br>#define CS_PIN    D8 // or SS<br><br>// SPI hardware interface<br>//MD_MAX72XX mx = MD_MAX72XX(CS_PIN, MAX_DEVICES);<br>#define HARDWARE_TYPE MD_MAX72XX::PAROLA_HW  //edit this as per your LED matrix hardware type<br>MD_MAX72XX mx = MD_MAX72XX(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);<br>// Arbitrary pins<br>//MD_MAX72XX mx = MD_MAX72XX(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);<br><br>// WiFi login parameters - network name and password<br>const char* ssid = &quot; &quot;;                   // edit your wifi SSID here<br>const char* password = &quot; &quot;;            // edit your wifi password here<br><br>// WiFi Server object and parameters<br>WiFiServer server(80);<br><br>// Global message buffers shared by Wifi and Scrolling functions<br>const uint8_t MESG_SIZE = 255;<br>const uint8_t CHAR_SPACING = 1;<br>const uint8_t SCROLL_DELAY = 75;<br><br>char curMessage[MESG_SIZE];<br>char newMessage[MESG_SIZE];<br>bool newMessageAvailable = false;<br><br>char WebResponse[] = &quot;HTTP/1.1 200 OK\nContent-Type: text/html\n\n&quot;;<br><br>char WebPage[] =<br>&quot;&lt;!DOCTYPE html&gt;&quot; \<br>&quot;&lt;html&gt;&quot; \<br>&quot;&lt;head&gt;&quot; \<br>&quot;&lt;title&gt;MAX7219 ESP8266&lt;/title&gt;&quot; \<br>&quot;&lt;style&gt;&quot; \<br>&quot;html, body&quot; \ <br>&quot;{&quot; \<br>&quot;width: 600px;&quot; \<br>&quot;height: 400px;&quot; \<br>&quot;margin: 0px;&quot; \<br>&quot;border: 0px;&quot; \<br>&quot;padding: 10px;&quot; \<br>&quot;background-color: white;&quot; \<br>&quot;}&quot; \<br>&quot;#container &quot; \<br>&quot;{&quot; \<br>&quot;width: 100%;&quot; \<br>&quot;height: 100%;&quot; \<br>&quot;margin-left: 200px;&quot; \<br>&quot;border: solid 2px;&quot; \<br>&quot;padding: 10px;&quot; \<br>&quot;background-color: #b3cbf2;&quot; \<br>&quot;}&quot; \          <br>&quot;&lt;/style&gt;&quot;\<br>&quot;&lt;script&gt;&quot; \<br>&quot;strLine = \&quot;\&quot;;&quot; \<br>&quot;function SendText()&quot; \<br>&quot;{&quot; \<br>&quot;  nocache = \&quot;/&amp;nocache=\&quot; + Math.random() * 1000000;&quot; \<br>&quot;  var request = new XMLHttpRequest();&quot; \<br>&quot;  strLine = \&quot;&amp;MSG=\&quot; + document.getElementById(\&quot;txt_form\&quot;).Message.value;&quot; \<br>&quot;  request.open(\&quot;GET\&quot;, strLine + nocache, false);&quot; \<br>&quot;  request.send(null);&quot; \<br>&quot;}&quot; \<br>&quot;&lt;/script&gt;&quot; \<br>&quot;&lt;/head&gt;&quot; \<br>&quot;&lt;body&gt;&quot; \<br>&quot;&lt;div id=\&quot;container\&quot;&gt;&quot;\<br>&quot;&lt;H1&gt;&lt;b&gt;WiFi MATRIX DISPLAY SYSTEM &lt;/b&gt;&lt;/H1&gt;&quot; \ <br>&quot;&lt;form id=\&quot;txt_form\&quot; name=\&quot;frmText\&quot;&gt;&quot; \<br>&quot;&lt;label&gt;Msg:&lt;input type=\&quot;text\&quot; name=\&quot;Message\&quot; maxlength=\&quot;255\&quot;&gt;&lt;/label&gt;&lt;br&gt;&lt;br&gt;&quot; \<br>&quot;&lt;/form&gt;&quot; \<br>&quot;&lt;br&gt;&quot; \<br>&quot;&lt;input type=\&quot;submit\&quot; value=\&quot;Send Text\&quot; onclick=\&quot;SendText()\&quot;&gt;&quot; \<br>&quot;&lt;p&gt;&lt;b&gt;Visit Us at&lt;/b&gt;&lt;/p&gt;&quot; \ <br>&quot;&lt;a href=\&quot;http://www.electromaniaweb.wordpress.com\&quot;&gt;www.electromaniaweb.wordpress.com&lt;/a&gt;&quot; \<br>&quot;&lt;/div&gt;&quot; \<br>&quot;&lt;/body&gt;&quot; \<br>&quot;&lt;/html&gt;&quot;;<br><br>char *err2Str(wl_status_t code)<br>{<br>  switch (code)<br>  {<br>  case WL_IDLE_STATUS:    return(&quot;IDLE&quot;);           break; // WiFi is in process of changing between statuses<br>  case WL_NO_SSID_AVAIL:  return(&quot;NO_SSID_AVAIL&quot;);  break; // case configured SSID cannot be reached<br>  case WL_CONNECTED:      return(&quot;CONNECTED&quot;);      break; // successful connection is established<br>  case WL_CONNECT_FAILED: return(&quot;CONNECT_FAILED&quot;); break; // password is incorrect<br>  case WL_DISCONNECTED:   return(&quot;CONNECT_FAILED&quot;); break; // module is not configured in station mode<br>  default: return(&quot;??&quot;);<br>  }<br>}<br><br>uint8_t htoi(char c)<br>{<br>  c = toupper(c);<br>  if ((c &gt;= &#39;0&#39;) &amp;&amp; (c &lt;= &#39;9&#39;)) return(c - &#39;0&#39;);<br>  if ((c &gt;= &#39;A&#39;) &amp;&amp; (c &lt;= &#39;F&#39;)) return(c - &#39;A&#39; + 0xa);<br>  return(0);<br>}<br><br>boolean getText(char *szMesg, char *psz, uint8_t len)<br>{<br>  boolean isValid = false;  // text received flag<br>  char *pStart, *pEnd;      // pointer to start and end of text<br><br>  // get pointer to the beginning of the text<br>  pStart = strstr(szMesg, &quot;/&amp;MSG=&quot;);<br><br>  if (pStart != NULL)<br>  {<br>    pStart += 6;  // skip to start of data<br>    pEnd = strstr(pStart, &quot;/&amp;&quot;);<br><br>    if (pEnd != NULL)<br>    {<br>      while (pStart != pEnd)<br>      {<br>        if ((*pStart == &#39;%&#39;) &amp;&amp; isdigit(*(pStart+1)))<br>        {<br>          // replace %xx hex code with the ASCII character<br>          char c = 0;<br>          pStart++;<br>          c += (htoi(*pStart++) &lt;&lt; 4);<br>          c += htoi(*pStart++);<br>          *psz++ = c;<br>        }<br>        else<br>          *psz++ = *pStart++;<br>      }<br><br>      *psz = &#39;\0&#39;; // terminate the string<br>      isValid = true;<br>    }<br>  }<br><br>  return(isValid);<br>}<br><br>void handleWiFi(void)<br>{<br>  static enum { S_IDLE, S_WAIT_CONN, S_READ, S_EXTRACT, S_RESPONSE, S_DISCONN } state = S_IDLE;<br>  static char szBuf[1024];<br>  static uint16_t idxBuf = 0;<br>  static WiFiClient client;<br>  static uint32_t timeStart;<br><br>  switch (state)<br>  {<br>  case S_IDLE:   // initialise<br>    PRINTS(&quot;\nS_IDLE&quot;);<br>    idxBuf = 0;<br>    state = S_WAIT_CONN;<br>    break;<br><br>  case S_WAIT_CONN:   // waiting for connection<br>    {<br>      client = server.available();<br>      if (!client) break;<br>      if (!client.connected()) break;<br><br>#if DEBUG<br>      char szTxt[20];<br>      sprintf(szTxt, &quot;%03d:%03d:%03d:%03d&quot;, client.remoteIP()[0], client.remoteIP()[1], client.remoteIP()[2], client.remoteIP()[3]);<br>      PRINT(&quot;\nNew client @ &quot;, szTxt);<br>#endif<br><br>      timeStart = millis();<br>      state = S_READ;<br>    }<br>    break;<br><br>  case S_READ: // get the first line of data<br>    PRINTS(&quot;\nS_READ&quot;);<br>    while (client.available())<br>    {<br>      char c = client.read();<br>      if ((c == &#39;\r&#39;) || (c == &#39;\n&#39;))<br>      {<br>        szBuf[idxBuf] = &#39;\0&#39;;<br>        client.flush();<br>        PRINT(&quot;\nRecv: &quot;, szBuf);<br>        state = S_EXTRACT;<br>      }<br>      else<br>        szBuf[idxBuf++] = (char)c;<br>    }<br>    if (millis() - timeStart &gt; 1000)<br>    {<br>      PRINTS(&quot;\nWait timeout&quot;);<br>      state = S_DISCONN;<br>    }<br>    break;<br><br><br>  case S_EXTRACT: // extract data<br>    PRINTS(&quot;\nS_EXTRACT&quot;);<br>    // Extract the string from the message if there is one<br>    newMessageAvailable = getText(szBuf, newMessage, MESG_SIZE);<br>    PRINT(&quot;\nNew Msg: &quot;, newMessage);<br>    state = S_RESPONSE;<br>    break;<br><br>  case S_RESPONSE: // send the response to the client<br>    PRINTS(&quot;\nS_RESPONSE&quot;);<br>    // Return the response to the client (web page)<br>    client.print(WebResponse);<br>    client.print(WebPage);<br>    state = S_DISCONN;<br>    break;<br><br>  case S_DISCONN: // disconnect client<br>    PRINTS(&quot;\nS_DISCONN&quot;);<br>    client.flush();<br>    client.stop();<br>    state = S_IDLE;<br>    break;<br><br>  default:  state = S_IDLE;<br>  }<br>}<br><br>void scrollDataSink(uint8_t dev, MD_MAX72XX::transformType_t t, uint8_t col)<br>// Callback function for data that is being scrolled off the display<br>{<br>#if PRINT_CALLBACK<br>  Serial.print(&quot;\n cb &quot;);<br>  Serial.print(dev);<br>  Serial.print(&#39; &#39;);<br>  Serial.print(t);<br>  Serial.print(&#39; &#39;);<br>  Serial.println(col);<br>#endif<br>}<br><br>uint8_t scrollDataSource(uint8_t dev, MD_MAX72XX::transformType_t t)<br>// Callback function for data that is required for scrolling into the display<br>{<br>  static enum { S_IDLE, S_NEXT_CHAR, S_SHOW_CHAR, S_SHOW_SPACE } state = S_IDLE;<br>  static char   *p;<br>  static uint16_t curLen, showLen;<br>  static uint8_t  cBuf[8];<br>  uint8_t colData = 0;<br><br>  // finite state machine to control what we do on the callback<br>  switch (state)<br>  {<br>  case S_IDLE: // reset the message pointer and check for new message to load<br>    PRINTS(&quot;\nS_IDLE&quot;);<br>    p = curMessage;      // reset the pointer to start of message<br>    if (newMessageAvailable)  // there is a new message waiting<br>    {<br>      strcpy(curMessage, newMessage); // copy it in<br>      newMessageAvailable = false;<br>    }<br>    state = S_NEXT_CHAR;<br>    break;<br><br>  case S_NEXT_CHAR: // Load the next character from the font table<br>    PRINTS(&quot;\nS_NEXT_CHAR&quot;);<br>    if (*p == &#39;\0&#39;)<br>      state = S_IDLE;<br>    else<br>    {<br>      showLen = mx.getChar(*p++, sizeof(cBuf) / sizeof(cBuf[0]), cBuf);<br>      curLen = 0;<br>      state = S_SHOW_CHAR;<br>    }<br>    break;<br><br>  case S_SHOW_CHAR: // display the next part of the character<br>    PRINTS(&quot;\nS_SHOW_CHAR&quot;);<br>    colData = cBuf[curLen++];<br>    if (curLen &lt; showLen)<br>      break;<br><br>    // set up the inter character spacing<br>    showLen = (*p != &#39;\0&#39; ? CHAR_SPACING : (MAX_DEVICES*COL_SIZE)/2);<br>    curLen = 0;<br>    state = S_SHOW_SPACE;<br>    // fall through<br><br>  case S_SHOW_SPACE:  // display inter-character spacing (blank column)<br>    PRINT(&quot;\nS_ICSPACE: &quot;, curLen);<br>    PRINT(&quot;/&quot;, showLen);<br>    curLen++;<br>    if (curLen == showLen)<br>      state = S_NEXT_CHAR;<br>    break;<br><br>  default:<br>    state = S_IDLE;<br>  }<br><br>  return(colData);<br>}<br><br>void scrollText(void)<br>{<br>  static uint32_t prevTime = 0;<br><br>  // Is it time to scroll the text?<br>  if (millis() - prevTime &gt;= SCROLL_DELAY)<br>  {<br>    mx.transform(MD_MAX72XX::TSL);  // scroll along - the callback will load all the data<br>    prevTime = millis();      // starting point for next time<br>  }<br>}<br><br>void setup()<br>{<br>#if DEBUG<br>  Serial.begin(115200);<br>  PRINTS(&quot;\n[MD_MAX72XX WiFi Message Display]\nType a message for the scrolling display from your internet browser&quot;);<br>#endif<br><br>#if LED_HEARTBEAT<br>  pinMode(HB_LED, OUTPUT);<br>  digitalWrite(HB_LED, LOW);<br>#endif<br><br>  // Display initialisation<br>  mx.begin();<br>  mx.setShiftDataInCallback(scrollDataSource);<br>  mx.setShiftDataOutCallback(scrollDataSink);<br><br>  curMessage[0] = newMessage[0] = &#39;\0&#39;;<br><br>  // Connect to and initialise WiFi network<br>  PRINT(&quot;\nConnecting to &quot;, ssid);<br><br>  WiFi.begin(ssid, password);<br><br>  while (WiFi.status() != WL_CONNECTED)<br>  {<br>    PRINT(&quot;\n&quot;, err2Str(WiFi.status()));<br>    delay(500);<br>  }<br>  PRINTS(&quot;\nWiFi connected&quot;);<br><br>  // Start the server<br>  server.begin();<br>  PRINTS(&quot;\nServer started&quot;);<br><br>  // Set up first message as the IP address<br>  sprintf(curMessage, &quot;%03d:%03d:%03d:%03d&quot;, WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3]);<br>  PRINT(&quot;\nAssigned IP &quot;, curMessage);<br>}<br><br>void loop()<br>{<br>#if LED_HEARTBEAT<br>  static uint32_t timeLast = 0;<br><br>  if (millis() - timeLast &gt;= HB_LED_TIME)<br>  {<br>    digitalWrite(HB_LED, digitalRead(HB_LED) == LOW ? HIGH : LOW);<br>    timeLast = millis();<br>  }<br>#endif<br><br>  handleWiFi();<br>  scrollText();<br>}</pre><p>In the code, note the following things:<br>1. Enter your wifi credentials is this part of the code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/0*Lj3HllOQSgLdUEAF.png" /></figure><p>2. Alternatively switch the word “Parola” with these words — FC-16, ICSTATION, GENERIC<br>Because sometimes we donot know what kind of LED matrix we have, these are the four most commonly available types so the code will work fine with any of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*FiFeUA_At5yBVscl.png" /></figure><p>The snippet of code to be edited is given above.</p><p>Now as soon as you upload the code, the display will show an IP Address.<br>Note that IP address and type it in your browser</p><p>Make sure that if it shows an ip address of 192.168.043.057 //Or anything else<br>Just omit the zero’s in between the address while typing in the browser<br>i.e — 192.168.43.57</p><p>After typing you will see a static web page where you can type your text and send it to your display system</p><p>The NodeMCU can now be disconnected from laptop and given an external power source and be installed and wirelessly controlled as long as the person who wishes to control it is connected to the same wifi credential given to the NodeMCU.</p><p>Here is the demo -<br><a href="https://www.youtube.com/watch?v=9rM8-ciWfMc">https://www.youtube.com/watch?v=9rM8-ciWfMc</a></p><p>Thankyou!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bcf130af687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I AM SENTIENT]]></title>
            <link>https://medium.com/@Bluehell/i-am-sentient-db632ede5829?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/db632ede5829</guid>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[brain]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 04:26:13 GMT</pubDate>
            <atom:updated>2023-04-11T15:21:17.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Are we truly Sentient?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*Vms9MfXJgI7Q_mSqbb8svQ.jpeg" /></figure><p>When I think about who I am, there’s one aspect above all that cannot be ignored: I am a sentient being.</p><p>I experience my existence, I feel like I’m here, looking out on the world through these eyes, perceiving this technicolor show from my own center stage. I’ll address this feeling as consciousness or as one might say — awareness.</p><p>We have searched for centuries, for a detailed definition of consciousness, but it’s easy enough to pin down what we are talking about, with the help of a simple comparison: when you are awake you have consciousness, when you are in deep sleep, you don’t.</p><p>This distinction gives us an inroad for a simple question: what is the difference between brain activity during those two states?</p><p>One way to measure that is with electroencephalography (EEG), which captures the summary of billions of neurons firing by picking up weak electrical signals outside of the skull. It’s bit of a crude technique; sometimes it is compared to trying to understand baseball by holding a microphone on the outside of a baseball stadium. <br>Nonetheless, EEG can offer immediate insights into the differences between the waking &amp; sleeping states.</p><p>When you are awake you brain waves reveal that your billions of neurons are involved in complex exchanges with one another: think of this as thousands of individuals having a conversation altogether in a packed dance club.</p><p>When you go to sleep, your body seems to shut down. So, it’s a natural assumption that the neuronal dance club quiets down. But in 1953 it was discovered that such an assumption is incorrect: the brain is just as active at night as it is during the day. During sleep, the neurons just coordinate with each other differently, entering a more synchronized rhythmic state. Imagine the packed club singing the national anthem in sync with each other.</p><p>As you can imagine, the complexity of the discussion in a club is much richer when thousands of conversations are playing out. In contrast, when the crowd is entering a synchronized state while singing the national anthem, it’s a less intellectual time.</p><p>So who you are at any given moment depends on the detailed rhythms of your neuronal firings. During the day, the conscious you emerges from that integrated neural complexity. At night, when the interactions of your neurons changes just a bit, you disappear. <br>Your loved ones have to wait until the next morning until your neurons let the synchronization die and work themselves back into the complex rhythm. <br>Only then do you return.</p><p>So who you are depends on what your neurons are up to, moment by moment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db632ede5829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Existentialism of Essentialism?]]></title>
            <link>https://medium.com/@Bluehell/existentialism-of-essentialism-1ae38fa67514?source=rss-4c704295382a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae38fa67514</guid>
            <category><![CDATA[meaning-of-life]]></category>
            <category><![CDATA[altruism]]></category>
            <category><![CDATA[purpose]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[existentialism]]></category>
            <dc:creator><![CDATA[Ajay Rajan]]></dc:creator>
            <pubDate>Sun, 09 Feb 2020 19:12:44 GMT</pubDate>
            <atom:updated>2023-04-11T15:19:34.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Existentialism or Essentialism?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-o93SkxBuCMNytRjsw4sGQ.jpeg" /></figure><p>Do you ever go on a run and wonder where the hell you are going?<br>Not just that, but why are you running?<br>Where are you coming from?<br>Who exactly is running?</p><p>Maybe it’s a dumb question or maybe it’s dumb not to ask.<br> <br>It will hit me at random times at random places. In the cab or when I’m walking to the supermarket. <br>Who exactly is walking to the supermarket?</p><p>I cannot really comprehend the vastness that lies behind these thoughts, but my conclusion always ends up being: The world doesn’t make a whole lot of sense.</p><h4><strong><em>Things are stranger than you think they are.</em></strong></h4><p>Let’s start with the fact that we are living on a floating rock and are literally only alive thanks to a fireball in the sky. <br>Trillions of micro-organisms that you cannot see, live in and on your body.</p><p>You are able to understand what I’m saying thanks to your brain’s ability to decipher words which now come to you in form of sound waves which I made with my mouth &amp; the opening in the lower part of my face that consumes food and water.</p><p>You are able to understand English because of a group of violent people who were good at boats and a very polite lady that liked to wear a piece of metal on her head from time to time.</p><p>I could do this all day.</p><p>This doesn’t get better in the picture of present day life. There are these gigantic global problems that I keep hearing about and feel utterly powerless to improve. <br>Climate change, nuclear arms, mass surveillance, wealth inequality and often ways in which we treat each other.<br> <br>Mainstream media feels like it’s actively making everything worse by running the same 5 sensationalised topics on loop.</p><p>Not to mention I myself come from a capitalized society that I fear is in itself inherently unsustainable, but I’m also actively participating in playing the game. <br>I have my own ambitions to climb the proverbial social ladder, and live a better life (whatever that means!). <br>Most of us know at some level money doesn’t buy happiness, right? <br>How many times have you heard that one? <br>Yet it plays such an important role in most of our decisions.</p><p>Things are now evolving at lightning speed, it kind of feels like my parents grew up in a different world, and extrapolating on that, my grandparents grew up in an alternate universe.<br> <br>I sense massive discrepancies in the worlds that exist on-and-off-line, It’s hard to know what to believe anymore. It’s even harder to know which direction is the right one. <br>Then there is me, or as I should say, the concept that I have of me. <br>I don’t really know why I am here or what I am supposed to be doing, my best answers sometimes feel like they fall into pieces in the context of everything else. <br>I should be in tears over the miracles of life or maybe horrified by the atrocities of war and famine. But really I am just worrying about how dumb I sounded in front of someone who I talked to maybe a day, a month or a couple of years ago. <br>When I say “I” what I mean is the name that was bestowed upon me(Ajay!), which is nothing but an idea that I &amp; people who know me have built about who I am.</p><p>I get hung up or offended when someone threatens my values or anything I identify with, which is really silly if you take a big step back. <br>I mean people are going to say whatever they want, whenever they want &amp; there is nothing I can do about it, and yet my world is built around this concept that I have of who I am and what I believe I can and cannot do.</p><p>Both my socio-economic background and things that occurred early in my life shaped the particular path I am on. <br>And it goes deeper in many ways, I am run by my own biology, a software has been encoded into me to seek food, safety and sex. It’s funny.</p><p>Everything seems really important at the moment but I am gonna be a pile of dust a hundred years from now.</p><p>If you hit pause, you can see it’s all just a giant circus. Suddenly science fiction doesn’t sound so unbelievable. <br>Humanity is just making it up as we go. It can feel like life is meaningless and random. The most frequent question that I ask myself is: <br>“What’s the fucking point?” <br>I mean I am doing my best here to better myself and be a productive citizen and contribute something of value, and I wonder sometimes if it’s worth it?</p><p>Maybe I am nowhere near as valiant and virtuous I’d like to think, and a lot more self interested than I’d like to admit!<br> <br>If you can’t relate please go on with your lives as you did before, don’t let me complicate things further for you. <br>The best way to avoid an existential crisis is not to ask too many questions. But, it’s a lot easier said than done. So, if you can relate to the things I am describing here, then —<strong><em> Welcome to the club</em></strong>!</p><h4><strong><em>A very brief look at existentialism</em></strong></h4><p>Fortunately or unfortunately, I am far from the first person to ask these questions. <br>Turns out, this is what philosophers have been doing for a very long time, and they all seem to come up with different answers. <br>Context is really important and there are literally a million different ways in which you can interpret the words of these philosophers wrote. <br>So I am just sharing where I am at right now, but my views are constantly evolving and changing whether I like it or not. <br>People find meaning in a lot of different ways, for example, religion, or maybe service to the nation, or maybe your family. <br>Probably you already knew that so I’ll be taking this in a little different direction. I want to focus on what a couple of french guys — <em>Jean Paul Sartre </em>and <em>Albert Camus</em> had to say on this topic which we will now be calling existentialism, but before we talk about existentialism we first have to talk about essentialism.</p><p>The core concept of essentialism is that every entity has a set of attributes that are necessary to its identity and function. <br>According to this sentence, you have an inherent purpose and in many ways it has been decided for you, and for thousands of years the established thinking in the west was just the way it was. <br>But then an awful lot of things happened throughout history, like WW2 for example, and people like <em>Sartre </em>began questioning a lot of established ideas, he spoke about this idea that he called — <strong><em>The absurdity of the world,</em></strong> which is something that you can see only if you are pulled out of the context of everything and can witness, even for a brief moment, just how weird everything is. <br>We may define absurdity as the search for answers in an answer-less world, so naturally the question comes back to — What if there are no answers?<br> <br>I am cherry picking here, but one of Sartre’s big claims, and the point I’m kind of building up to is that <strong><em>being precedes essence, </em></strong>in other words — You exist first and then you figure out what your purpose is.<br> <br>This is a completely different way of looking at the world than essentialism because it acknowledges that we are sort of making up the rules as we go.</p><p>Let’s just assume that this is the case, being precedes essence, to my mind you have several options — You can believe in higher power as most people do, in a religious or a non-religious sense. <br>Or you can accept that life is absurd and just focus on the present moment. The second option is what <em>Camus, </em>the other French guy, believed. <br>He argued that thinking anything else would be running away from reality. Now alternatively, you can create the meaning in your life, you know you can decide what you want to be about. The amazing thing about is that it’s up to you, The angst you feel while thinking about your life and the meaning it should have, well, <em>Sartre </em>had a theory for that as well. He called it — “Angoisse” or Anguish. <br>He believes that it comes from the fact that you are actually incredibly free &amp; no matter your situation you have an enormous amount of options at your disposal, and to be that free actually is an overwhelming idea. <br>It is a lot of responsibility. His thinking was that basically you are ignoring your own freedom, and money does not equal freedom because money can possess you or tie you down, arguably more than anything else.</p><h4><strong><em>It doesn’t matter what you believe</em></strong></h4><p>I guess what’s left here are my own personal conclusions on all of this. Other than the fact that my horoscope might be a black hole and my personality type is that of an Advocate, I’m doing fine, I don’t really believe there is a right or wrong answer to all of this, whether you believe in the divine connectedness of all things or on the absolute meaninglessness of it all.</p><p>All of us have been very self involved and it always has been that way.</p><p>At the end of the day I think any kind of belief system or lack thereof, could be used for doing or confronting the hard things in life. <br>And ultimately, I don’t think that says anything about the belief system in and of itself, and everything about the individual.</p><p>For me it doesn’t matter what you believe. <br>I judge people based on action and I really like it when people take responsibility for themselves and create the world they want to live in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae38fa67514" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>