Root/
Source at commit 58e0dda95d89dc652422961e6f5b823b41a86175 created 11 years 9 months ago. By Werner Almesberger, fw/accel.c: use timer 0 to trigger a pair of conversions (X/Y) only every 1 ms | |
---|---|
1 | /* |
2 | * fw/accel.c - Acceleration sensor |
3 | * |
4 | * Written 2012 by Werner Almesberger |
5 | * Copyright 2012 Werner Almesberger |
6 | * |
7 | * This program is free software; you can redistribute it and/or modify |
8 | * it under the terms of the GNU General Public License as published by |
9 | * the Free Software Foundation; either version 2 of the License, or |
10 | * (at your option) any later version. |
11 | */ |
12 | |
13 | |
14 | #include <stddef.h> |
15 | #include <stdbool.h> |
16 | #include <stdint.h> |
17 | |
18 | #include <avr/io.h> |
19 | #include <avr/interrupt.h> |
20 | |
21 | #include "io.h" |
22 | #include "accel.h" |
23 | |
24 | |
25 | void (*sample)(bool x, uint16_t v) = NULL; |
26 | |
27 | |
28 | static bool chan_x; |
29 | |
30 | |
31 | static inline void admux(bool x) |
32 | { |
33 | ADMUX = |
34 | 1 << REFS0 | /* Vref is AVcc */ |
35 | (x ? ADC_X : ADC_Y); |
36 | } |
37 | |
38 | |
39 | static inline void adcsra(bool start) |
40 | { |
41 | ADCSRA = |
42 | 1 << ADEN | /* enable ADC */ |
43 | (start ? 1 << ADSC : 0) | |
44 | 1 << ADIE | /* enable ADC interrupts */ |
45 | 7; /* clkADC = clk/128 -> 62.5 kHz */ |
46 | } |
47 | |
48 | |
49 | ISR(ADC_vect) |
50 | { |
51 | uint16_t v; |
52 | |
53 | v = ADC; |
54 | if (sample) |
55 | sample(chan_x, v); |
56 | |
57 | if (chan_x) { |
58 | chan_x = 0; |
59 | admux(0); |
60 | adcsra(1); |
61 | } |
62 | } |
63 | |
64 | |
65 | ISR(TIMER0_OVF_vect) |
66 | { |
67 | chan_x = 1; |
68 | admux(1); |
69 | adcsra(1); |
70 | } |
71 | |
72 | |
73 | void accel_start(void) |
74 | { |
75 | adcsra(0); |
76 | |
77 | TCNT0 = 0; |
78 | OCR0A = 125; /* 8 MHz/64/125 = 1 kHz */ |
79 | TCCR0A = |
80 | 1 << WGM01 | /* WG Mode 7 (Fast PWM to OCR0A) */ |
81 | 1 << WGM00; |
82 | TCCR0B = |
83 | 1 << WGM02 | /* WG Mode 7, continued */ |
84 | 1 << CS01 | /* clkIO/64 */ |
85 | 1 << CS00; |
86 | TIMSK0 = 1 << TOIE0; /* interrupt on overflow */ |
87 | } |
88 |
Branches:
master
tornado-v1