0

I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library.

2 Answers 2

0
  1. First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?
  2. In case the answer to the previous question is "yes", then you can just cast it on the fly: int int_val = (int)function_returning_longint();
  3. In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution: int int_val = function_returning_longint() >> 8; This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like int8_t and int16_t. And in your case you might have to shift by a different value than 8.

Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.

-1

If you want to store it as int, you have to firstly store it in a long type then convert it into int.

For instance:

long i;
int j;
i = getReading();
j = (int) i;

There are many ways to do it, for example you can also use rounding to convert it into integer variable.

1
  • It's not necessary to use an auxiliary variable. But what is really dangerous in this answer, is that it doesn't check if the value is small enough to be represented as int. Oct 19, 2015 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.