1////////////////////////////////////////////////////////////////////////////////
2// //
3// This software is supplied under the terms of a license agreement or //
4// nondisclosure agreement with Mitov Software and may not be copied //
5// or disclosed except in accordance with the terms of that agreement. //
6// Copyright(c) 2002-2016 Mitov Software. All Rights Reserved. //
7// //
8////////////////////////////////////////////////////////////////////////////////
9
10#ifndef _MITOV_SPEED_TO_CLOCK_h
11#define _MITOV_SPEED_TO_CLOCK_h
12
13#include <Mitov.h>
14
15namespace Mitov
16{
17 class SpeedToClock : public Mitov::CommonSink
18 {
19 typedef Mitov::CommonSink inherited;
20
21 public:
22 OpenWire::SourcePin DirectionOutputPin;
23 OpenWire::SourcePin ClockOutputPin;
24
25 public:
26 bool Enabled = true;
27 float MaxFrequency = 100.0f;
28
29 protected:
30 unsigned long FLastTime = 0;
31 unsigned long FPeriod = 0;
32// bool FDirection;
33 bool FSendOutput = false;
34
35 protected:
36/*
37 virtual void CalculateFields()
38 {
39 FPeriod = ( (( 1 / Frequency ) * 1000000 ) + 0.5 );
40 }
41*/
42 virtual void SystemLoopBegin( unsigned long currentMicros ) override
43 {
44 if( ! FSendOutput )
45 FLastTime = currentMicros;
46
47 else
48 while( currentMicros - FLastTime >= FPeriod )
49 {
50 if( Enabled )
51 ClockOutputPin.Notify( NULL );
52
53 FLastTime += FPeriod;
54 }
55
56 inherited::SystemLoopBegin( currentMicros );
57 }
58
59 virtual void SystemStart() override
60 {
61 inherited::SystemStart();
62 FLastTime = micros();
63 }
64
65 protected:
66 virtual void DoReceive( void *_Data ) override
67 {
68 float ASpeed = constrain( *(float *)_Data, 0.0, 1.0 );
69 float AFrequency = abs( ASpeed - 0.5 ) * 2;
70 FSendOutput = ( AFrequency != 0 );
71 if( FSendOutput )
72 {
73 AFrequency *= MaxFrequency;
74 FPeriod = ( (( 1 / AFrequency ) * 1000000 ) + 0.5 );
75 }
76
77 else
78 FPeriod = 0;
79
80 bool ADirection = ASpeed > 0.5;
81
82 DirectionOutputPin.Notify( &ADirection );
83 }
84
85 };
86}
87
88#endif