Program 3: Delay Generation using a Timer (Polling Method) - 5.3 | EXPERIMENT NO. 9 TITLE: Introduction to ARM Microcontrollers - Basic I/O and Peripherals | Microcontroller Lab
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to Timer Configuration

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today we're going to look at how we can use timers to generate precise delays. Can anyone tell me why timers are important in embedded systems?

Student 1
Student 1

They help control the timing of events, like LED blinking or responding to button presses.

Teacher
Teacher

Exactly! Timers provide a way to handle tasks that require accurate timing. Now, let's discuss how we configure a timer. What do you think we need to set first?

Student 2
Student 2

Maybe the prescaler? It alters the frequency of the timer clock.

Teacher
Teacher

Correct! The prescaler divides the clock frequency to slow down the timer. The prescaler value determines how many timer ticks equal one increment in the counter. Now, what follows after setting the prescaler?

Student 3
Student 3

We have to set the auto-reload value to define how long the timer will count before resetting.

Teacher
Teacher

Yes! The auto-reload value determines the number of counts for the desired delay. Let's summarize this session: We first enable the timer clock, set the prescaler to get the desired counting frequency, and then define the auto-reload count for the delay.

Polling the Update Interrupt Flag (UIF)

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

In our second session, let's discuss polling the update interrupt flag, UIF. Why is polling important after we start the timer?

Student 4
Student 4

We need to know when the timer has finished counting to our set value!

Teacher
Teacher

Exactly! Polling allows us to check the status of the UIF repeatedly until it indicates that our delay is complete. Once UIF is set, we can safely clear it.

Student 1
Student 1

So, does the program just sit there using CPU time while waiting?

Teacher
Teacher

Typically, yes. That’s why in real applications, clever use of timers is crucial to minimize CPU load. Let’s practice how we would implement this in our code.

Student 2
Student 2

Should we consider using interrupts instead for more complex applications?

Teacher
Teacher

Great point! Using interrupts can make your programs more efficient, allowing them to perform other tasks while waiting for the timer to finish. Always an essential aspect to bear in mind!

Practical Example: Blinking an LED

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now, let's put all we've learned into practice by writing some code to blink an LED using our timer. What is the first step in our program?

Student 3
Student 3

We need to enable the GPIO for the LED so that we can control it.

Teacher
Teacher

That's right! After that, we will follow it with timer configuration steps. Can anyone outline the code for enabling the timer?

Student 4
Student 4

We would enable the timer clock, set the prescaler, configure the auto-reload, then start the timer.

Teacher
Teacher

Perfect! Finally, we will enter a loop where we toggle the LED state using our delay function. What will you observe when we run this program?

Student 1
Student 1

The LED should turn ON and OFF every 500 milliseconds, showing precise timing!

Teacher
Teacher

Exactly! This demonstrates how effective timers can be in ensuring accurate event timing in your applications.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section explains how to generate precise delays using a timer in ARM microcontrollers, specifically through the polling method.

Standard

In this section, students learn to utilize general-purpose timers to create accurate delays for LED blinking. The approach emphasizes the use of specific registers and configurations needed for timer operations, showcasing practical C code for implementation.

Detailed

Delay Generation using a Timer (Polling Method)

This section focuses on using general-purpose timers in ARM microcontrollers (STM32) to generate precise delays. By leveraging polling methods, we can effectively manage timing for tasks like LED blinking.

Key Points Covered:
1. Timer Configuration: Timer clocks must be enabled and the prescaler and auto-reload register values set to achieve the desired delay. For instance, if you want a 500 ms delay, you can configure the timer with a prescaler value and an auto-reload value accordingly.
2. Polling the Update Interrupt Flag (UIF): Once the timer is started, we poll the UIF to check when the timer has overflowed, indicating the completion of the delay.
3. Practical Example in C: The section provides a practical example where a LED on PA5 is toggled using the timer for generating precise time delays, illustrating the process with example code.

This method is advantageous for ensuring more accurate timing compared to software-based loops, making it particularly useful in embedded systems where timing precision is crucial.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Objective and Assumptions

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Objective: To generate a precise delay of 500 milliseconds using a general-purpose timer (e.g., TIM2) by polling its update flag, and use this delay to blink the on-board LED (PA5).

