diff --git a/Interface/Harp.Behavior/AdcToVolt.cs b/Interface/Harp.Behavior/AdcToVolt.cs new file mode 100644 index 0000000..4495227 --- /dev/null +++ b/Interface/Harp.Behavior/AdcToVolt.cs @@ -0,0 +1,101 @@ +using System; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using Bonsai.Harp; +using Bonsai; + +namespace Harp.Behavior +{ + /// + /// Represents an operator that convertes raw ADC values to Volts. + /// + [Description("Converts a sequence of raw ADC reads to Volt.")] + public class AdcToVolt : Transform + { + /// + /// Converts a with raw voltage readings to volts. + /// + /// + /// A sequence of objects representing the converted values. + /// + public override IObservable Process(IObservable source) + { + return source.Select( + value => new AnalogVoltData() + { + AnalogInput0 = AdcToVoltConverter(value.AnalogInput0), + AnalogInput1 = AdcToVoltConverter(value.AnalogInput1) + }); + } + + /// + /// Converts a sequence of values + /// with raw voltage readings to volts. + /// + /// + /// A sequence of objects representing the converted values. + /// + public IObservable> Process(IObservable> source) + { + return source.Select( + value => + { + var payload = new AnalogVoltData() + { + AnalogInput0 = AdcToVoltConverter(value.Value.AnalogInput0), + AnalogInput1 = AdcToVoltConverter(value.Value.AnalogInput1) + }; + return Timestamped.Create(payload, value.Seconds); + }); + } + + /// + /// Converts a raw ADC value to volts. + /// + /// The raw ADC value to be converted. + /// The converted voltage value. + private static float AdcToVoltConverter(short adcValue) + { + // Full adc scale 4096 -> 3.3/1.6 = 2.0625V + // In practice, HW supports max 5V which translates + // to = 15/39 (given by resistor) * 5V = 1.9231 VMax + // input to the ADC. + // 1.9231V/2.0625V * 4095 = 3818 @ 5V analog input + return (float)(5.0 / 3818) * adcValue; + } + } + + /// + /// Represents the converted values from raw adc units to volts from + /// a payload of the AnalogData register. + /// + public struct AnalogVoltData + { + /// + /// The voltage at the output of the ADC channel 0. + /// + public float AnalogInput0; + + /// + /// The voltage at the output of the ADC channel 1. + /// + public float AnalogInput1; + + /// + /// Returns a that represents the + /// converted AnalogData payload. + /// + /// + /// A that represents the + /// converted AnalogData payload. + /// + public override string ToString() + { + return "AnalogVoltData { " + + "AnalogInput0 = " + AnalogInput0 + ", " + + "AnalogInput1 = " + AnalogInput1 + " " + + "}"; + } + } +}