I'm using an HC-SR04 Ultrasonic Sensor that displays distance, there's two if statements, if it's below 0 it comes out as 0 (that part works as intended), if it's over 4 meters (distance variable is a centimeter) it is supposed to say "Out of range", and that's the part I'm having an issue with. Here's the full code
const int TrigPin = 2;
const int EchoPin = 3;
float distance;
void setup() {
Serial.begin(9600);
pinMode(TrigPin,OUTPUT);
pinMode(EchoPin,INPUT);
}
void loop () {
digitalWrite(TrigPin,LOW);
delayMicroseconds(2);
digitalWrite(TrigPin,HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin,LOW);
distance = pulseIn(EchoPin,HIGH)/58.0; // divided by 58 to change into cm
if(distance < 0) {
distance = 0;
}
if(distance > 400) {
distance = "Out of range";
}
Serial.println(distance );
}
This returns an error that says "cannot convert 'const char [13]' to 'float' in assignment" (line 26), is there any way to convert the distance variable without using a new variable? (There's already another if statement for the distance variable). I am a pretty early beginner in this so the solution could be extremely simple and I just don't know it.
distance
is a float, you cannot set a float to a char *.Well you cannot convert the variable to be another data type after you have declared it to be int. What you can do is declare it char * (string) and then when you want to set it to a number like 0, to convert the number to a string. That is if you really want to have a single variable for both.