This is just a test from other full code that I'v made and my radians after I calculate it turns into a negative number. I'm probably doing it wrong but I think you guys can direct me about this and help me with it, I have no idea why it's like that. Also don't mind other variables that are not mentioned in the loop. Also the laserServo_Pos needs to be between 0° and 55°. And the distanceL should be maximum 40 cm
#include <Servo.h>
#define shaftServo_Pin 3
#define laserServo_Pin 9
const int echoPinL = 5;
const int trigPinL = 6;
const int echoPinR = 10;
const int trigPinR = 11;
int laserPin = 2;
int shaftServo_Pos;
int laserServo_Pos;
Servo shaftServo;
Servo laserServo;
int distanceL;
int distanceR;
int leftside;//if the object is on the left side 1=true, 0=false
int rightside;//if the object is on the right side 1=true, 0=false
void setup(){
int shaftServo_Pos = 90;
int laserServo_Pos = 0;
shaftServo.attach(shaftServo_Pin);
laserServo.attach(laserServo_Pin);
pinMode(echoPinL, INPUT);
pinMode(trigPinL, OUTPUT);
pinMode(echoPinR, INPUT);
pinMode(trigPinR, OUTPUT);
pinMode(laserPin, OUTPUT);
Serial.begin(115200);
Serial.println("Start-setup");
shaftServo.write(shaftServo_Pos);
laserServo.write(laserServo_Pos);
}
void loop(){
float rad;
long durationL;
digitalWrite(trigPinL, LOW);
delayMicroseconds(2);
digitalWrite(trigPinL, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinL, LOW);
durationL = pulseIn(echoPinL,HIGH);
distanceL = (durationL/ 2 ) * 0.0343;
delay(20);
Serial.print("Distance: ");
Serial.println(distanceL);
rad = tan(distanceL + 2.26 / 15.35);//"2.26" distance from the front edge of the sensor to the shaft, "15.35" length from the middle of the sensor to the top hinge
Serial.print("Radian: ");
Serial.println(rad);
laserServo_Pos = ((rad * 4068) / 71)-15;
if(laserServo_Pos <= 55 && laserServo_Pos >= 0){//not permanent just temporarily
Serial.print("Laser servo pos: ");
Serial.println(laserServo_Pos);
laserServo.write(laserServo_Pos);
}
delay(2000);
}
Here is my "test bench".

