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// http://www.legolab.daimi.au.dk/CSaEA/RCX/Manual.dir/Sensors.dir/Sensors.html
11// https://seriousrobotics.wordpress.com/2011/11/20/using-rcx-lego-sensors-with-arduino/
12
13#ifndef _MITOV_LEGO_RCX_LIGHT_SENSOR_h
14#define _MITOV_LEGO_RCX_LIGHT_SENSOR_h
15
16#include <Mitov.h>
17
18namespace Mitov
19{
20 template<int DIGITAL_PIN_NUMBER, int ANALOG_PIN_NUMBER> class LEGO_RCX_LightSensor : public Mitov::CommonEnableSource, public Mitov::ClockingSupport
21 {
22 typedef Mitov::CommonEnableSource inherited;
23
24 public:
25 uint32_t ChargePeriod = 2;
26 uint32_t MinValue = 90;
27 uint32_t MaxValue = 160;
28
29 bool Normalize : 1;
30
31 protected:
32 bool FHasValue : 1;
33
34 float FValue;
35 unsigned long FStartTime;
36
37 protected:
38
39 virtual void SystemStart() override
40 {
41 inherited::SystemStart();
42 FStartTime = micros();
43 pinMode( DIGITAL_PIN_NUMBER, OUTPUT );
44 digitalWrite( DIGITAL_PIN_NUMBER, HIGH );
45 }
46
47 virtual void SystemLoopBegin( unsigned long currentMicros ) override
48 {
49 if( ( currentMicros - FStartTime ) >= ChargePeriod * 1000 )
50 {
51 pinMode( DIGITAL_PIN_NUMBER, INPUT );
52
53 analogRead( ANALOG_PIN_NUMBER ); // Give some settle time
54 FValue = analogRead( ANALOG_PIN_NUMBER );
55 if( Normalize )
56 FValue = ( FValue - MinValue ) / (MaxValue - MinValue);
57
58 pinMode( DIGITAL_PIN_NUMBER, OUTPUT );
59 digitalWrite( DIGITAL_PIN_NUMBER, HIGH );
60 FHasValue = true;
61
62 FStartTime = micros();
63 }
64
65 if( ! ClockInputPin.IsConnected() )
66 ReadSensor();
67
68 inherited::SystemLoopBegin( currentMicros );
69 }
70
71 protected:
72 void ReadSensor()
73 {
74 if( FHasValue )
75 OutputPin.Notify( &FValue );
76 }
77
78 protected:
79 virtual void DoClockReceive( void *_Data ) override
80 {
81 ReadSensor();
82 }
83
84 public:
85 LEGO_RCX_LightSensor() :
86 FHasValue( false ),
87 Normalize( true )
88 {
89 }
90 };
91}
92
93#endif