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.
- 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?
- 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();
- 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
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.