This is only a minor annoyance and does not actually affect the running of my program in anyway, it is more a curiosity of how i would solve it if it was critical to the program operation for future reference.
The issue i have is my program has a variable Capacity Remaining % which i print to the terminal.
This value is calculated with the following code snippets:
// User Defined Variables
int TANK_DEPTH = 100; // Sump Depth Setting (cm)
// Variables For UltraSonic Sensor Calculation
float VELOCITY = 0.034; // Speed of Sound 340 m/s in cm/us
long DURATION; // Time Trig -> Echo
float DISTANCE; // Distance (cm)
float PERCENT; // Sump Capacity Percentage (%)
float VAL_A = 100/TANK_DEPTH ; // Used in Percentage Calculation
// Read Echo Pulse Travel Time
DURATION = pulseIn(US_ECHO_PIN, HIGH);
// Calculate Distance Measurement:
// Speed = Time x Velocity
// Distance = Time x Velocity / 2
DISTANCE = DURATION*VELOCITY/2;
// Calculate Capacity Percentage
PERCENT = VAL_A*DISTANCE;
When the sensor reads a value over the defined Tank Depth(=100) i.e 110cm it reads 110% how would i make the code so that it ignores any value over 100% and just displays 100% ???
As i say this wouldn't occur in this application as it would never read over 100% and has only occurred while i am testing i am just curious.
That's not even the simplest solution. You could also use constrain(), which under the hood probably does the same:
PERCENT = constrain(PERCENT, 0, 100);
Another thing: all capital variable names are normally used to distinguish constants such as your VELOCITY (which presumably never changes). Those variables normally then also have the const keyword added to their declaration:
const float VELOCITY = 0.034;
Now if you still try to change the value somewhere in the code, the compiler throws an error.
An then there is the line feed character that you can use instead of println(). The println() function automatically sends a line feed and carriage return after the print data. Most of the time sending a line feed does the same as println().
Some ways to print to the next line without println(). Six lines without println:
void setup()
{
Serial.begin(115200);
Serial.print("line one"); // reference line
Serial.print('\n'); // send just line feed
Serial.print("line two");
Serial.print("\nline three"); // insert a line feed into a string
Serial.write(10); // send DEC value of line feed
Serial.print("line four");
Serial.write(0x0a); // send HEX value of line feed
Serial.print("line five");
Serial.print("\r\n"); // the same as println()
Serial.print("line six");
}
void loop()
{
}