Assumptions:
- System Clock: 84 MHz (APBx clock frequency assumed to be 84 MHz or derived from it).
- Timer: TIM2 (connected to APB1 bus). Max APB1 frequency is usually 42 MHz.
- Let's assume TIM2 clock is 42 MHz.
- Desired Delay: 500 ms = 0.5 s.

Detailed Explanation

In this program, we aim to create a delay of 500 milliseconds utilizing a timer to control the blinking of an LED connected to pin PA5. The system clock runs at 84 MHz, which is used to derive the timer's frequency. Here, we assume that the timer TIM2 operates with a frequency of 42 MHz. Hence, to achieve a delay of half a second, we need to properly configure the timer's prescaler and auto-reload values.

Examples & Analogies

Think of the timer as a stopwatch that starts counting every millisecond. If you want to stop the stopwatch at 500 milliseconds, you need to set up the timer to know when it has counted to 500. Just like a timer in a kitchen that beeps when the food is ready, we will poll the timer until it indicates that 500 milliseconds have passed.

Calculations for Timer Configuration

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Calculations:
- Let Timer_Clock_Frequency = 42 MHz.
- Choose Prescaler_Value = 41999.
- Counter_Clock_Frequency = 42,000,000 / (41999 + 1) = 1,000 Hz (1 kHz).
- Time_per_Count = 1 / 1,000 Hz = 1 ms.
- For a 500 ms delay:
- Auto_Reload_Value (ARR) = (500 ms / 1 ms/count) - 1 = 499.

Detailed Explanation

To configure the timer accurately, we determine the necessary values for the prescaler and the auto-reload register. Setting the prescaler at 41999 divides the 42 MHz clock frequency down to 1 kHz, which results in each count lasting 1 millisecond. To create a delay of 500 milliseconds, the auto-reload register is set to 499, meaning the timer will count from 0 to 499, giving us the desired interval.

Examples & Analogies

Imagine you're timing an event where you need to wait for 500 seconds. If your timer counts in 1-second increments, you need to program it to keep going until it reaches 500. By setting a 'delay' of 499 counts (for the 500 milliseconds), you're effectively giving your bystander an exact countdown they need.

Timer Delay Function Implementation

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

// C Code:

include "stm32f4xx.h"

// Define symbolic names for convenience

define LED_PIN_NUM 5

void timer_delay_ms(unsigned int ms) {
// 1. Enable Clock for TIM2 (TIM2 is on APB1 bus)
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
// 2. Configure Prescaler
// TIM2_PSC (Prescaler Register): 41999 -> Counter clock becomes 1 kHz (1ms per count)
TIM2->PSC = 41999;
// 3. Configure Auto-Reload Value for the desired delay
// TIM2_ARR (Auto-Reload Register): For 500ms delay, ARR = 499 (since each count is 1ms)
TIM2->ARR = ms - 1; // ms delay, so ms-1 counts from 0 to ms-1
// 4. Generate an update event to load the prescaler and ARR values immediately
TIM2->EGR |= TIM_EGR_UG; // Set UG bit
// 5. Clear the Update Interrupt Flag (UIF)
TIM2->SR &= ~TIM_SR_UIF; // Clear UIF bit
// 6. Start TIM2 by enabling the counter
TIM2->CR1 |= TIM_CR1_CEN; // Set CEN bit
// 7. Wait until the Update Interrupt Flag (UIF) is set (polling)
while (!(TIM2->SR & TIM_SR_UIF));
// 8. Clear UIF and stop timer for one-shot delay
TIM2->SR &= ~TIM_SR_UIF; // Clear UIF again
TIM2->CR1 &= ~TIM_CR1_CEN; // Clear CEN bit to stop timer
}

Detailed Explanation

The timer_delay_ms function is constructed to configure and control the timer for a specified delay in milliseconds. First, we enable the timer clock, set up the prescaler, and auto-reload value to manage how the timer counts. Next, we initiate an update event for the timer to correctly load these configurations. After starting the timer, we enter a polling loop, which keeps the CPU busy until the timer reaches the designated count (indicated by setting the update interrupt flag). Finally, we stop the timer and reset the flag for future use.

