px-fwlib 0.10.0
Cross-platform embedded library and documentation for 8/16/32-bit microcontrollers generated with Doxygen 1.9.2
timer.c
1/* =============================================================================
2 ____ ___ ____ ___ _ _ ___ __ __ ___ __ __ TM
3 | _ \ |_ _| / ___| / _ \ | \ | | / _ \ | \/ | |_ _| \ \/ /
4 | |_) | | | | | | | | | | \| | | | | | | |\/| | | | \ /
5 | __/ | | | |___ | |_| | | |\ | | |_| | | | | | | | / \
6 |_| |___| \____| \___/ |_| \_| \___/ |_| |_| |___| /_/\_\
7
8 Copyright (c) 2006-2014 Pieter Conradie <https://piconomix.com>
9
10 License: MIT
11 https://github.com/piconomix/px-fwlib/blob/master/LICENSE.md
12
13============================================================================= */
14
15/**
16 * @ingroup AVR_TUTORIALS
17 * @defgroup AVR_TUT02_TIMER 02_timer
18 *
19 * How to configure and use a TMR peripheral as a blocking delay.
20 *
21 * File(s):
22 * - arch/avr/tutorials/02_timer/timer.c
23 *
24 * The LED flashes: on for 100 ms, off for 900 ms, on for 100 ms, ...
25 *
26 * See also:
27 * - @ref AVR_SYSCLK
28 * - @ref AVR_EX_FLASHING_LED
29 */
30
31#include <stdint.h>
32#include <stdbool.h>
33#include <avr/io.h>
34
35// LED GPIO pin macros
36#define LED_INIT() DDRB |= (1 << 0)
37#define LED_ON() PORTB |= (1 << 0)
38#define LED_OFF() PORTB &= ~(1 << 0)
39
40// Define CPU frequency in Hz
41#define F_CPU 7372800ul
42
43void tmr_init(void)
44{
45 /*
46 * Start 16-bit TMR1 with clock prescaler CLK/1024. For F_CPU = 7372800 Hz,
47 * the resolution is 139 us and the maximum time is 9.1 s
48 *
49 * Select Clear Timer on Compare match (CTC) mode of operation. This means
50 * that when TCNT1 reaches the OCR1A value, OCF1A flag will be set and
51 * TCNT1 will be reset to 0.
52 */
53 TCCR1A = (0 << WGM11) | (0 << WGM10);
54 TCCR1B = (0 << WGM13) | (1 << WGM12) | (1 << CS12) | (0 << CS11) | (1 << CS10);
55}
56
57void tmr_delay(uint16_t delay_ms)
58{
59 // Calculate and set delay
60 OCR1A = ((F_CPU / 1024) * delay_ms) / 1000;
61 // Reset counter
62 TCNT1 = 0;
63 // Clear OCF1A flag by writing a logical 1; other flags are unchanged
64 // This is more efficient than using "TIFR1 |= (1 << OCF1A);"
65 TIFR1 = (1 << OCF1A);
66 // Wait until OCF1A flag is set
67 while((TIFR1 & (1 << OCF1A)) == 0) {;}
68}
69
70int main(void)
71{
72 // Initialise LED GPIO pin
73 LED_INIT();
74 // Initialise timer
75 tmr_init();
76
77 // Loop forever
78 while(true)
79 {
80 // Enable LED
81 LED_ON();
82 // Wait 100 ms
83 tmr_delay(100);
84 // Disable LED
85 LED_OFF();
86 // Wait 900 ms
87 tmr_delay(900);
88 }
89}
#define F_CPU
Processor frequency in Hz.
Definition: px_board.h:52