I've got a strange error and I'm hoping that I just overlooked something, but I can't for the life of me determine my issue. I've written a function to change the value that will be written to a servo, but for some reason the value isn't changing within the code. The following code my be incomplete syntax wise(I'm only including relative pieces), but it does compile and upload through the IDE.
The following code contains my setup and loop functions.
#include <Servo.h>
// ULTRASONIC PIN DEFINITIONS
#define TrigPin 7
#define RightEcho 8
#define LeftEcho 10
//SERVO DEFINITION
Servo servo1;
#define led 9 //LED USED FOR INITIAL TESTING
long RightTime, LeftTime, RightDistance, LeftDistance;
float servotime; //DECLARE VARIABLE
void setup(){
// I/O DECLARATIONS
pinMode(TrigPin, OUTPUT);
pinMode(RightEcho, INPUT);
pinMode(LeftEcho, INPUT);
pinMode(led,OUTPUT); //LED USED FOR INITIAL TESTING
servo1.attach(6); //ATTACH SERVO TO PIN 6
int servotime = 1500; //init servo angle
servo1.writeMicroseconds(servotime); //INITIALIZE POSITION
digitalWrite(TrigPin, LOW); //Initialize trigger as low
Serial.begin(9600); //Serial Communication for troubleshooting
}
void loop(){
LeftTime = readHCSR04(TrigPin, LeftEcho);
RightTime = readHCSR04(TrigPin, RightEcho);
RightDistance = (RightTime / 148); //Distance in Inches, eqn from datasheet
LeftDistance = (LeftTime / 148); //Distance in Inches, eqn from datasheet
calcTime(LeftTime, RightTime, servotime);
servo1.writeMicroseconds(servotime);
}
This code contains the calcTime function
float calcTime( float left, float right, int timetowrite){ //May need to change floats to ints
// 5% Tolerance
if (((.95 * left) > right) == 1){ //if left is more than right (w/ tol)
timetowrite = timetowrite + ((left - right)/2); // add half of the difference (half brings them equal)
}
if (((.95 * right) > left) == 1) { //if right is more than left (with tol)
timetowrite = timetowrite - ((right - left)/2); //subtract half of the difference
}
return timetowrite;
}
The problem I'm have is the timetowrite variable in the calcTime function is always return a 0. When I run the serial monitor, I have the two conditions being met(The .95*left > right and vice versa), so I'm fairly certain that the loop is being executed(although I'm going to do some further testing on that as soon as I'm done with this post).
I'm wondering if I have an issue with the types of variables I'm doing math with. I'm declaring a long in the setup and then utilizing a float in my calcTime function. I guess I don't know enough about programming concepts to know if that's allowed or not.
Any insight on this would be much appreciated as I'm at a loss as to why it's always returning a 0.