Why won't the function work?

So I am trying to convert a number from a 0 to 270 range to a 0 to 180 range and it always outputs 0. I could be stupid but I am unsure what I'm doing wrong.


Servo myservo;

int pos = 90;

int temp;

void write270(int position) {
  temp = position / 270 * 180;
  myservo.write(temp);
}

void setup() {
  Serial.begin(9600);
  myservo.attach(2);
}

void loop() {
  write270(90);
}

try

 temp = 180 *position / 270;

or do you really want to divide pos by 48600?

I'll keep that in mind. Thank you for the help.

I think you want:
temp = position * 180 / 270;
Or
temp = position * 2 / 3;

Strictly saying, not always.
Your function will return 0 for position values in range 0-269, but 180 for position = 270.
It is because the result of integer division x/y where x < y will truncated down to nearest integer, so always returns zero

General rule with integers:
Multiply first, than divide.
By the way: integer division by 16 is way faster than division by 15...

...and be careful that what you're multiplying into is big enough to hold it.

2 Likes

Whatever this does or does not, there is nothing to do with 48600, or 270 * 180.

I ran this program

# include <stdio.h>

long a, b, c;

int main()
{
    printf("Hello World\n");
    
    a = 12345678 / 270 * 180;
    b = 12345678 / (270 * 180);
    c = 12345678 * 180 / 270;
    
    printf("a = %ld    b = %ld   c =  %ld\n", a, b, c);

    return 0;
}

and got this reuslt:

main.cpp: In function β€˜int main()’:
main.cpp:13:18: warning: integer overflow in expression of type β€˜int’ results in β€˜-2072745256’ [-Woverflow]
   13 |     c = 12345678 * 180 / 270;
      |         ~~~~~~~~~^~~~~
Hello World
a = 8230320    b = 254   c =  -7676834

...Program finished with exit code 0
Press ENTER to exit console.

The rearranged calculation of c overflows. The other calculataions are what you would expect.

Be careful out there.

a7

why didn't you try using the value of 90 that the OP uses?

output

Hello World
a = 0    b = 0   c =  60
# include <stdio.h>

long a, b, c;

int main()
{
    printf("Hello World\n");
    
#define X  90
    a = X / 270 * 180;
    b = X / (270 * 180);
    c = X * 180 / 270;
    
    printf("a = %ld    b = %ld   c =  %ld\n", a, b, c);

    return 0;
}

You can also take a look at the function map() !
It is by default in the Arduino IDE and is exactly what you need :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.