Can I read an analog input as integer, not as double?

I want to read the position of a joystick. 0 shall be middle, negative (-127) shall be left and positive (127) shall be right. So I want to read the result of the analog input into a signed integer variable.
(The “joystick” driver doesn’t help, it has only two channels and returns doubles.)
My idea is to read the eight MSB of the ADC result into an sbyte with MSB toggled:

Is that (or something similar) possible?
(I don't want to convert a 12 bit fixpoint value to a 64 bit floating point value and then back to an 8 bit fixpoint value...)

This should work :

private static Int32 _scaleLow, _scaleHigh;         // Lower/Upper bound of scale
        private const Int32 MinValue = 0, MaxValue = 4095;  // Min/Max values returned by ADC

        public static void Main()
            SetScale(-127, 127);
            Debug.Print("0 -> " + Scale((Int32) 0.0));
            Debug.Print("4095 -> " + Scale((Int32) 4095.0));
            Debug.Print("2048 -> " + Scale((Int32) 2048.0));


        public static void SetScale(Int32 low = MinValue, Int32 high = MaxValue)
            if (((high - low) > MaxValue) || (low >= high)) { throw new ArgumentOutOfRangeException("SetScale"); }
            _scaleLow = low;
            _scaleHigh = high;

        private static Int32 Scale(Int32 x)
            return (_scaleHigh - _scaleLow) * (x - MinValue) / MaxValue + _scaleLow;

Result :

0 -> -127
4095 -> 127
2048 -> 0

Probably you missunderstood my question.
My FEZ Cerberus has one (or more) 12 bit ADC which produces a 12 bit fixpoint value. My question is: How can I read this value without converting it to a floating point value?

ReadRaw() method instead of Read() ?

That’s too easy of a solution. ???

This works:

Microsoft.SPOT.Hardware.AnalogInput input = new Microsoft.SPOT.Hardware.AnalogInput(Microsoft.SPOT.Hardware.CPU.AnalogChannel.ANALOG_0);
int position = input.ReadRaw();

Thanks, Bec a Fuel!
My next proplem is: How can I use the gadgeteer socket numbers instead of “[…]AnalogChannel.ANALOG_0”? (FEZ Cerberus and probably some other gadgeteer mainboards)

 _analog = new AnalogInput(GT.Socket.GetSocket(3, true, null, null).AnalogInput3);

This is for the analog channel on Pin 3 of socket 3 on the Cerberus mainboard.

1 Like