Go Down

Topic: How can I simplify this simple code? (Read 1 time) previous topic - next topic


boolean Plane::planeDisplaced(String dir, float input) {

You seem to be routinely passing numeric values around as Strings (and presumably parsing them again and again each time you need to access the value). You should really consider using numbers instead of strings. You could slightly simplify your bounds check using abs(), but I don't see it making a huge difference. Get rid of those Strings, though.
I only provide help via the forum - please do not contact me for private consultancy.


It depends on what you mean by "simpler."

The "modulo" solution makes for a short expression, but will increase execution time, because "modulo" is a relatively expensive calculation.

The "ternary operator" (x ? y:z) makes for fewer lines of code in the source, but it harder to read (IMO), and is likely to produce the same code as the if/else statement.

As other have said, your use of Strings is inappropriate and inefficient.  Assuming that the argument to your function MUST be a string (ie, cleaning up this function, but not looking beyond it), you can improve things by only doing the string to number conversion once:

Code: [Select]
float Plane::to360(String dir)
  float dirval = current(dir);   // (or maybe "int" ?)

  if (dirval < 0) {
    absRollAngle = (360 + dirval);
  }  else {
    absRollAngle = dirval;
  return absRollAngle;


Thanks everyone. I have taken your advice and altered my program to use compiler variables (bytes) instead of Strings and chars. I think it will run more efficiently now. Can someone please direct me to an article (Or give me an explanation) on why using String variables are usually bad in C++/Arduino?

Thanks again,
RadarProject - Arduino Autopilot for RC http://radarproject.wordpress.com/


There is not an article about using String class in Arduino is bad yet but from experience of many members and the fact that Arduino's free() function is buggy, it is easy to conclude that keep using String class will eventually drain memory to zero and crash the program.


Read Nick's sticky in this forum - it explains it and has a link to a discussion thread on the topic.

Go Up