px-fwlib
0.10.0
Cross-platform embedded library and documentation for 8/16/32-bit microcontrollers
generated with
Doxygen
1.9.2
pwm.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_TUT06_PWM 06_pwm
18
*
19
* How to configure and use a TMR peripheral to generate a PWM output.
20
*
21
* File(s):
22
* - arch/avr/tutorials/06_pwm/pwm.c
23
*
24
* The piezo buzzer is driven with a 50% duty cycle at about 1000 Hz.
25
*
26
* @tip_s
27
* An undesirable side-effect effect of the flexibility and power of the
28
* TMR peripherals is the sheer size of the datasheet documentation. Most
29
* times it helps to skip the lengthy description and focus on the actual
30
* peripheral register description, e.g. do not start at p.94, but jump
31
* directly to "15.9 Register Description" on p.105 of the ATmega328P
32
* datasheet.
33
* @tip_e
34
*/
35
36
#include <stdint.h>
37
#include <stdbool.h>
38
#include <avr/io.h>
39
40
// Define CPU frequency in Hz
41
#define F_CPU 7372800ul
42
43
int
main(
void
)
44
{
45
// Initialise PD6 to output low to buzzer
46
PORTD &= ~(1 << 6);
47
DDRD |= (1 << 6);
48
49
/*
50
* Start Timer 0 with clock prescaler CLK/64 and CTC mode.
51
* Output on PD6 (OC0A).
52
*
53
* For F_CPU = 7372800 Hz:
54
* - resolution is 8.7 us
55
* - frequency range is 57600 Hz to 225 Hz
56
*/
57
TCCR0A = (0 << COM0A1) | (1 << COM0A0) | (1 << WGM01) | (0 << WGM00);
58
TCCR0B = (0 << WGM02) | (1 << CS02) | (0 << CS01) | (0 << CS00);
59
60
// Reset counter
61
TCNT0 = 0;
62
// Set frequency to about 1000 Hz
63
OCR0A = ((
F_CPU
/ (2 * 64)) / 1000) - 1;
64
65
// Loop forever
66
while
(
true
) {;}
67
}
F_CPU
#define F_CPU
Processor frequency in Hz.
Definition:
px_board.h:52