Examples & Analogies

Think of this function like a factory that needs to set up machinery before starting production. First, you power up the machines (enabling the clock), then you adjust their settings (prescaler and auto-reload), start them, and repeatedly check if they've finished the required cycles (polling). Once done, you can stop them and reset for the next batch.

Main Function and LED Control

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

int main(void) {
// Configure PA5 as General Purpose Output (for LED) - Same as Program 1
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
GPIOA->MODER &= ~(GPIO_MODER_MODER5_Msk);
GPIOA->MODER |= GPIO_MODER_MODER5_0;
GPIOA->OTYPER &= ~GPIO_OTYPER_OT_5;
GPIOA->ODR &= ~(1U << LED_PIN_NUM); // Initialize LED OFF
while (1) {
// Turn LED ON
GPIOA->ODR |= (1U << LED_PIN_NUM);
timer_delay_ms(500); // Delay for 500ms
// Turn LED OFF
GPIOA->ODR &= ~(1U << LED_PIN_NUM);
timer_delay_ms(500); // Delay for 500ms
}
}

Detailed Explanation

In the main function, we set up GPIO pin PA5 for output, ensuring the LED is configured correctly first. The program then enters an infinite loop where it continuously toggles the LED on and off with a 500ms pause in between, using the previously defined timer_delay_ms function to regulate the timing.

Examples & Analogies

Imagine you are turning a light on and off at a party to create a cool effect. You first make sure the bulb is fitted correctly (setting up PA5), then you turn it on, count to 500 seconds (timer_delay function), and then turn it off. You keep doing this to keep the party lively!

Expected Behavior and Monitoring

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Simulation/Expected Results:
- Hardware: The on-board LED on PA5 should blink ON and OFF with approximately 0.5-second intervals, demonstrating precise timing controlled by the timer.
- Keil/CubeIDE Debugger: Monitor Peripherals view for TIM2 (TIM2->CNT and TIM2->SR). Observe TIM2->CNT incrementing, TIM2->SR's UIF bit becoming 1 after the programmed delay, and PA5 toggling.

Detailed Explanation

After implementing the program, we expect the LED to blink in half-second intervals. This visual indication serves as feedback that the timer is functioning correctly and our delay logic works as intended. In the debugging environment, we can watch the timer's count register and the status register, verifying the timer's behavior against our expectations.

Examples & Analogies

Just like being at a concert where the lights blink to the beat, seeing the LED blink confirms everything is working smoothly. By watching the timer's count, it's like having a backstage view of how the lighting shows are being controlled, ensuring they match the rhythm on stage.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • Timer Configuration: Setting up the prescaler and auto-reload registers is essential for delay generation using timers.

  • Polling Method: The polling method requires constant checking of the timer's update flag to manage the timing.

  • Applications of Timers: Timers are widely used in embedded systems for event timing, blinking LEDs, and more.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • Using TIM2 to generate a precise 500 ms delay to blink an LED every half second.

  • Configuring timer registers to control the timing of events in microcontroller applications.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • Prescaler brings the count down low, meant to slow the timer's flow.

📖 Fascinating Stories

  • Imagine a race where each runner needs to slow down, the prescaler is their trainer.

🧠 Other Memory Gems

  • Remember 'PIC' for Timer tasks: Programming, Initialization, Counting.

🎯 Super Acronyms

TAP

  • Timer
  • Auto-reload
  • Polling - the steps to remember for using timers.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: Timer

    Definition:

    A hardware peripheral that counts clock cycles and can generate timed events through interrupts or flags.

  • Term: Prescaler

    Definition:

    A register that divides the input clock frequency to alter the timer's counting speed.

  • Term: AutoReload Register

    Definition:

    A register that defines the value the timer counts to before it resets, generating an update event.

  • Term: Polling

    Definition:

    The process of regularly checking a status indicator, such as a flag, in a program.

  • Term: Update Interrupt Flag (UIF)

    Definition:

    A flag indicating that a timer has reached its count limit and can trigger an interrupt or be polled.