I have a project that requires action if a certain error value has existed for a certain time. This code is executed every millisecond and the time might be 200mS.
I check for the error and if it's present check the time, if not, I reset the time variable. I.E.
There are a couple pitfalls that could occour. You need to make sure that the error is always positive for that code to work. Also, depending on what type of data you use for ticks, it could roll over and go back to zero if the systems has been in error for a long time.
I suppose there's a reason for that, but seems to me all using a signed type does is force you to check for < 0 and account for that too, but hey, it's your code...
I suppose there's a reason for that, but seems to me all using a signed type does is force you to check for < 0 and account for that too, but hey, it's your code...
An unsigned type for errors can make calculating the error more difficult.
For example, if the error is the difference between x1 and x2, and the code has:-
Code:
error = x1 - x2;
when x2 is larger than x1, the error value could appear to be really large.
Let's assume that error is an unsigned integer, so 0 - 65535, and x1 = 20 and x2 = 23, then x1 - z2 will result in
error = 65533
which is not what you want.
It's easier to have error as a signed integer, and calculate like this:-
As the code uses less than 20% of the available space and I've got processor time in abundance, it was more important to have easily understandable code. Which I believe it is.
Mike.
Edit, I think if(var<0) is easier to understand than if(var>127) and doesn't need changing if you change var to any other size.
I agree Mike, <0 is simpler.
Is there some special meaning to negative error codes vs positive ones?
The code in your original post works fine if all the values are unsigned, no abs required.
Just curious, since I usually reserve using signed variables for situations that require it.
The error can be positive or negative and different code has to be executed depending on the sign but the value needs to be positive. As I said, I've got oodles of time and program space so using signed variables is no problem.