<?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 Rohit Nimkar on Medium]]></title>
        <description><![CDATA[Stories by Rohit Nimkar on Medium]]></description>
        <link>https://medium.com/@csrohit?source=rss-28caeacdb058------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CP3JpOatE5ckWZ0jn_kQgQ.jpeg</url>
            <title>Stories by Rohit Nimkar on Medium</title>
            <link>https://medium.com/@csrohit?source=rss-28caeacdb058------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:28:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@csrohit/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[Output Compare Mode on STM32F4 Timers]]></title>
            <link>https://medium.com/@csrohit/output-compare-mode-on-stm32f4-timers-6d961162bbe2?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d961162bbe2</guid>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[timer]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[baremetal]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Tue, 13 May 2025 12:06:08 GMT</pubDate>
            <atom:updated>2025-05-15T02:26:27.849Z</atom:updated>
            <content:encoded><![CDATA[<h4>⏱️ STM32 Timer Essentials</h4><h4>A practical, bare-metal guide to configuring output compare channels on STM32F4 microcontrollers.</h4><p>Timers are one of those peripherals that you just can’t ignore when working with microcontrollers. They’re super versatile — whether you want to blink LEDs, generate PWM signals, or measure time intervals, timers have your back.</p><p>In this post, I’ll walk you through how to set up Timer3 on the STM32F4 to use all four output compare channels. We’ll do this the bare-metal way — no HAL or fancy libraries — just straight-up register programming.</p><p>If you’re new to STM32 timers or want a refresher on the basics (like using timers to generate delays), I recommend checking out my previous article:</p><p><a href="https://medium.com/@csrohit/getting-started-with-general-purpose-timer-stm32f401-6782adb95dde">Getting started with General Purpose Timer STM32F401 ⏱</a></p><p>That post covers the fundamentals of how timers work, setting up a simple delay, and writing your first timer interrupt handler. The article you’re reading now is a natural continuation, diving deeper into output compare mode and multi-channel timing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*ovaZTcJN4rJzjCedZ_9rtQ.png" /><figcaption>fig. Output Compare internal block</figcaption></figure><h3>Why Output Compare? ⏲️</h3><p>The Output Compare mode is neat. It lets your timer watch its counter and trigger events when it hits certain values. For example, you can toggle a pin, generate an interrupt, or even start a DMA transfer. With four channels on TIM3, you can handle multiple timed events simultaneously, perfect for multitasking in embedded systems.</p><h3>How Output Compare Mode Works (STM32 Perspective)</h3><p>Output Compare mode is one of the most fundamental timer features in STM32. Here’s what’s happening under the hood, as described in [<a href="https://www.st.com/resource/en/application_note/an4776-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf"><em>AN4776, section 1.3.3</em></a>]:</p><h4>The Core Idea</h4><ul><li>The timer’s counter (CNT) continuously counts up (or down, depending on configuration).</li><li>Each channel has its compare register (CCR1, CCR2, CCR3, CCR4).</li><li>When the counter value (CNT) matches the value in a CCRx register, an output compare event is generated for that channel.</li></ul><h4>What Happens on a Match?</h4><ul><li>The action taken on a match depends on the OCxM (Output Compare Mode) bits in the CCMRx register:</li><li>Toggle: The output pin toggles its logic state (high ↔ low).</li><li>Set/Reset: The output pin is set high or low.</li><li>PWM: The output pin generates a PWM waveform.</li><li>Generate an interrupt (if enabled in DIER)</li><li>Trigger a DMA request</li></ul><h4>Block Diagram Reference</h4><ul><li>Each timer channel is like a mini-state machine:</li><li>It monitors the timer counter.</li><li>When a match occurs, it performs the programmed action on the output pin (see Figure 2 in AN4776).</li></ul><h3>Getting started</h3><h4>What You’ll Need 🧰</h4><ul><li>Any STM32F4 board (I’m using an STM32F401, but this works on most STM32F4 MCUs)</li><li>Basic C skills and some familiarity with microcontroller registers</li><li>Your favorite IDE (STM32CubeIDE, Keil, or whatever you prefer)</li><li>LEDs hooked up to PA6, PA7, PB0 &amp; PB1 pins</li><li>An LED hooked up to PC13 (optional, but it makes things more fun!)</li></ul><h3>Setting Up Timer3</h3><h4><strong>1. Enable Clock</strong></h4><p>Before using GPIO pins or the timer itself, you must enable their clocks.</p><ul><li>GPIOAEN and GPIOBEN enable the clocks for GPIOA and GPIOB (for timer channel output pins).</li><li>TIM3EN enables the clock for TIM3 itself, making its registers accessible.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01141131801217e77c71dbb10935c231/href">https://medium.com/media/01141131801217e77c71dbb10935c231/href</a></iframe><h4>2. GPIO Configuration: MODER, AFR Registers</h4><p>Timer channels are mapped to specific pins (e.g., PA6, PA7, PB0, PB1). These must be set to “Alternate Function” mode so the timer peripheral can control them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5681d1d7b77e708a0b51b6d3bc1b7a0e/href">https://medium.com/media/5681d1d7b77e708a0b51b6d3bc1b7a0e/href</a></iframe><p>Each pin can serve multiple alternate functions. Here, we select AF02 for the relevant pins, which connect them to TIM3 output compare channels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a54b2a7293bbd07eff92eb6d59f6cc59/href">https://medium.com/media/a54b2a7293bbd07eff92eb6d59f6cc59/href</a></iframe><h4>3. Timer Time-Base Configuration: PSC, ARR Registers</h4><p>This sets up the time-base unit of the timer (see AN4776, Section 1.2.2).</p><ul><li>PSC (Prescaler): Divides the timer input clock. If your system clock is 16 MHz, setting PSC to 15999 gives you a 1 kHz timer clock (16MHz / (16,000–1) = 1,000 Hz).</li><li>ARR (Auto-Reload Register): Sets the period. With ARR = 999, the timer counts from 0 to 999, so you get an update event every 1s.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15ed3f8ee5b44c9d8e7c6a2e14e7c9c5/href">https://medium.com/media/15ed3f8ee5b44c9d8e7c6a2e14e7c9c5/href</a></iframe><h4>4. Interrupt Enable: DIER Register &amp; NVIC</h4><ul><li><strong>DIER (DMA/Interrupt Enable Register)</strong>: Setting the UIE bit enables the “update interrupt” (triggered when the timer overflows).</li><li><strong>NVIC</strong>: Enables the TIM3 interrupt in the Nested Vectored Interrupt Controller.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8b14976e176353bb5ff2c975c262fc7/href">https://medium.com/media/f8b14976e176353bb5ff2c975c262fc7/href</a></iframe><h4>5. Output Compare Channel Configuration: CCRx, CCMRx, CCER</h4><p>Each CCR (Capture/Compare Register) sets the value at which the corresponding channel will trigger its output compare event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd59143511f4e7457d695353eb120320/href">https://medium.com/media/dd59143511f4e7457d695353eb120320/href</a></iframe><p><strong>CCMRx (Capture/Compare Mode Register):</strong></p><ul><li>OCxM bits select the output mode (toggle, set, reset, PWM, etc.).</li><li>Toggle mode means the output pin will flip its state each time the timer counter matches the CCRx value.</li><li>OCxPE enables the preload feature, so changes to CCRx take effect at the next update event (<a href="https://www.st.com/resource/en/application_note/an4776-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf">see AN4776, section 1.4.2</a>).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2007b0c1e401ee7a6cd62f94a5567797/href">https://medium.com/media/2007b0c1e401ee7a6cd62f94a5567797/href</a></iframe><h4>6. Enable Capture-Compare channels &amp; Start timer</h4><ul><li><strong>CCER (Capture/Compare Enable Register)</strong>: Each CCxE bit enables the corresponding channel’s output to the pin.</li><li><strong>CR1 (Control Register 1)</strong>: Setting the CEN bit starts the timer counter.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14272537471108ac0e2d6ec949860e11/href">https://medium.com/media/14272537471108ac0e2d6ec949860e11/href</a></iframe><h4>Step 2: Timer Interrupt Handler</h4><p>We’ll use the timer’s update interrupt to create a simple timing flag that we can use for delays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/155ba1911fff752c44037e92d296bc20/href">https://medium.com/media/155ba1911fff752c44037e92d296bc20/href</a></iframe><h4>Step 3: A Simple Delay Function</h4><p>We can build a millisecond delay function using the flag set by the interrupt. It uses the __WFI() instruction to put the CPU into a low-power state while waiting, which is more power-efficient than busy-waiting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba30382014d4e9b1926f45110517bc37/href">https://medium.com/media/ba30382014d4e9b1926f45110517bc37/href</a></iframe><h4>Step 4: Stitch everything together</h4><p>Finally, let’s toggle an LED connected to PC13 every second to see our timer in action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41a47da4bd997c6d2597c33fcf1e7073/href">https://medium.com/media/41a47da4bd997c6d2597c33fcf1e7073/href</a></iframe><h3>👀 What You’ll See</h3><ul><li>The LEDs connected to PA6, PA7, PB0, and PB1 will toggle at different intervals, corresponding to the output compare values set for each channel. If you have an oscilloscope or logic analyzer, you can observe these pins switching states precisely as the timer counter matches their compare registers.</li><li>The LED connected to PC13 will blink every second, driven by the timer’s update interrupt and the delay function implemented in software.</li><li>This setup demonstrates how multiple timer channels can independently control different GPIO pins simultaneously, showcasing the power of STM32 timers for multitasking and precise timing.</li></ul><p>For a complete working example including source code, project files, and build instructions, you can visit the GitHub repository here:</p><p><a href="https://github.com/csrohit/stm32f4-baremetal/tree/main/7-out-compare">stm32f4-baremetal/7-out-compare at main · csrohit/stm32f4-baremetal</a></p><h4>📖 Further Reading</h4><ol><li><a href="https://www.st.com/resource/en/application_note/an4776-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf">[AN4776] General-purpose timer cookbook for STM32 microcontrollers</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d961162bbe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with General Purpose Timer STM32F401 ⏱]]></title>
            <link>https://medium.com/@csrohit/getting-started-with-general-purpose-timer-stm32f401-6782adb95dde?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/6782adb95dde</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Mon, 12 May 2025 09:45:40 GMT</pubDate>
            <atom:updated>2025-05-12T17:18:50.514Z</atom:updated>
            <content:encoded><![CDATA[<h4>STM32 Timer Essentials</h4><h4>A baremetal approach to programming the General Purpose timer in STM32F401 micro-controller</h4><p>The general-purpose timers consist of a 16-bit or 32-bit auto-reload counter driven by a programmable pre-scaler.</p><p>Their use cosists of but not limited to</p><ol><li>⏳ Generating Delay</li><li>📏 Measuring pulse length of input signals (Input Capture)</li><li>∿ Generating Output Waveforms (Output Compare &amp; PWM)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBZAcaI79e0W2DDN-6sxoQ.png" /><figcaption>Image from <a href="https://wiki.st.com/stm32mcu/wiki/Getting_started_with_TIM">ST Microelectronics</a></figcaption></figure><h3>How does the timer block work?</h3><p>At its core, the timer consists of several key components that work together to generate accurate time delays and trigger interrupts:</p><ul><li><strong>Clock Source</strong>: The timer receives its clock from the APB bus, derived from the system clock.</li><li><strong>Prescaler (PSC)</strong>: This block divides the incoming clock frequency, allowing the timer to count at a slower, configurable rate.</li><li><strong>Counter (CNT)</strong>: The heart of the timer, it increments on each tick of the prescaled clock.</li><li><strong>Auto-Reload Register (ARR)</strong>: Defines the timer period by setting the maximum count value. When the counter reaches this value, it resets and triggers an update event.</li><li><strong>Status Register (UIF)</strong>: The Update Interrupt Flag signals when the counter hits the ARR value, indicating a timer overflow.</li><li><strong>Interrupt/DMA Request</strong>: Upon overflow, the timer can notify the CPU via interrupts or initiate DMA transfers.</li><li><strong>Control Registers</strong>: These configure timer modes, enable counting, and manage interrupts.</li></ul><figure><img alt="Timer block diagram" src="https://cdn-images-1.medium.com/max/573/1*33r-lLUlTRBEdY-1qjqVxg.png" /><figcaption>fig. Block Diagram of General Purpose Timer</figcaption></figure><p>A timer in STM32 microcontrollers operates by first receiving a clock signal from the APB bus. This clock is divided down by the Prescaler (PSC) to achieve the desired timer frequency. Once the timer is enabled by setting the CEN (counter enable) bit, the timer’s counter begins counting from zero up to the value specified in the Auto-Reload Register (ARR).</p><p>When the counter reaches the ARR value, it generates an update event, which sets the Update Interrupt Flag (UIF) in the status register. If timer interrupts are enabled, this event will trigger an interrupt, allowing the CPU to execute a specific handler function. After overflow, the counter resets to zero and the counting cycle repeats, enabling precise periodic event generation or timekeeping in embedded applications.</p><h3>Generating Delay using Timer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*ZopdTlphzlpzkfh-VZmGPA.png" /><figcaption>Fig. Timer setup for Delay</figcaption></figure><h4>Initialize Timer</h4><p>The provided code initializes TIM1 to generate a 1 ms interrupt using a 16 MHz system clock. Here’s how it works:</p><ol><li><strong>Clock Activation</strong>: The timer’s peripheral clock is enabled via RCC-&gt;APB2ENR, ensuring TIM1 receives clock signals.</li><li><strong>Prescaler Tuning</strong>: By setting PSC = 15, the timer clock downscales APB2 clock from 16 MHz to 1 MHz (1 µs per tick).</li><li><strong>Period Configuration</strong>: The ARR register is configured to set the timer period. As the timer counts from 0 to ARR, in order to set the period of 1ms, the timer should count 1000 steps at the rate of 1µs/step. Thetimer starts counting from 0 hence theARR is set to 999 (1000 — 1), creating a 1 ms period (1,000 ticks × 1 µs).</li><li>Interrupt Setup: Enabling the update interrupt (UIE) and NVIC ensures the CPU triggers an ISR on Timer Update Event.</li><li>Timer Start: The counter begins incrementing with CR1 |= TIM_CR1_CEN.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbb7420cbf75785fc17a8f3136af8276/href">https://medium.com/media/cbb7420cbf75785fc17a8f3136af8276/href</a></iframe><h4>Define Interrupt handler</h4><p>The TIM1_UP_TIM10_IRQHandler() function is an interrupt service routine (ISR) used to handle timer overflow events for TIM1. When the timer reaches its auto-reload value, it sets an update interrupt flag (UIF) in the status register. The ISR first checks if this flag is set, confirming the overflow event. It then clears the UIF flag to acknowledge and reset the interrupt, ensuring the handler is not repeatedly triggered for the same event. <br>After clearing the flag, the ISR sets a global variable (typically declared as volatile) to signal to the main program that the timer period has elapsed. This mechanism allows the main application to respond to precise timing events without constantly polling the timer, making the system more efficient and responsive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3d4d9af3f694841f5c1cf4f48719e7/href">https://medium.com/media/3f3d4d9af3f694841f5c1cf4f48719e7/href</a></iframe><h4>Define delay() function</h4><p>The delay_timer() function provides a blocking delay in milliseconds by working alongside the timer interrupt mechanism. It uses the __WFI() instruction to put the CPU into a low-power state while waiting, which is more power-efficient than busy-waiting. Once the flag is set by the ISR, the function clears it and continues to the next iteration until the total delay time is reached.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b61fe378e73ae017745b0b4654a34c7/href">https://medium.com/media/8b61fe378e73ae017745b0b4654a34c7/href</a></iframe><h4>Driver code</h4><p>The main() function Initialises the timer and cofigures C13 as digital output. It toggles the C13 after 1000ms delay generated using the timer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95d465d5889bde4f807b97a8561d7093/href">https://medium.com/media/95d465d5889bde4f807b97a8561d7093/href</a></iframe><h3>Trying it yourself</h3><p>The source code for this blog is available on GitHub. Feel free to star, contribute, or create issues on the repo.</p><p><a href="https://github.com/csrohit/stm32f4-baremetal/tree/main/6-timer">stm32f4-baremetal/6-timer at main · csrohit/stm32f4-baremetal</a></p><h4>Output</h4><p>The LED🔴 connected to C13 should blink after every 100ms (1s).</p><h3>Additional Resources</h3><ol><li><a href="https://www.st.com/resource/en/application_note/an4013-introduction-to-timers-for-stm32-mcus-stmicroelectronics.pdf">https://www.st.com/resource/en/application_note/an4013-introduction-to-timers-for-stm32-mcus-stmicroelectronics.pdf</a></li><li><a href="https://www.st.com/resource/en/application_note/an4776-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf">https://www.st.com/resource/en/application_note/an4776-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf</a></li><li><a href="https://wiki.st.com/stm32mcu/wiki/Getting_started_with_TIM">https://wiki.st.com/stm32mcu/wiki/Getting_started_with_TIM</a></li><li><a href="https://github.com/csrohit/stm32f4-baremetal/tree/main/6-timer">https://github.com/csrohit/stm32f4-baremetal/tree/main/6-timer</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6782adb95dde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting multiple analog channels in STM32F1]]></title>
            <link>https://medium.com/@csrohit/converting-multiple-analog-channels-in-stm32f1-e05e10e45e48?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05e10e45e48</guid>
            <category><![CDATA[cad]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[arm]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 16:41:56 GMT</pubDate>
            <atom:updated>2024-01-16T10:09:49.445Z</atom:updated>
            <content:encoded><![CDATA[<h4>Programming Arm Cortex M3</h4><h4>A step-by-step explanation of SCAN mode working of ADC in STM32F103 (Blue Pill)</h4><p>In the <a href="https://medium.com/@csrohit/adc-configuration-in-continuous-mode-for-stm32-d7c9fd38a10c">previous post, </a>we’ve seen the operation of ADC in single-channel mode. We have converted the analog voltage into its digital equivalent continuously. What if we have to convert multiple analog channels, do we have to reinitialize the ADC for every new channel?</p><p>In this blog, we will perform the conversion of multiple analog channels and log the values over USART.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXZm75MzNqsvO-1QItUdDQ.png" /><figcaption>Fig: ADC, DMA interoperation</figcaption></figure><h4>ADC operation</h4><p>If you haven’t been through the basics of ADC, please check out the following article. It explains the basic initiation and operation of ADC in single-channel mode.</p><p><a href="https://medium.com/@csrohit/adc-configuration-in-continuous-mode-for-stm32-d7c9fd38a10c">ADC configuration in continuous mode for STM32</a></p><p>To enable ADC to convert multiple channels, it has to be configured in Scan mode. This mode can be selected by setting the SCAN bit in the ADC_CR1 register. Once this bit is set, ADC scans all the channels selected in the ADC_SQRx registers and starts conversion one by one.</p><p>As ADC stores the result in <em>ADC_DR</em> register, the data is overwritten after every conversion. Hence we must save this result at the end of every conversion. DMA comes to our rescue in this situation and transfers the converted data to SRAM after each update of the<em>ADC_DR</em> register.</p><blockquote>Since converted regular channels value are stored in a unique data register, it is necessary to use DMA for conversion of more than one regular channel.</blockquote><blockquote>When using the Scan mode DMA bit must be set.</blockquote><blockquote>Only the end of conversion of a regular channel generates a DMA request, which allows the transfer of its converted data from the ADC_DR register to the destination location selected by the user.</blockquote><p>After every EOC event, ADC sends a request signal to the DMA controller. As soon as the DMA controller acknowledges the request, ADC releases the requests and starts a new conversion.</p><p>If the CONT bit is set in ADC_CR1 register, the conversion does not stop at the last selected group channel but continues again from the first selected group channel.</p><p>If the CONT bit is not set then ADC will enter into standby mode and ADON bit in the ADC_CR1 register is cleared by hardware. To restart the conversion we have the set the ADON bit from software and the conversion cycle repeats.</p><h4>ADC configuration</h4><p>Configure PA1 &amp; PA2 in analog input mode.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a742971dbec411db35c38d4d28e6c4c2/href">https://medium.com/media/a742971dbec411db35c38d4d28e6c4c2/href</a></iframe><p>Set the number of channels to be converted in theADC_SQR1 register. The value to be set is nChannels — 1 as value 0 (default)corresponds to 1 channel conversion. Here we write 1 for the nChannels=2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5145573f19ba5d83dd09de7dda8ebfd8/href">https://medium.com/media/5145573f19ba5d83dd09de7dda8ebfd8/href</a></iframe><p>Specify the order of channels to be converted, here we are specifying that the first channel of the sequence is channel1 &amp; second channel in the sequence is channel2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bcd14231471ac81361d4976454bd0c9/href">https://medium.com/media/5bcd14231471ac81361d4976454bd0c9/href</a></iframe><p>Set the sampling time for both channels, the following lines configure the sampling time to 28.5 cycles (refer to datasheet).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20ac4d164b80641ad09dafc53b29ad0a/href">https://medium.com/media/20ac4d164b80641ad09dafc53b29ad0a/href</a></iframe><p>The most important thing to configure is to enable scan mode &amp; DMA requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c46cd391643011605ae3a9f9f09a123/href">https://medium.com/media/2c46cd391643011605ae3a9f9f09a123/href</a></iframe><h4>DMA Operation</h4><p>The Channel1 of DMA1 is associated with ADC1, hence we have to configure the channel to service requests from ADC1.</p><blockquote>DMA channel must be enabled before enabling DMA, so not to miss any DMA requests issues by the ADC</blockquote><p>After the arrival of the request signal from the ADC, the DMA controller accesses the ADC_DR register and copies the content (16 bits) to the memory pointer by the CMAR register. The controller then acknowledgement is sent to the ADC. After the request is de-asserted (released) by ADC, the DMA controller then releases the acknowledgment. If there are more requests then the ADC can initiate the next transaction.</p><p>In summary, each DMA transfer consists of three operations:</p><ul><li>The loading of data from the peripheral data register or a location in memory is addressed through an internal current peripheral/memory address register. The start address used for the first transfer is the base peripheral/memory address programmed in the DMA_CPARx or DMA_CMARx register</li><li>The storage of the data loaded to the peripheral data register or a location in memory is addressed through an internal current peripheral/memory address register. The start address used for the first transfer is the base peripheral/memory address programmed in the DMA_CPARx or DMA_CMARx register</li><li>The post-decrementing of the DMA_CNDTRx register, which contains the number of transactions that are still to be performed.</li></ul><h4>DMA Configuration</h4><p>Set the peripheral address for the DMA channel as the address of ADC_DR register. Set the memory address for the DMA channel as the address of the buffer adc_value. The total number of transactions is to be set in DMA_CNTDR register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ffffe193c28dfbf67b943cb27817ade/href">https://medium.com/media/3ffffe193c28dfbf67b943cb27817ade/href</a></iframe><p>Set the direction of data transfer i.e. the data is to be copied from peripheral to memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd7656c1bd47f583fef8ef3e4eb55a33/href">https://medium.com/media/fd7656c1bd47f583fef8ef3e4eb55a33/href</a></iframe><p>Set the size of data to be transferred from source to destination. As the converted value is 16 bits long, we configure the DMA to transfer 16 bits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ace6723a91e4ca4a35e6be1ada4ebed/href">https://medium.com/media/8ace6723a91e4ca4a35e6be1ada4ebed/href</a></iframe><p>Set the increment mode on memory and peripheral addresses. we have to increment the memory address after every transfer to copy the converted value to a new location every time. For every transfer the CMAR the register is incremented by MSIZE i.e. 16 bits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be3991f5162b3c68bf8c69a8e039dddb/href">https://medium.com/media/be3991f5162b3c68bf8c69a8e039dddb/href</a></iframe><p>To understand DMA in-depth, please head over to this article, which elaborates on the DMA operation in more detail.</p><p><a href="https://medium.com/@csrohit/working-with-usart-and-dma-in-stm32-arm-cortex-m3-6a0e8b3174f3">Working with USART and DMA in STM32 (ARM Cortex M3)</a></p><h4>Circuit Diagram</h4><p>Connect the components as shown in the circuit diagram. Flash the program using ST-Link or any other method of your liking. Shine a light on LDR or change the potentiometer value to observe the corresponding digital value on the USART console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbMp7ofO9Z-LU-AFbwh5hA.png" /><figcaption>Fig: Circuit Diagram for testing</figcaption></figure><h4>Building &amp; flashing on target</h4><p>The program is configured using Makefile and can be easily flashed on the target if you have the required dependencies installed on your system.</p><p>Please refer to the ReadMe file in the attached repository for instructions related to the installation of dependencies on your system</p><h4>Getting the source code</h4><p>The source code for this blog is available on GitHub. Feel free to star, contribute, or create issues on the repo.</p><p><a href="https://github.com/csrohit/stm32f1-baremetal/tree/main/adc/scan-regular">stm32f1-baremetal/adc/scan-regular at main · csrohit/stm32f1-baremetal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05e10e45e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Procedure Call Standard for Arm Architecture — Part 1]]></title>
            <link>https://medium.com/@csrohit/understanding-procedure-call-standard-for-arm-architecture-part-1-ff78031842c8?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff78031842c8</guid>
            <category><![CDATA[embedded-c-programming]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[stm32]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 11:48:17 GMT</pubDate>
            <atom:updated>2023-03-25T11:48:17.342Z</atom:updated>
            <content:encoded><![CDATA[<h4>Guide to ARM Cortex M</h4><h3>Understanding Procedure Call Standard for Arm Architecture — Part 1</h3><h4>Understanding how 64-bit parameters are passed to functions by AAPCS</h4><p>While writing embedded applications, I have never considered the order of function parameters, however, I have to consider it after learning about the Arm Architecture Procedure Call Standard (AAPCS). Thanks to <a href="https://www.linkedin.com/in/aozgurayik/">Özgür Ayık</a>, for his article on this topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_NbcNlcWbMf4G2YrBUh9w.png" /></figure><h3>AAPCS</h3><p>The specification defines how separately compiled and assembled subroutines can work together. The stack &amp; core registers are a vital part of this procedure call standard. The use of stack or core registers for passing values between subroutines is dependent on the fundamental data types.</p><h4>The Stack</h4><p>The stack is a contiguous area of memory that may be used for the storage of local variables and for passing additional arguments to subroutines when there are insufficient argument registers available.</p><p>The stack implementation is <em>full-descending</em>, with the current extent of the stack held in the register SP (r13). The rules for the maintenance of the stack are divided into two parts: a set of constraints that must be observed at all times, and an additional constraint that must be observed at a public interface.</p><p>Universally, the stack pointer should always be double-word aligned i.e. SP mod 4 == 0. At a public interface, the stack pointer should be double-word aligned i.e. SP mode 8 == 0.</p><h4>Core registers</h4><p>There are 16, 32-bit core (integer) registers visible to the ARM and Thumb instruction sets. These are labeled r0- r15 or R0-R15. Register names may appear in assembly language in upper or lower cases. In this specification upper case is used when the register has a fixed role in the procedure call standard. <em>Table 2, Core registers and AAPCS usage </em>summarize the uses of the core registers in this standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsrEyExLn2X1XcS1Q2-hWg.png" /><figcaption>fig: function/subroutine calls with different arguments</figcaption></figure><h3>Subroutine calls</h3><p>Both the ARM and Thumb instruction sets contain a primitive subroutine call instruction, BL, which performs a branch-with-link operation. All the function calls are translated to branch with link (BL) instructions in assembly.</p><h4>Parameter Passing</h4><p>The base standard provides for passing arguments in core registers (r0-r3) and on the stack. For subroutines that take a small number of parameters, only registers are used, greatly reducing the overhead of a call.</p><h4>Handling values larger than 32bits</h4><p>Fundamental types larger than 32 bits may be passed as parameters to, or returned as the result of, function calls. When these types are in core registers the following rules apply:</p><ul><li>A double-word-sized type is passed in two consecutive registers (e.g., r0 and r1, or r2 and r3). As the parameter requires double word alignment, NCRN is rounded off to the next even register.</li><li>A 128-bit containerized vector is passed in four consecutive registers. The content of the registers is as if the value had been loaded from memory with a single LDM instruction.</li></ul><blockquote>NCRN — Next Core Register Number, represents the next register in queue for operation</blockquote><h4>Order of parameters</h4><p>In the first example, the first parameter is 32-bit first parameter is passed in r0 and the 64-bit second parameter is passed in r2-r3, leaving r1 register unused. As the second parameter is double-word aligned the <strong><em>NCRN</em></strong> is rounded to the next even register i.e. r2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYNB9NlOV7EQmC4vNwZtGA.jpeg" /><figcaption>fig. calling second_func</figcaption></figure><p>In 2nd example, the 64-bit first parameter is passed through r0-r1 and the 32-bit second parameter is passed through r2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxzGdQPwX0imOUAqAgfE4g.jpeg" /><figcaption>fig. calling first_func</figcaption></figure><p>In the 3rd example, the 32-bit first &amp; 2nd parameters are passed in r0 &amp; r1 and the 64-bit third parameter is passed in r2-r3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y67o7xA8YyHJ_Hl21bwTJQ.jpeg" /><figcaption>fig. Calling fourth_func</figcaption></figure><p>In the last example, though the size of all arguments is the same as that of prev example, the last parameter is passed using the stack. This is caused by changing the order of parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cK8lDRCHGkNeBDG4Afu_wg.jpeg" /><figcaption>fig. calling third_func</figcaption></figure><h3>Conclusion</h3><p>We can conclude as follows:</p><ol><li>When passing 64-bit parameters to function, the registers and efficiently used if the said parameter is evenly indexed, i.e. 0,2.</li><li>If we pass equal to or less than 4 32-bit parameters then the function call is faster as stack is not involved.</li></ol><h3>References</h3><ol><li><a href="https://github.com/ARM-software/abi-aa/blob/2982a9f3b512a5bfdc9e3fea5d3b298f9165c36b/aapcs32/aapcs32.rst#the-stack">https://github.com/ARM-software/abi-aa/blob/2982a9f3b512a5bfdc9e3fea5d3b298f9165c36b/aapcs32/aapcs32.rst</a></li><li><a href="https://www.linkedin.com/posts/aozgurayik_software-architecture-arm-activity-7044081670257295360-WBdu?utm_source=share&amp;utm_medium=member_desktop">https://www.linkedin.com/posts/aozgurayik_software-architecture-arm-activity-7044081670257295360-WBdu</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff78031842c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ADC configuration in continuous mode for STM32]]></title>
            <link>https://medium.com/@csrohit/adc-configuration-in-continuous-mode-for-stm32-d7c9fd38a10c?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7c9fd38a10c</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[embedded-c-programming]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[arm-cortex-m-series]]></category>
            <category><![CDATA[stm32]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 08:46:54 GMT</pubDate>
            <atom:updated>2023-02-19T17:17:31.166Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stm32 Baremetal Embedded-C Programming</h4><h4>Interfacing ADC in ARM Cortex M3 controller in continuous mode</h4><p>In the STM32F103 board, we have a single Successive Approximation type Analog to Digital Converter with a resolution of 12 bits. It has 18 channels which allow us to measure analog voltage from 16 external and 2 internal sources.</p><p>The A/D conversion of all channels can be performed in continuous, discontinuous, scan, and single modes. The result can be stored in the data register in both the left and right alignments.</p><blockquote>The ADC input clock is generated by PCLK2 divided by a pre scalar and it must not exceed 14 MHz</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*pe-rkMyif-AkzqQSp5T7iA.png" /><figcaption>fig: Control flow diagram</figcaption></figure><h3>Functional Description</h3><p>The ADC can be switched on/off by setting the ADON bit in the CR2 register. When the ADON bit is set for the first time i.e. value changes from 0 to 1, the ADC wakes up from power-down mode. The conversion starts when the ADON bit is set for the second time after the ADC power-up time.</p><p>The temperature sensor is connected to channel ADCx_IN16 and the internal reference voltage VREFINT is connected to ADCx_IN17. These two internal channels can be selected and converted as injected or regular channels.</p><h3>Modes</h3><p>The ADC can be operated in any one of the following modes. In this article, we are going to discuss the continuous operation mode.</p><h4>Single Conversion Mode</h4><p>In single conversion mode, the ADC stops after performing only one conversion. The mode can be started by either the external trigger or by setting the ADON bit while the CONT bit is 0.</p><h4>Continuous Mode</h4><p>In continuous conversion mode, the ADC starts the next conversion as soon as it finishes one. This mode can be triggered by either the external trigger or by setting the ADON bit while the CONT bit is 1.</p><p>After each conversion:<br>Data is stored in the 16-bit ADC_DR register and the End of Conversion (EOC) flag is set. An interrupt is generated if the EOCIE bit is set.</p><h4>Scan Mode</h4><p>Scan mode is used to scan a group of analog channels. This mode can be triggered by setting the SCAN bit in the ADC_CR1 register. The temperature sensor is connected to channel ADCx_IN16 and the internal reference voltage VREFINT is connected to ADCx_IN17. These two internal channels can be selected and converted as injected or regular channels.</p><h4>Discontinuous Mode</h4><p>This mode is enabled by setting the DISCEN bit in the ADC_CR1 register. It can convert a short sequence of n conversions (n &lt;=8), a part of the sequence of conversions selected in the ADC_SQRx registers. The value of n is specified by writing to the DISCNUM[2:0] bits in the ADC_CR1 register.</p><h3>Calibration</h3><p>The ADC has a built-in self-calibration mode. Calibration significantly reduces accuracy errors due to internal capacitor bank variations. During calibration, an error correction code (digital word) is calculated for each capacitor, and during all subsequent conversions, the error contribution of each capacitor is removed using this code.</p><p>Calibration is started by setting the CAL bit in the ADC_CR2 register. Once calibration is over, the CAL bit is reset by the hardware and normal conversion can be performed. It is recommended to calibrate the ADC once at power-on. The calibration codes are stored in the ADC_DR as soon as the calibration phase ends.</p><blockquote>It is recommended to perform a calibration after each power-up.</blockquote><blockquote>Before starting calibration, the ADC must have been in a power-on state (ADON bit = ‘1’) for at least two ADC clock cycles.</blockquote><h3>Data Alignment</h3><p>ALIGN bit in the ADC_CR2 register selects the alignment of data stored after conversion. Data can be left or right-aligned as shown in fig</p><figure><img alt="left data alignment" src="https://cdn-images-1.medium.com/max/1024/1*fMJKD4PjihC1ojS75DrHNA.png" /><figcaption>fig: left alignment</figcaption></figure><figure><img alt="right data alignment" src="https://cdn-images-1.medium.com/max/1024/1*JygfYRItQiM4fZZ6-RfMaQ.png" /><figcaption>fig: right-alignment</figcaption></figure><h3>Programmable Sample time</h3><p>ADC samples the input voltage for a number of ADC_CLK cycles which can be modified using the SMP[2:0] bits in the ADC_SMPR1 and ADC_SMPR2 registers. Each channel can be sampled with a different sample time.</p><p>The total conversion time is calculated as follows: <br><strong><em>Tconv = Sampling time + 12.5 cycles</em></strong></p><p>Example:<br><em> </em><strong><em>With an ADCCLK = 14 MHz and a sampling time of 1.5 cycles: Tconv = 1.5 + 12.5 = 14 cycles = 1 μs</em></strong></p><h3>Program</h3><p>The program initialization the peripherals and then continuously writes the analog reading on the serial console. The clock configuration and the ADC configuration are explained in detail however the USART functions are invoked from the library, explained in the following article</p><p><a href="https://medium.com/@csrohit/working-with-usart-and-dma-in-stm32-arm-cortex-m3-6a0e8b3174f3">Working with USART and DMA in STM32 (ARM Cortex M3)</a></p><h4>Clock initialization</h4><p>By default, the controller is using the internal RC oscillator operating at 8MHz as the primary clock. We will be configuring it to use the external resonator as the clock source operating at 72MHz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3f91d011473e6612e5fbbf2eeb9531f/href">https://medium.com/media/a3f91d011473e6612e5fbbf2eeb9531f/href</a></iframe><p>To dive deep into the inner working of the clock circuit and its configuration, head over to the following article:</p><p><a href="https://medium.com/@csrohit/clock-configuration-in-stm32-6a058da220e0">Clock Configuration in STM32</a></p><h4>ADC Config &amp; Initialization</h4><p>As the ADC clock cannot exceed 14MHz, we will select the pre-scalar value accordingly i.e. 6. ADC clock will have a frequency of 72Mhz/6 = 12MHz . The clock sources of ADC and PORTA are enabled afterward.</p><p>Pin PA0 where the analog sensor is connected is reset and configured in analog input mode.</p><p>For better accuracy, the sampling time is set as 28.5 cycles as described in the above section. The ADC is woken from the power down state while setting the mode as continuous and right data alignment. The ADC will keep reading the value and updating it in the ADC_DR register in right-aligned mode.</p><p>The conversions are started after the completion of recalibration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8899abce955d907509851713cfd3c45c/href">https://medium.com/media/8899abce955d907509851713cfd3c45c/href</a></iframe><h4>Main function</h4><p>As the ADC is configured in continuous mode, the value read from the ADC_DR register is printed on the serial console at every 500ms interval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/315170ef976bb0287be7758e3ab29601/href">https://medium.com/media/315170ef976bb0287be7758e3ab29601/href</a></iframe><h3>Building &amp; Flashing on target</h3><p>This project is configured using Makefile and does not use any external libraries. The entire project is available in the following repository along with all the instructions for building &amp; flashing.</p><p><a href="https://github.com/csrohit/stm32-adc/tree/main/continuous">stm32-adc/continuous at main · csrohit/stm32-adc</a></p><h3>References</h3><ol><li><a href="https://www.st.com/resource/en/reference_manual/cd00171190-stm32f101xx-stm32f102xx-stm32f103xx-stm32f105xx-and-stm32f107xx-advanced-arm-based-32-bit-mcus-stmicroelectronics.pdf">STM32F103 reference manual</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7c9fd38a10c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clock Configuration in STM32]]></title>
            <link>https://medium.com/@csrohit/clock-configuration-in-stm32-6a058da220e0?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a058da220e0</guid>
            <category><![CDATA[arm-cortex-m-series]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[baremetal]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 17:50:10 GMT</pubDate>
            <atom:updated>2023-01-09T17:50:10.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>STM32 Baremetal EmbeddedC Programming</h4><h4>An in-depth guide to using the STM32 Arm Cortex M3 controller at its maximum speed</h4><p>By default, the clock on the STM32F1 series of micro-controllers is configured at speed of 8MHz. This is enough for many applications; however, you might want to run the controller at a higher speed to achieve your goals.</p><p>In this article, I will be explaining in detail the Clock configuration procedure for the STM32F103 microcontroller. This process is mostly the same for the majority of the STM32 micro-controllers and can be made to work with minor adjustments according to the clock circuitry.</p><h3>Clocks</h3><p>For the STM32F103 we have 3 different clock sources to drive the system clock (SYSCLK):</p><ol><li>HSI Oscillator clock</li><li>HSE Oscillator clock</li><li>PLL Clock</li></ol><figure><img alt="Clock Configuration in STM32F103" src="https://cdn-images-1.medium.com/max/832/1*fjptU9SAb-H15E-Wl9UBBg.png" /><figcaption>Fig 1: Clock configuration flow diagram</figcaption></figure><p>The device also has secondary clocks to drive the built-in RTC, but it is out of scope for this article. We will be focusing on HSE to get the max possible clock speed for SYSCLK.</p><h4>HSI Oscillator Clock</h4><p>The HSI clock signal is generated from an internal 8 MHz RC Oscillator and can be used directly as a system clock or divided by 2 to be used as PLL input.</p><p>The HSI RC oscillator has the advantage of providing a clock source at a low cost (no external components). It also has a faster startup time than the HSE crystal oscillator however, even with calibration the frequency is less accurate than an external crystal oscillator or ceramic resonator.</p><blockquote>When HSI is used as a clock source, the maximum system clock frequency that can be achieved is 36MHz.</blockquote><h4>HSE Oscillator Clock</h4><p>The high-speed external clock signal can be generated from two sources i.e. a ceramic oscillator or an external clock. For the scope of this article, we will look at the HSE external ceramic oscillator clock.</p><p>The 4 to 16 MHz external oscillator has the advantage of producing a very accurate rate on the main clock. The associated hardware configuration is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*b5IS2fZOCqNQB3ROgJkUFA.png" /><figcaption>Fig 2: HSE hardware connections</figcaption></figure><p>The HSERDY flag in the Clock control register (RCC_CR) indicates if the high-speed external oscillator is stable or not. At startup, the clock is not released until this bit is set by the hardware. An interrupt can be generated if enabled in the Clock interrupt register (RCC_CIR).</p><p>The HSE Crystal can be switched on and off using the HSEON bit in the Clock control register (RCC_CR).</p><h4>PLL Clock</h4><p>The internal PLL can be used to multiply the HSI RC output or HSE crystal output clock frequency. Refer to Figure 8 and the Clock control register (RCC_CR).</p><p>The PLL configuration (selection of HSI oscillator divided by 2 or HSE oscillator for PLL input clock, and multiplication factor) must be done before enabling the PLL. Once the PLL is enabled, these parameters cannot be changed.</p><p>An interrupt can be generated when the PLL is ready if enabled in the Clock interrupt register (RCC_CIR).</p><h3>Application Code</h3><p>The clock configuration code is explained as follows</p><h4>Set Flash Latency</h4><p>The FLASH_ACR register is used to enable/disable prefetch and half-cycle access, and to control the Flash memory access time according to the CPU frequency. The tables below provide the bit map and bit descriptions for this register.</p><p>These bits represent the ratio of the SYSCLK (system clock) period to the Flash access time.<br> 000 Zero wait state, if 0 &lt; SYSCLK 24 MHz<br> 001 One wait state, if 24 MHz &lt; SYSCLK  48 MHz<br> 010 Two wait states, if 48 MHz &lt; SYSCLK  72 MHz<br>As we are configuring our controller to run at 72MHz, setting 2 wait states as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bd4c2f1fb89b1fb67f843ce4786d466/href">https://medium.com/media/1bd4c2f1fb89b1fb67f843ce4786d466/href</a></iframe><h4>APB divisor and HSE divisor</h4><p>In the first line below snippet, we are setting the APB clock to be obtained after dividing the HCLK by 2. In the next line we are setting the division factor of the HSE clock to 0 i.e. HSE clock is not to be divided before applying to PLL.</p><blockquote>Maximum allowable clock speed on APB1 peripherals is 36MHz</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d94096b1a3095c16a2f2fab699ec700f/href">https://medium.com/media/d94096b1a3095c16a2f2fab699ec700f/href</a></iframe><h4>Turn on HSE</h4><p>After configuring the division factor we switch on the HSE oscillator and wait for it to reach a stable state. The stable (ready) state is indicated by HSERDY bit. This bit needs 6 cycles of the HSE oscillator clock to fall down after the HSEON reset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0b4d8527aa2a856028de599660a9d4b/href">https://medium.com/media/a0b4d8527aa2a856028de599660a9d4b/href</a></iframe><h4>PLL configuration</h4><p>The source clock for the PLL is configured using PLLSRC bit in the RRCC_CFGR register. Setting this bit configures HSE as the source of the PLL.</p><p>The PLL multiplication factor can be configured by modifying the PLLMULL bits in the RCCC_CFGR register. Setting these bits to PLLMULL9 multiplies the HSE clock by a factor of 9.</p><p>After the configuration is done, the PLL is turned on by setting the PLLON bit in RCC_CR register. The ready state is indicated by PLLRDY bit in the same register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a914c60d1c202d7da3158d19796688/href">https://medium.com/media/f9a914c60d1c202d7da3158d19796688/href</a></iframe><h4>Core clock source selection</h4><p>After the PLL is ready, it is now safe to set it as the main source of the clock signal for the core. It is done by modifying the RCC_CFGR_SWS bits in the RCC_CFGR register. Setting these bits to RCC_CFGR_SWS_PLL enables PLL as the source of the system clock.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/657211012eb5e4aa69b322e8a4c4e525/href">https://medium.com/media/657211012eb5e4aa69b322e8a4c4e525/href</a></iframe><h4>Using the newly generated clock</h4><p>Using the above steps, we have successfully set the clocks as follows</p><ul><li>HCLK to 72MHz</li><li>SYSCLK to72MHz</li><li>AHBCLK to 72MHz</li><li>APB1CLK to 36MHz</li><li>APB2CLK to 72MHz</li></ul><p>In the demo application for this article, this clock@72MHz is used to drive the SysTick timer which in turn is used as a timebase for the aplication.</p><p>To know more about systick programming on STM32, head over to this article:</p><p><a href="https://medium.com/@csrohit/blue-pill-systick-programming-878dec0f1582">Programming SysTick timer on STM32f1 Blue Pill board as ARM Cortex M3</a></p><h3>Getting the source code</h3><p>Entire source code and information related to building and running code on the Blue Pill board is available in the following repository</p><p><a href="https://github.com/void-pointer-x/bluepill-clock-configuration">GitHub - void-pointer-x/bluepill-clock-configuration</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a058da220e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with USART and DMA in STM32 (ARM Cortex M3)]]></title>
            <link>https://medium.com/@csrohit/working-with-usart-and-dma-in-stm32-arm-cortex-m3-6a0e8b3174f3?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a0e8b3174f3</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[arm-cortex-m-series]]></category>
            <category><![CDATA[arm]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 16:52:42 GMT</pubDate>
            <atom:updated>2022-12-23T16:52:42.501Z</atom:updated>
            <content:encoded><![CDATA[<h4>STM32 EmbeddedC Baremetal Programming</h4><h4>A step-by-step guide on how to use DMA to transmit and receive data to and from USART</h4><p>I/O is one of our embedded application&#39;s slowest and most time-consuming parts. The application runs the best when the CPU is given the responsibility it is meant for i.e. processing. If we can delegate the task of reading/writing from memory to reading/writing the peripherals to someone else, then we can achieve this. This is when DMA comes to our help.</p><figure><img alt="DMA usart flow" src="https://cdn-images-1.medium.com/max/721/1*EdsvLyZJK3GbVMhWFUuhcg.png" /><figcaption>DMA for USART1 Transmit mode</figcaption></figure><h3>DMA (Direct Memory Acess)</h3><p>Direct memory access (DMA) is used in order to provide high-speed data transfer between peripherals and memory as well as memory to memory. Data can be quickly moved by DMA without any CPU actions. This keeps CPU resources free for other operations.</p><p>STM32F1 has a single DMA controller with 7 channels. It also has an arbiter for handling the priority between the DMA requests.</p><h4>Features</h4><ul><li>7 channels with individual software triggers</li><li>4 software-programmable priority levels</li><li>Independent source and destination transfer sizes (byte, half-word, and word)</li><li>Support for circular buffer management</li><li>3 event flags for transfer-complete, half-transfer-complete and transfer-error</li><li>Programmable number of transfers: up to 65535</li><li>Access to Flash, SRAM, APB1, APB2 and AHB peripherals as source and destination</li></ul><h4>Transfer direction</h4><p>Data can be transferred in any one of the following directions</p><ol><li>Memory to Memory</li><li>Memory to Peripheral</li><li>Peripheral to Memory</li><li>Peripheral to Peripheral</li></ol><h4>DMA Transactions</h4><p>After an event, the peripheral sends a request signal to the DMA Controller. The DMA controller serves the request depending on the channel priorities. As soon as the DMA Controller accesses the peripheral, an Acknowledge is sent to the peripheral by the DMA Controller. <br>The peripheral releases its request as soon as it gets the Acknowledge from the DMA Controller. Once the request is de-asserted by the peripheral, the DMA Controller releases the Acknowledge. If there are more requests, the peripheral can initiate the next transaction.<br>This complete flow is termed as 1 <em>DMA Transaction. </em>It consists of the following 3 operations:</p><ol><li>Data is loaded from the memory pointed by CPAR/CMAR register into an internal holding register</li><li>Data is then transferred from the holding register to the address pointed by the memory pointed by CMAR/CPAR register according to the direction of the transaction</li><li>Decrement the pending transactions counter</li></ol><h3>DMA Channels</h3><p>Each channel can handle DMA transfer between a peripheral register located at a fixed address and a memory address. The amount of data to be transferred (up to 65535) is programmable. The register which contains the number of data items to be transferred is decremented after each transaction.</p><h4>Programmable data sizes</h4><p>Transfer data sizes of the peripheral and memory are fully programmable through the PSIZE and MSIZE bits in the DMA_CCRx register.</p><h4>Pointer incrementation</h4><p>The memory and peripheral counters can optionally be incremented after each transaction. This feature can be enabled/disabled using the PINC and MINC bits in the DMA_CCRx register.</p><h4>Circular mode</h4><p>After the counter (number of data items to be transferred) reaches 0, it is reloaded with the initial value and the process repeats itself.</p><h3>Channel configuration procedure</h3><p>The following sequence should be followed to configure the DMA channel. In this example, we have configured channel 4 of DMA1 to transmit data on USART1 in circular mode.</p><h4>Set peripheral address</h4><p>Set the peripheral register address in the DMA_CPARx register. The data will be moved to this address from the memory after the peripheral event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e103fdb06d3409fab42e95fb07f5d1a/href">https://medium.com/media/9e103fdb06d3409fab42e95fb07f5d1a/href</a></iframe><h4>Set memory address</h4><p>Set the memory address in the DMA_CMARx register. The data will be written to or read from this memory after the peripheral event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46bacf840fbf38b982ac472712702c95/href">https://medium.com/media/46bacf840fbf38b982ac472712702c95/href</a></iframe><h4>Set the total no. of transactions</h4><p>Configure the total number of data to be transferred in the DMA_CNDTRx register. After each peripheral event, this value will be decremented.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe8f5ead1d256368aee1b11a1b221640/href">https://medium.com/media/fe8f5ead1d256368aee1b11a1b221640/href</a></iframe><h4>Configure channel priority</h4><p>Configure the channel priority using the <em>PL[1:0]</em> bits in the DMA_CCRx register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34da0c8dc03f5ffd7d83b05855162006/href">https://medium.com/media/34da0c8dc03f5ffd7d83b05855162006/href</a></iframe><h4>Configure transaction properties</h4><p>Configure data transfer direction, peripheral &amp; memory incremented mode, and peripheral &amp; memory data size in the DMA_CCRx register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edc3b0cffb43243377575e13eb837cfc/href">https://medium.com/media/edc3b0cffb43243377575e13eb837cfc/href</a></iframe><h4>Enable circular mode and interrupts</h4><p>Enable circular mode to repeat transactions continuously and enable interrupt after half and/or full transfer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb91585874b243bd7840c6c41555ec92/href">https://medium.com/media/eb91585874b243bd7840c6c41555ec92/href</a></iframe><h4>Activate channel</h4><p>Activate the channel by setting the ENABLE bit in the DMA_CCRx register. As soon as the channel is enabled, it can serve any DMA request from the peripheral connected to the channel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/381102b96eb0cb5158f06589c35a4b7a/href">https://medium.com/media/381102b96eb0cb5158f06589c35a4b7a/href</a></iframe><p>Once half of the bytes are transferred, the half-transfer flag (HTIF) is set and an interrupt is generated if the Half-Transfer Interrupt Enable bit (HTIE) is set. At the end of the transfer, the Transfer Complete Flag (TCIF) is set and an interrupt is generated if the Transfer Complete Interrupt Enable bit (TCIE) is set.</p><h3>USART</h3><p>The USART1 Transmitter is mapped to Channel 4 of DMA1. You can configure the USART1 peripheral by following the directions given in the following article.</p><p><a href="https://medium.com/@csrohit/stm32-blue-pill-usart-programming-f159dd6d896b">STM32 Blue Pill USART Programming</a></p><h4>Enable DMA Request for USART Transmitter</h4><p>USART transmitter can be configured to send requests to DMA when the data register is empty. This can be achieved by setting the DMAT bit in the USARTx_CR3 register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f8c2eb61a091096469b65425f6046c4/href">https://medium.com/media/2f8c2eb61a091096469b65425f6046c4/href</a></iframe><h4>main() function</h4><p>This function sets up the clock and initializes the DMA and USART1 peripherals.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/436816fe90bd77606155e60e582a40af/href">https://medium.com/media/436816fe90bd77606155e60e582a40af/href</a></iframe><p>as circular mode is enabled, we need not do anything after this. The DMA controller will retransmit the string continuously.</p><h3>Getting the source code</h3><p>The complete source code for this demo is available in the following GitHub repository. Please follow the instructions listed in the README file for building and flashing the binary on the target micro-controller.</p><p><a href="https://github.com/csrohit/stm32-uart/tree/main/dma-circular">stm32-uart/dma-circular at main · csrohit/stm32-uart</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a0e8b3174f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arm Cortex M3 Memory-mapped peripherals as Objects in C++]]></title>
            <link>https://medium.com/@csrohit/memory-mapped-peripherals-as-objects-in-c-51ee5bb54ca9?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/51ee5bb54ca9</guid>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[arm-cortex-m-series]]></category>
            <category><![CDATA[arm]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 18:19:10 GMT</pubDate>
            <atom:updated>2022-12-20T16:25:10.145Z</atom:updated>
            <content:encoded><![CDATA[<h4>STM32 Embedded C Baremetal Programming</h4><h4>A brief introduction to writing drivers for STM32 peripherals in C++ with objects mapped to existing peripherals.</h4><p>After my attempt at <a href="https://medium.com/@csrohit/writing-linker-script-for-stm32-arm-cortex-m3-%EF%B8%8F-fdc2acaaddcc">writing a linker script from scratch</a> and <a href="https://medium.com/@csrohit/stm32-startup-script-in-c-b01e47c55179">a startup script in C++</a>, I wanted to write drivers for ARM Cortex M peripherals in C++. I tried a couple of designs but in all the implementations the class definition required additional SRAM space for objects, which I wanted to avoid.</p><figure><img alt="Main function" src="https://cdn-images-1.medium.com/max/1024/1*yI-FEDsMirIOmBMiErGueQ.png" /><figcaption>fig 1: final main function</figcaption></figure><p>I posted my query on LinkedIn and Reddit that I wanted to create objects in c++ such that they are allocated pre-determined memory/address. I got a couple of responses that directed me to a CPPCon presentation by Dan Saks. I implemented his techniques and was able to reach my goal with this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuwzuAGtAEFk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuwzuAGtAEFk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuwzuAGtAEFk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/75c5a13d7a98f3b851df8b86f409e819/href">https://medium.com/media/75c5a13d7a98f3b851df8b86f409e819/href</a></iframe><p>In this article, I am going to demonstrate one of the techniques suggested by Dan Saks i.e. <strong>placement new. </strong>Using these I have implemented a simple USART driver in C++ in OOP style.</p><h3>Constructors</h3><p>The USART objects we create should be initialized before use, which is achieved by defining a constructor.</p><p>The constructors provide guaranteed initialization of the objects. If class USART has a constructor, the compiler <em>guarantees</em> to initialize every USART object by calling the constructors. Unfortunately, using a typecast invalidates this guarantee.</p><p>Memory-mapped objects are not <em>normal </em>objects in a way that</p><ul><li>We are not defining any objects of the type USART</li><li>We are just setting up pointers/references to the existing locations using <em>reinterpret_cast</em>.</li><li>The compiler is unable to generate a proper constructor for such objects.</li></ul><h4>Why not use reinterpret_cast?</h4><p>If we only use typecasting to create an object pointer then it becomes important that we call the initializer function right after to initialize the peripheral.</p><pre>USART *p = reinterpret_cast&lt;USART *&gt;(0x40013800);<br>p-&gt;init();</pre><p>If this step is skipped by the developer then our code would break. We have to find a way to create a new object which points to the predefined memory location and initializes it. Here, <em>placement new</em> comes to our rescue</p><h3>placement new</h3><p>When we create an object using the <em>new</em> keyword then it performs the following 2 operations:</p><ol><li>It uses the <em>new </em>operator to allocate memory</li><li>instantiates an object in the allocated memory.</li></ol><pre>// A new-expression has the form:<br>USART *p = new USART(v); // (v) is optional<br><br>// it is translated in the following 2 operations<br>p = static_cast&lt;USART *&gt;(operator new(sizeof(USART)));<br>p-&gt;USART(v); // call to constructor (for interpretation only)</pre><p>If we create an object this way then the allocated memory will be in the heap region which we don’t want. The <em>placement new</em> separates these two operations. It allows us to pass pre-allocated memory and then construct a new object in this past memory.</p><p>The address of the memory location the object is pointing to is known at compile time so most of the operations and checks can be done at compile time which helps up achieve the speed and code size parity with embedded-C.</p><blockquote>There is no concept called placement delete, but we can use the destructor to de-initialize the peripheral.</blockquote><h4>Constructors &amp; placement new</h4><p>C++ provides a version of the <em>new</em> operator that can be used to place an object a the desired location, overriding that will enable us to achieve our goal.</p><pre>void *operator new(size_t, void *p) noexcept {<br>return p;<br>}</pre><p>It ignores the first argument and returns the second argument. For placement new, we pass the pre-allocated address of the object as an argument to new. While creating a new reference to the memory-mapped object, we pass the address as an argument as follows &lt;region is the address&gt;:</p><pre>USART *p = new (region) USART(v); // (v) is optional</pre><blockquote>Argument to new is different from argument to constructor.</blockquote><blockquote>Here <em>v</em> is the argument passed to the constructor whereas <em>region</em> is the argument passed to the new operator.</blockquote><h3>Project operation</h3><p>In the main function, a reference to the USART class is taken which represents the USART1 peripheral. It is then configured using a C++ driver and string data is sent to USART every 2 seconds.</p><h4>USART Class definition</h4><p>The private members are the registers defined according to the memory layout described in the reference manual. Writing to these private member properties will have the same effect as writing to actual registers.</p><p>The functionality and configuration-related methods are defined as public members.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64a778de153b04105ad351d15bc5f664/href">https://medium.com/media/64a778de153b04105ad351d15bc5f664/href</a></iframe><h4>Overloading new operator</h4><p>As described above the new operator is overloaded which ignores the first parameter and returns the typecasted pointer to the mapped memory address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/009a1e9e2c1be730b3def97af8de59f9/href">https://medium.com/media/009a1e9e2c1be730b3def97af8de59f9/href</a></iframe><h4>Defining memory-mapped object</h4><p>In the below snippet, a reference to the USART1 peripheral is created using our overloaded new operator. A reference is created instead of a pointer in order to access its members using the . (dot) operator in place of the -&gt; (arrow) operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88c8f857a055fa7052513530ff3309e8/href">https://medium.com/media/88c8f857a055fa7052513530ff3309e8/href</a></iframe><p>The peripheral is configured by using the methods defined in the class and the string is transmitted every 2 seconds.</p><ul><li>Set baud rate to 9600</li><li>Enable transmitter</li><li>Start USART1 peripheral operation</li></ul><h4>Constructor</h4><p>The constructor initializes the clock for the peripheral and respective GPIO ports. The <em>Tx</em> and <em>Rx</em> pins are configured accordingly as shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9a060c11babaf26336b8a9998499612/href">https://medium.com/media/e9a060c11babaf26336b8a9998499612/href</a></iframe><h4>Destructor</h4><p>When the peripheral is no longer in use then it can be disabled by using the delete statement. It will safely disable the clock source for the peripheral, and additional checks can be applied to wait until the pending data transfer is finished.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd5b2612792632ce8852758ab4b28d5f/href">https://medium.com/media/dd5b2612792632ce8852758ab4b28d5f/href</a></iframe><h3>Getting the source code</h3><p>The entire source code for the USART driver as well as the other project files is available in the following GitHub repository. Refer to the README.md file for instructions related to building and flashing on the target microcontroller.</p><p><a href="https://github.com/csrohit/stm32-uart/tree/main/cpp">stm32-uart/cpp at main · csrohit/stm32-uart</a></p><h3>References</h3><ol><li><a href="https://cdn2-ecros.pl/event/codedive/files/presentations/2015/Representing-Memory-Mapped-Devices-Saks.pdf">Representing Memory-Mapped Devices as Objects by Dan Saks.</a></li><li><a href="https://www.geeksforgeeks.org/placement-new-operator-cpp/">Placement new operator in C++.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51ee5bb54ca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Linker Script for STM32 (Arm Cortex M3)️]]></title>
            <link>https://medium.com/@csrohit/writing-linker-script-for-stm32-arm-cortex-m3-%EF%B8%8F-fdc2acaaddcc?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc2acaaddcc</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[arm-cortex-m-series]]></category>
            <category><![CDATA[embedded-c]]></category>
            <category><![CDATA[stm32]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 13:29:01 GMT</pubDate>
            <atom:updated>2022-12-02T13:29:01.865Z</atom:updated>
            <content:encoded><![CDATA[<h4>Compiling and Linking programs for Embedded projects</h4><p>A step-by-step guide on how to write the custom linker script for Arm Cortex M3 micro-controller e.g. STM32F103 from scratch📝</p><p>ld combines a number of object and archive files, relocates their data, and ties up symbol references. Usually, the last step in compiling a program is to run ld.</p><p>When compiling programs for desktops🖥️, the linking process is taken care of by the toolchain. However, the linking process is more important when developing for embedded domain📟 as specific sections need to be placed in specific memory locations.</p><p>To have better command over the linking process, a set of instructions is provided to the linker which tells it to put the different sections in the output binary in a specific way.</p><p>In this article, we will be writing the linker script required for building a blinky program on an Arm Cortex M3 STM32 MCU from scratch...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-bVkV1WxohNBYGDxDjQWw.png" /><figcaption>Linking &amp; Relocation flow</figcaption></figure><h3>Linker🔗</h3><p>The linker combines input files into a single output file. The output file and each input file are in a special data format known as an <em>object file format</em>.</p><p>It accepts Linker Command Language files written in a superset of AT&amp;T’s Link Editor Command Language syntax, to provide explicit and total control over the linking process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*nje3e_TGwUEJeGwJ2eqkdw.png" /><figcaption>linking process</figcaption></figure><h3>Linker Script📝</h3><p>Every link is controlled by a <em>linker script</em>. This script is written in the linker command language.</p><p>The main purpose of the linker script is to describe how the sections in the input files should be mapped into the output file and to control the memory layout of the output file. It directs the linker to perform many other operations, using the commands described in the subsequent sections.</p><p>The simplest possible linker script consists of only one ‘SECTIONS’<strong> </strong>command to describe the memory layout of the output file. The following linker script loads the ‘text’ section at address 0x10000 and the data section at 0x8000000.</p><h4>ENTRY command</h4><p>The first instruction to execute in a program is called the <em>entry point</em>. You can use this command to set the entry point. This address is then put into the ELF file header. <br>The argument is a symbol name: ENTRY(&lt;symbol_name&gt;)</p><h4>SECTIONS command</h4><p>This command tells the linker how to combine input sections into output sections, and how to place the output sections in memory. The format of the SECTIONScommand is:</p><pre>SECTIONS<br>{<br>  sections-command<br>  sections-command<br>  …<br>}</pre><p>Each <em>sections-command may be one of the following:</em></p><ul><li>an ENTRY command</li><li>a symbol assignment</li><li>an output section description</li><li>an overlay description</li></ul><p>Don’t worry about this jargon, I will be explaining all these in upcoming articles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d82b2902aa4f3e9d6f6e766f2a5477ac/href">https://medium.com/media/d82b2902aa4f3e9d6f6e766f2a5477ac/href</a></iframe><h4>MEMORY command</h4><p>This command describes the location and size of blocks of memory in the target. You can use it to describe which memory regions may be used by the linker, and which memory regions it must avoid. The format of the MEMORY command is:</p><pre>MEMORY<br>  {<br>    name [(attr)] : ORIGIN = origin, LENGTH = len<br>    …<br>  }</pre><p>The <em>name </em>is the name used in the linker script to refer to the region. The attr string is an optional list of attributes which can be one of the following:</p><ul><li>‘R’ for Read-only sections</li><li>‘W’ for Read/write section</li><li>‘X’ for the Executable section</li><li>‘A’ for the Allocatable section</li><li>‘I’ for the Initialized section</li><li>‘!’ to invert the sense of any attribute that follows</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ee749c90f7eef3b5c1b5433e9015e09/href">https://medium.com/media/9ee749c90f7eef3b5c1b5433e9015e09/href</a></iframe><p>In the above script, we specify that there are two memory regions available for allocation.</p><ol><li>rom<br>This region is read and execute region starting at address 0x00 with a size of 256 kilobytes.</li><li>ram<br>This region is a read, write, and non-executable region starting at address 0x40000000 with a size of 4 megabytes.</li></ol><p>Every loadable or allocatable output section has two addresses. The first is the <em>VMA</em> or virtual memory address. This is the address the section will have when the output file is run. The second is the <em>LMA</em> or load memory address. This is the address at which the section will be loaded.</p><h4>Symbols and expressions</h4><p>Symbols are the identifiers defined in the linker scripts that are placed in the symbol table. Unlike variables, linker scripts symbol declarations, by contrast, create an entry in the symbol table but do not assign any memory to them. Thus they are an address without a value.</p><p>The special symbol name <strong>·</strong> indicates the location counter. You may only use this within a SECTIONS command. The semicolon after the expression is required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cb56ea6f92675835eecf1607442b371/href">https://medium.com/media/2cb56ea6f92675835eecf1607442b371/href</a></iframe><p>In this example, the symbol floating_point will be defined as zero. The symbol _etext will be defined as the address following the last .text input section. The symbol _bdata will be defined as the address following the .text output section aligned upward to a 4-byte boundary.</p><h4>Location Counter📍</h4><p>The special linker variable <strong>·</strong> (dot) represents the current output location counter, hence it can only appear in an expression within the SECTIONS command.<br>Assigning value to<strong> · </strong>will cause the location counter to be moved however, it can only be moved forward and not backward. Moving it backward may create areas of overlapping LMAs.<br>I will be explaining the location counter in detail in another article.</p><h3>Linker script in action</h3><p>Let’s write a linker script from scratch for our bare-metal blink project on STM32F103C8T6 MCU.</p><h4>Declare entry section</h4><p>We have defined a function Reset_handler()in the startup_<em>stn32f103.c file. </em>It should be called by the MCU after powering on, so we specify the symbol as the entry point for the application using this statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/138081a2b09388c31041656f326571a1/href">https://medium.com/media/138081a2b09388c31041656f326571a1/href</a></iframe><h4>Declare MEMORY regions</h4><p>Let’s define two memory sections for SRAM and FLASH memories. The FLASH is read/execute while the SRAM is read/write but the non-executable region.</p><p>From the datasheet, we have set the start addresses of FLASH and SRAM as 0x8000000 and 0x20000000 respectively. The MCU has 64KB of FLASH and 20KB of embedded SRAM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e37204ddcc2189a07b1227db6cb4e8/href">https://medium.com/media/56e37204ddcc2189a07b1227db6cb4e8/href</a></iframe><h4>Declare section for vector table</h4><p>For Arm Cortex M3 micro-controllers the 0x00 address should contain the value to be stored in the stack pointer, and the next address should contain the address of the Reset handler followed by the rest of the vector table.</p><p>In the <em>startup_stm32f103.c</em> file, we have defined an array vectors having the MSP value as well as the entire vector table. The array is placed in a separate section .isr_vector using the <em>section </em>compiler attribute.</p><p>To ensure proper booting of the MCU, we have to relocate this section to address 0x8000000. This is the first section declared in FLASH so it will be present at the first available memory location in the FLASH i.e. 0x8000000.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4497fbb1d457b5cc1f3e94be332163b/href">https://medium.com/media/e4497fbb1d457b5cc1f3e94be332163b/href</a></iframe><p>You might be wondering about the KEEP directive surrounding the input section name🧐, it instructs the linker to keep this section in the final executable even if it is not referenced in any other section.</p><p>Sections, that are not referenced by any other section but still need to be included in the executable are known as <strong>Magic Sections</strong>.</p><h4>.text section</h4><p>The exact position of other sections is not a concern as long as they are present in the correct memory region. The .text label on line 3 is the name of the output section and it is assigned to the <em>FLASH </em>memory region.</p><p>The wildcard present in *(.text) statement, instructs the linker to include .text sections from all the object files. The wildcard at the end of the *(text.*) statement instructs the linker to include all the subsections inside the .text section from all the object files. e.g. .text.ms_delay from the <em>delay.o </em>file<em> </em>or .text.startup.main from <em>main.o </em>file<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba3530d99004bcc6634b9e5cd4d50274/href">https://medium.com/media/ba3530d99004bcc6634b9e5cd4d50274/href</a></iframe><p>The . = ALIGN(4) statement updates the value of the location pointer to be aligned to 4bytes as the branch address is required to be aligned to 4bytes in Arm Cortex M architecture.</p><p>The _etext = . expression at line 10, assigned the value of the location pointer to the symbol _etext .</p><h4>.data section</h4><p>The .data section contains the pre-initialized global variables. Its contents are stored in the FLASH region when linking but should be loaded in SRAM during boot. The relocation is done by the startup_stm32f103.c and we need to provide the boundaries of the data section.</p><p>The Load Memory Address (LMA) is provided using the LOADADDR directive and the Virtual Memory Address (VMA) is provided using the _sdata = . statement. Unlike .text section where . represented LMA, in the .data section representing the VMA as this section is stored in SRAM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c96d6fa8d14cc7fae0254c1b0aa86997/href">https://medium.com/media/c96d6fa8d14cc7fae0254c1b0aa86997/href</a></iframe><h4>.bss section</h4><p>Unlike the .data section is not stored in FLASH but directly initialized to 0’s in SRAM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f947c975bc2efa353da5ba918fc21c18/href">https://medium.com/media/f947c975bc2efa353da5ba918fc21c18/href</a></iframe><h3>Build, Run and test</h3><p>The complete source code for this article is available in this Git Repository. Just clone, build and flash the binary onto an STM32F1 board to see it in action.</p><p><a href="https://github.com/csrohit/stm32-baremetal/tree/optimize-code">GitHub - csrohit/stm32-baremetal at optimize-code</a></p><h4>Output</h4><p>We can verify the contents of the final executable file are as per the instructions given in the linker script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMcpu3cVapTd64hf7cWOLQ.png" /><figcaption>Section table of the final executable file</figcaption></figure><h4>Further Reading</h4><p>Visit this article to understand the working of the startup file written in embedded C/C++.</p><p><a href="https://medium.com/@csrohit/stm32-startup-script-in-c-b01e47c55179">STM32 Startup script in C++</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc2acaaddcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing size of the executable for Embedded programs]]></title>
            <link>https://medium.com/@csrohit/optimizing-binary-size-for-embedded-programs-be8937a5754b?source=rss-28caeacdb058------2</link>
            <guid isPermaLink="false">https://medium.com/p/be8937a5754b</guid>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[linker]]></category>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[arm-cortex-m-series]]></category>
            <category><![CDATA[gcc]]></category>
            <dc:creator><![CDATA[Rohit Nimkar]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 03:40:31 GMT</pubDate>
            <atom:updated>2022-12-02T13:30:53.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>Compiling and linking Embedded Projects</h4><h4>A peek into compiler and linker options when building programs for embedded micro-controllers</h4><p>Given that a considerable amount of time and resources are consumed developing applications for desktop environments e.g. Linux Kernel, it makes sense to run the same software on embedded devices. It will make efficient use of an enormous investment of talent, time, and in some cases, money, which went into creating and improving it.</p><p>Embedded devices, however, lack much of the processing power and speed found on a desktop computer. Embedded systems are highly resource-constrained and cannot run the same applications as desktops.</p><p>This article will show you how to eliminate the typical inefficiencies in your code i.e. the unused public functions which are not referenced by other modules of the program. Usually, this technique saves about 10% of the precious flash memory on your microcontroller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1_ltoQoit2WrbGukjyGEg.png" /><figcaption>Fig 1: Linking module object files into final executable file</figcaption></figure><h3>Compilation flow</h3><p>The ELF object module (.o file) consists of blocks called sections. The compiler compiles the source code (.c file) and puts the executable code in sections/segments. The structure of object files is as follows:</p><ul><li>the<strong><em> header </em></strong>contains descriptive and control information</li><li><strong><em>.text </em></strong>section contains compiled executable code</li><li>.<strong><em>data</em></strong> section contains initialized variables of <em>global</em> storage class</li><li>.<strong><em>bss</em></strong> section contains uninitialized (initialized to 0 by default) variables of <em>global</em> storage class</li><li>.<strong><em>rodata</em></strong> sections contained read-only variables/data</li></ul><h4>Compiling delay.c</h4><p>In fig 1. the <em>.text </em>section<em> </em>contains executable code from <em>src/gpio.c. </em>It includes source codes for both the delay functions though the <em>unused_delay()</em> function is not being referenced.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ae7d6a4ea379515c49194395aa69e8e/href">https://medium.com/media/8ae7d6a4ea379515c49194395aa69e8e/href</a></iframe><p>After compiling the bodies of both functions are put into a single <em>.text</em> section, which is visible in the below screenshot of the sections table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSv9OpDIg2IqvDHZMknenw.jpeg" /><figcaption>Fig 2: section table of delay.o</figcaption></figure><h4>Compiling main.c</h4><p>As visible from the code snippet, the unused_delay() function is not referenced by the main() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0369aa9177065c327b535dfff5930abf/href">https://medium.com/media/0369aa9177065c327b535dfff5930abf/href</a></iframe><h4>Linking main.o and delay.o into blink.elf</h4><p>Linker sees that <em>main.o</em> has an undefined reference to the symbol ms_delay, it scans <em>delay.o</em> and finds its definition. Linker adds all the sections from the file including the <strong>entire</strong> <em>.text</em> section to the executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pjCZjj-KnX0OzjVtvCDQA.png" /><figcaption>Fig 2: Symbol table for main.o</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0b7Dbv2PMz_zhePY3igIQ.png" /><figcaption>Fig 3: Symbol table of delay.o</figcaption></figure><h4>We have a problem!</h4><p>Linker has no way of eliminating <em>unused_delay() </em>code because it is no longer known which part of the <em>.text</em> section is in <em>delay.o</em> corresponds to which function. It is only known where <em>ms_delay()</em> starts inside it, but as far as the linker is concerned, <em>ms_delay()</em> may jump around the entire <em>.text</em> section. <br>The linker has to link the entire <em>.text</em> section or risk losing parts of <em>ms_delay()</em>. This is how linking works in Unix since the beginning.</p><h4>Is there a solution?</h4><p>Yes, put every function into its very own section! The flags -ffunction-sections and -fdata-sections do that for us. So the code for <em>ms_delay()</em> goes into the <em>.text.ms_delay</em> section and the code for <em>unused_delay() </em>goes into the <em>.text.unused_delay</em> section. Now linker can distinguish between the two sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVsV47lsRTpa7KHtB-br_w.png" /><figcaption>Fig 4: list of sections for the delay.o using -ffunctions</figcaption></figure><h4>Are we done?</h4><p>No, the linker will still combine all the .text.* sections from selected modules into one .text section in the executable including the .text.unused_delay.<br>Now, we have to somehow tell the linker to drop the unused section…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJa9yZIqYeypFkYNMZQ3NA.png" /><figcaption>Fig 5: symbol table for blink.elf</figcaption></figure><p>As evident from the symbol table, both functions are still included in the symbol table of the final executable.</p><h4>How to tell the linker to drop unused sections?</h4><p>ld --gc-sections (if you invoke ld from gcc, use gcc Wl, --gc-sections), with this option, ld will not pull in all the sections from a .o file, it will pull only those which are needed to resolve a symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wG4azR4IJHRvx2lLBRKvmw.png" /><figcaption>Fig 6: Symbol table for blink.elf after using — gc-sections</figcaption></figure><p>Now, it can be verified that the <em>unused_delay()</em> function is not included in the final executable object file, only the <em>ms_delay()</em> function is included. This has saved us precious space in flash memory.</p><blockquote>ld --gc-sections does not collect only needed sections. It collects all sections from needed .o files, but before combining them into output file, it drops those sections which are not reachable from “seed” sections.</blockquote><h3>What about side effects?</h3><p>Your program will break if it uses special sections which are meant to be included in the final executable, even if these “magic” sections themselves are not represented. e.g. .isr_vectors .</p><h4>How to fix the “magic section” problem</h4><p>Often, this can’t be fixed. You must not link statically against libraries that use the “magic section” technique or use it yourself. Tweaking the linker script can sometimes fix this problem😅. Stay tuned for a detailed article that explains why we require magic sections and how to fix this problem if you are surprised by the “magic section” like I was.</p><p>Wait a minute, what is linker script🤔? If you are having the same problem then check out this article to know more about Linker script.</p><p><a href="https://medium.com/@csrohit/writing-linker-script-for-stm32-arm-cortex-m3-%EF%B8%8F-fdc2acaaddcc">Writing Linker Script for STM32 (Arm Cortex M3)🛠️</a></p><h3>Getting the source code</h3><p>Complete source code for this article available in the following repository</p><p><a href="https://github.com/csrohit/stm32-baremetal/tree/optimize-code">GitHub - csrohit/stm32-baremetal at optimize-code</a></p><h4>References</h4><ol><li><a href="https://elinux.org/images/2/2d/ELC2010-gc-sections_Denys_Vlasenko.pdf">Link time dead code and data elimination using GNU toolchain by Denys Vlasenko</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be8937a5754b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>