0

I'm mapping a potentiometer from 0-1023 to 1000-120000 (1 sec to 2 minutes) for a timer, like:

maxDelay = map (pot2, 0, 1023, 1000, 120000);

Both variables are integers. Now I would like to convert/round values to counts of 10 seconds (a count of thousands), so if I have anything from 1001-5000 this would be rounded to 1000 (1sec), and if I have 5001-10000 it would be rounded to 10000 (10 secs), then 20sec, 30sec, etc...until it reaches 120secs. I know I could have a few "if" statements but I'm trying to figure out the right way of doing these maths. Thanks.

Chu
  • 105
  • 1
  • 6

1 Answers1

1

I didn't yet compiled it, but something like this should work:

#include <Math.h>

int converter(int x)
{
    if(x <= 5000)
        return 1000;
    else 
        return (int)(round(x / 10000.0) * 10000.0);
}
Filip Franik
  • 1,272
  • 1
  • 7
  • 20
  • I'm not sure that's what I'm looking for....for example, if the value (x) is 2500, dividing by 1000 is 2.5...the result I'm expecting is 1000. How is this going to round the values? – Chu Feb 08 '19 at 09:46
  • In the wonderful world if integers dividing `2500` by `1000` gives us `2`. I thing I misunderstood your question. You want the system to show only values 1,10,20,30... Right? – Filip Franik Feb 08 '19 at 09:47
  • right, but still I need it to be 1000 when smaller than 5000...but in this case I can just have an IF. But when higher than 5000, for example 8000, it should result in 10000...(rounds up 8 to 10, etc)..17000 to 20000... – Chu Feb 08 '19 at 09:51
  • Yes, 1, 10, 20, 30..that's it. – Chu Feb 08 '19 at 09:52
  • that's great! it looks good now, I will have a go and let you know. Thanks. – Chu Feb 08 '19 at 09:55
  • Sorry it's still not working for 17000 rounding to 20000 give me a minute. – Filip Franik Feb 08 '19 at 09:57
  • yes, I noticed this way it will always round numbers down...which is not what I expected but it's OK, it should do the job. Although if you want to improve the answer I appreciate too. thanks! :) – Chu Feb 08 '19 at 10:02
  • Instead of using properties of integer unfortunately I had to use `round` method. It's not as elegant (it requires cast to double and then back to integer to work correctly) but this approach should do exactly what you want. – Filip Franik Feb 08 '19 at 10:23
  • Just a note for future reference (if anyone is looking for a similar solution), on an Arduino Due this should work fine, but on Atmega boards I used an unsigned long instead of an integer since these values are over 32,767. – Chu Feb 08 '19 at 11:02