view timer.cc @ 6:acbd0ddd002b

Add shared 1ms timer code Now blinks in a slightly useful manner Now has several submodes for acceptor state machine Clean ups
author Frank Kingswood <frank@kingswood-consulting.co.uk>
date Tue, 01 Apr 2014 20:35:06 +0100
parents
children
line wrap: on
line source
1 /* #------------------------------------------------------------------------#
2 | |
3 | timer.cc |
4 | |
5 | Shared 1ms timer. |
6 | |
7 | Copyright 2014, Frank A. Kingswood, www.kingswood-consulting.co.uk |
8 | |
9 #------------------------------------------------------------------------# */
11 #include <avr/io.h>
12 #include <avr/interrupt.h>
13 #include "timer.h"
14 #include "gpib.h"
16 SharedTimer *volatile SharedTimer::First=0;
18 inline void TimerInterrupt()
19 {
20 SharedTimer *timer=SharedTimer::First;
21 while(timer)
22 { timer->Tick();
23 timer=timer->Next;
24 }
25 }
27 SharedTimer::SharedTimer()
28 {
29 cli();
30 if((Next=First)==0)
31 {
32 TCCR0A=(1<<WGM01)|(1<<WGM00); // fast pwm mode (but no PWM output)
33 TCCR0B=(1<<WGM02)|(1<<CS01)|(1<<CS00); // prescaler=64
34 OCR0A=250-1; // 250*64=16000 cycles, 1ms
35 OCR0B=255;
36 TIMSK0=(1<<TOIE0); // enable overflow interrupt
37 }
38 First=this;
39 sei();
40 }
42 void SharedTimer::Tick()
43 { }
45 ISR(TIMER0_OVF_vect)
46 { TimerInterrupt();
47 }
49 Timer::Timer()
50 :SharedTimer(),Count(0),Reload(0),TimedOut(false)
51 {
52 }
54 void Timer::Tick()
55 {
56 uint16_t count=Count;
57 if(count>0 && --count==0)
58 { TimedOut=true;
59 Count=Reload;
60 }
61 else
62 Count=count;
63 }
65 uint16_t Timer::Read() const
66 {
67 cli();
68 uint16_t r=Count;
69 sei();
70 return r;
71 }
73 void Timer::Single(uint16_t time)
74 {
75 cli();
76 TimedOut=false;
77 Reload=0;
78 Count=time;
79 sei();
80 }
82 void Timer::Repeat(uint16_t time)
83 {
84 cli();
85 TimedOut=false;
86 Reload=Count=time;
87 sei();
88 }
90 void Timer::Clear()
91 {
92 cli();
93 TimedOut=false;
94 Reload=Count=0;
95 sei();
96 }
98 void Blinky::Tick()
99 {
100 if(--Count==0)
101 { Count=Reload;
102 Pattern=(Pattern>>1) | (Pattern<<15);
103 GPIB.LED(Pattern&1);
104 }
105 }
107 Blinky::Blinky()
108 :SharedTimer(),Count(0),Reload(0),Pattern(0)
109 {}
111 void Blinky::operator()(uint8_t period,uint16_t pattern)
112 { Count=Reload=period;
113 Pattern=pattern;
114 }
116 void Blinky::operator()(uint16_t pattern)
117 { Pattern=pattern;
118 }
120 Blinky blinky;
122 /* ----- EOF timer.cc ----- */