typecast does not work?!

Hello guys,

I got a problem with my function here while I was using the servo lib for the first time to test it.
I used the example of the beginners guide (but does not matter).

I Write a small function to scale the output of the 10-Bit ADC to the input of the Servo class method write. So finally I want to use the full resolution of the ADC (0...1023) as input for the Servo class within a range from 0...180.

So what I do is:

void loop() {

static uint16_t valPoti_u16; //variable for the poti raw values
uint8_t agServo_deg_u8; //angle of the servo
uint32_t valTempAngle_u32; //temp variable used for upscaling

// read the values on A0
valPoti_u16 = analogRead(A0);

// upscale the linear adaption by 10000 --> (( 180 / 1024 ) * 10000 ) * valPoti
valTempAngle_u32 = uint32_t(1758 * valPoti_u16);
Serial.println(valTempAngle_u32);

// calculate set point for servo
agServo_deg_u8 = uint8_t(valTempAngle_u32 / 10000);
Servo1.write(agServo_deg_u8);

delay(20);

}

What I'm really wondering. In the middle of the code I do the upscaling so that I won't loose too much accuracy. But the value is not written into valTempAngle_u32. The typecast is not working correctly because the operation inside the brackets is done before with an implicit cast derived by the variable valPoti_u16. So I'm really confused. If I switch the valPoti_u16 variable to 32bit everything works fine. But there is no need to waste RAM for another 16bit which I really don't use at this point. Can you explain me why the typecast to 32bit is not working properly? Thanks in advance.

Greetings,
fostgate

1758UL * valPoti_u16;

Your typecast was simply too late.

Please remember to use code tags when posting code blah blah blah

There is a map() function that can do the mapping for you:

  Servo1.write( map(analogRead(A0), 0, 1023, 0, 180) );

But since both ranges start at 0 you can use:

  Servo1.write((analogRead(A0) * 180UL) / 1023));

The 180 is made an Unsigned Long because 1023 * 180 > 32767 so it won't fit in an int.

   static uint16_t valPoti_u16;    //variable for the poti raw values
   uint8_t agServo_deg_u8;       //angle of the servo
   uint32_t valTempAngle_u32;  //temp variable used for upscaling

        // read the values on A0
   valPoti_u16 = analogRead(A0);

Why is valPoti_u16 static, when you assign it a new value on EVERY pass through loop()?