Go Down

### Topic: Basic question concerning types (Read 970 times)previous topic - next topic

#### mjarek

##### Feb 27, 2011, 03:23 pm
In my code I try to map the value of delta (which is time interval based on millis() ), usually in the range of 400-800 ms, to a byte (400 = 0, 800 = 255, values outside the range are clipped to the border values). I have this code:

if (delta > 800) delta = 800;
axis = delta - 400;
if (axis < 0) axis = 0;
axis = (axis * 1000) / 1569;
...
Wire.send(axis);

axis is int, delta is unsigned long. When I output the values, delta behaves exactly as it should. axis, however, takes rather strange values, even negative ones, although those should be ruled out completely.

I suppose this is a case of mismatched types. I guess that when I get the axis value right, it would still be sent incorrectly to Wire (as it should be a byte)?

I could hack it somehow, I suppose, but I would prefer to understand the underlying principles and see a more elegant solution...

#### PaulS

#1
##### Feb 27, 2011, 03:33 pmLast Edit: Feb 27, 2011, 03:35 pm by PaulS Reason: 1
Quote
When I output the values, delta behaves exactly as it should. axis, however, takes rather strange values, even negative ones, although those should be ruled out completely.

This depends on how you output the value.

Quote
In my code I try to map the value of delta (which is time interval based on millis() ), usually in the range of 400-800 ms, to a byte (400 = 0, 800 = 255, values outside the range are clipped to the border values). I have this code:

There are map() and constrain() functions to do this. Why not use them?

Finally, just because the value in axis could fit in a byte, Wire.send() will not send it as a byte, because it isn't a byte. If you need Wire.send() to send a single byte, you need to store the value to be sent in a byte variable, and pass that variable to the Wire.send() function.

#### Magician

#2
##### Feb 27, 2011, 03:39 pm
I suggest, that do a casting than subtract:
axis = (int)delta - 400;

#### pluggy

#3
##### Feb 27, 2011, 04:08 pm
Providing you define the variables taking millis() values as 'unsigned long' rather than 'int' there shouldn't be any problems.
http://pluggy.is-a-geek.com/index.html

#### mjarek

#4
##### Feb 27, 2011, 05:01 pm

I have misinterpreted the purpose of map() before - it seems it is indeed perfect for this case.

If I type axis as byte, then, this should work?

delta = constrain (delta, 400, 800) ;
axis = map(delta, 400, 800, 1, 255);
Wire.send (axis);

I cannot test this out yet, wife's still around

#### PaulS

#5
##### Feb 27, 2011, 05:21 pm
Quote
If I type axis as byte, then, this should work?

delta = constrain (delta, 400, 800) ;
axis = map(delta, 400, 800, 1, 255);
Wire.send (axis);

Shouldn't the to range be 0 to 255? Otherwise, yes.