Hi!
I have this function outside my loop(), and I am wondering if there is any way I can make this function by using void.. I need to get rid of that int
I´m pretty new at this so, sorry if I ask dumb questions.
int se(){
long howfar;
digitalWrite(trigPin,LOW);
delayMicroseconds(5);
digitalWrite(trigPin,HIGH);
delayMicroseconds(15);
digitalWrite(trigPin,LOW);
howfar=pulseIn(echoPin,HIGH);
howfar=howfar/29;
return round(howfar);
}
I don't think we are clear on why you need to get rid of the int function type specifier. It would help to have you post all of your code. If you are calling it from within loop(), you can always ignore the return value:
void loop()
{
int temp;
temp = se(); // This uses the return value
se(); // This simply ignores the return value
}
All of these are global ints, so there must be some other reason.
const int IN1 = 2;
const int IN2 = 3;
const int IN3 = 4;
const int IN4 = 5;
const int recvPin = 11;
const int trigPin = 7;
const int echoPin = 8;
const int avstandGrense = 20; //distancelimit
const int svingetid = 300; //turntime in milliseconds
Also, your code has nothing in loop(), which means it does nothing after setup() is finished. What do you hope to do?
I'm sorry, I ment to say that we are not allowed to use global variables. The thing is that I am going to control a robot car with a remote control and then I will have a function for automatic "smart" car. So the biggest problem is to make the car run by it self.
If you are not allowed to use global variables, that's one thing. I doubt however that you're not allowed to use functions that return an int. Your se function should be fine as is.
int se(){
long howfar;
digitalWrite(trigPin,LOW);
delayMicroseconds(5);
digitalWrite(trigPin,HIGH);
delayMicroseconds(15);
digitalWrite(trigPin,LOW);
howfar=pulseIn(echoPin,HIGH);
howfar=howfar/29;
return round(howfar);
}
howfar is type long. The constant 29 is type int. Better you use 29L and not do mixed-type math.
round() is a floating point function that will convert howfar to float which may change 3 to 2.99999.
howfar being an integer, when you divide it will return the integer part of the division.
Integer (not just type int) math
5 / 2 = 2 -- the integer division result
5 % 2 = 1 -- the remainder
The return is supposed to be an int but you give it a float that the compiler will likely cast for you.
But if you want your code to be clear you should code the cast anyway.
return (int) howfar; // forget round(), long howfar will never have a fractional portion.
As Bulldog mentioned, if you make howfar a global variable then the function and loop() can use it.
And BTW, the speed of sound depends on the temperature of the air. Humidity and density have some effect but much less while temperature must vary a lot to make a significant difference.