Arduino Code: Assigning Serial Monitor Input to Float Variables

Subscribe to my Feed!

The Arduino code given on this page will allow you to input numbers into the Arduino IDE’s Serial Monitor and assign them to float variables. Essentially, this allows you to manually control the Arduino through the Serial Port.

The example code below calculates the hypotenuse of a right triangle from the user inputted base and height. To use it, upload the Sketch to the Arduino, open the Serial Monitor, type in the desired values, and hit enter when you’ve finished typing them in.

The interesting bit is done in the getFloatFromSerialMonitor() function. If, for example, you wanted to assign the variable x using input from the Serial Monitor, you would do so like this.

float x = getFloatFromSerialMonitor();

From there, you can then use x in whatever floating point calculations you desire. That’s all there is to it!

 
 void setup(){
   Serial.begin(9600);
 }
 
void loop()
{
 
 Serial.println("Hypotenuse of a right triangle calculator");
 Serial.println("What is the base?");
 float x = getFloatFromSerialMonitor();
 Serial.println(x);
 Serial.println("What is the height?");  
 float y = getFloatFromSerialMonitor();
 Serial.println(y); 
 Serial.println("The Hypotenuse is:");  
 Serial.println(sqrt(x*x+y*y));
 Serial.println("~~~~~~~~~~~~~~~~~~");    
}
 
  float getFloatFromSerialMonitor(){
  char inData[20];  
  float f=0;    
  int x=0;  
  while (x<1){  
  String str;   
  if (Serial.available()) {
    delay(100);
    int i=0;
    while (Serial.available() > 0) {
     char  inByte = Serial.read();
      str=str+inByte;
      inData[i]=inByte;
      i+=1;
      x=2;
    }
    f = atof(inData);
    memset(inData, 0, sizeof(inData));  
  }
  }//END WHILE X<1  
   return f; 
  }

Subscribe to my Feed!