aboutsummaryrefslogtreecommitdiff
path: root/pwm.c
blob: c38a1624632d38343dacb2cea8c03a8782d6c8d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*	LED pwm, uses timer0
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>
#include <assert.h>
#include <stdlib.h>

#include "speaker.h"
#include "pwm.h"

/* max count for blinks */
static uint8_t blink[6];
static uint8_t comphit = 0;
static uint8_t state = 0;
/* PORTB and PORTB values */
static uint8_t val[2];
static uint8_t init[2];

static uint8_t ledToArray (const uint8_t i) {
	assert (i < PWM_LED_COUNT);
	if (i >= 2) {
		return 1;
	} else {
		return 0;
	}
}

static uint8_t ledToShift (const uint8_t i) {
	assert (i < PWM_LED_COUNT);
	static const uint8_t shifts[] = {PB6, PB7, PD2, PD3, PD4, PD5};
	return shifts[i];
}

/*	All LEDs are off for state % 2 == 0 (off state) or state >= 7 (end of blink
 *	sequence), setting blink[i] = state*2 causes LED i to blink state times
 */
ISR(TIMER0_COMPA_vect) {
	++comphit;
	/* divide by 13 to get ~10 Hz timer */
	if (comphit >= 13) {
		comphit = 0;
		++state;
		if (state == 12) {
			state = 0;
		}
		val[0] = init[0];
		val[1] = init[1];
		if (state >= 10 || state % 2 == 0) {
			/* end of blink/off state */
		} else {
			for (uint8_t i = 0; i < PWM_LED_COUNT; i++) {
				if (state < blink[i]) {
					val[ledToArray (i)] |= (1 << ledToShift(i));
				}
			}
		}
	}

	if (comphit % 2 == 0) {
		/* switch off: we can’t just set to 0 here, since PB6 is used by
		 * speaker */
		PORTB = PORTB & ~((1 << PB6) | (1 << PB7));
		PORTD = PORTD & ~((1 << PD2) | (1 << PD3) | (1 << PD4) | (1 << PD5));
	} else {
		PORTB |= val[0];
		PORTD |= val[1];
	}
}

void pwmInit () {
	/* set led1,led2 to output */
	DDRB |= (1 << PB6) | (1 << PB7);
	/* set led3,led4,led5,led6 to output */
	DDRD |= (1 << PD2) | (1 << PD3) | (1 << PD4) | (1 << PD5);
}

void pwmStart () {
	/* reset timer value */
	TCNT0 = 0;
	/* set ctc timer0 (part 1) */
	TCCR0A = (1 << WGM01);
	/* enable compare match interrupt */
	TIMSK0 = (1 << OCIE0A);
	/* compare value */
	OCR0A = 255;
	/* io clock with prescaler 256; ctc (part 2) */
	TCCR0B = (1 << CS02) | (0 << CS01) | (0 << CS00);
}

void pwmStop () {
	/* zero clock source */
	TCCR0B = 0;
}

void pwmSetBlink (const uint8_t i, const uint8_t value) {
	assert (i < PWM_LED_COUNT);
	if (value == PWM_BLINK_ON) {
		/* permanently switch on LED */
		init[ledToArray (i)] |= (1 << ledToShift (i));
	} else {
		init[ledToArray (i)] &= ~(1 << ledToShift (i));
		blink[i] = value*2;
	}
}