I am writing a function to calculate the distance of an object using a HCSR04 sensor. The sensor sends out a sound and waits for the return. Using the time it takes for the sound to return, I can calculate the distance of the object. My function performs this task and returns the distance in centimeters. I use the returned value to judge if my robot can continue moving forwards and in which direction to turn when an object is blocking its path.
I use the function as follows:
def sides():
if sen.dist_1() + sen.dist_5() < stg.safe_front_dist:
print("Sides Checked - Going back.")
return "back"
elif sen.dist_1() > sen.dist_5():
print("Sides Checked - Left.")
return "left"
elif sen.dist_1() < sen.dist_5():
print("Sides Checked - Right.")
return "right"
else:
print("Error checking sides.")
return "error"
While this works without problems, I am wondering if it is better to assign the values of each function to a variable then compare the variables. This would look like:
def sides():
dist_1 = sen.dist_1()
dist_5 = sen.dist_5()
if dist_1 + dist_5 < stg.safe_front_dist:
print("Sides Checked - Going back.")
return "back"
elif dist_1 > dist_5:
print("Sides Checked - Left.")
return "left"
elif dist_1 < dist_5:
print("Sides Checked - Right.")
return "right"
else:
print("Error checking sides.")
return "error"