Change a variable to text for serial monitor (Arduino Uno)

252 Views Asked by At

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.

2

There are 2 best solutions below

0
On

distance is a float, you cannot set a float to a char *.

is there any way to convert the distance variable without using a new variable?

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.

0
On

"is there any way to convert the distance variable without using a new variable?" You don't need to convert it or use another variable. Don't change distance and send a string instead:

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

  // You don't need this check. pulseIn returns an unsigned long. It's always >= 0
  /*if(distance < 0) {
    distance = 0;
  } */
  if(distance > 400) {
    Serial.println("Out of range");
    return;
  }

  Serial.println(distance );
}

Unrelated to your problem. You don't need to check if distance is negative. pulseIn returns an unsigned long. It's always non-negative.