So I've been doing a project in which floating point calculations have slowed it down to the point where a critical timing function is thrown off considerably, and the output I get is about half of what it should be. Quick searches of the internet have informed me that floats are incredibly inefficient in Arduino Unos, so I should somehow convert everything to fixed point math.
I quickly wrote this test code to see the impact of the change from fixed point to floating point. I ran this code once using all floating point numbers and having the readVoltage() function return a float, and it took about 13.5 seconds.
I then converted as much of it to fixed points as I could figure out (which is the code I've pasted here), and it takes 12.5 seconds to run. I understand that if done properly, fixed point math should be 40x faster than floating point math, and fixed points can do everything floating points can.
How can I improve this code so it runs faster?
//An example of a program that takes an analog input, converts it to voltage, and displays
//Speed testing features have been added. Will output the time the code took in ms at the end
const int resistorFactor = 5115; //divide by 10 to get actual factor, 511.5
unsigned long time;
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long sTime = millis();
int i = 0;
while(i < 1000) { //Run the ReadVoltage() funtion a bunch, and output 1) what it equals and 2) How you would convert it to human readable numbers
Serial.println(ReadVoltage());
Serial.print(" ");
Serial.println(ReadVoltage() / 100.0);
i++;
}
unsigned long eTime = millis();
Serial.println((eTime - sTime));
Serial.end();
}
int ReadVoltage() {
int val = analogRead(A5);
val = 709; //This is just a testing variable, to trick it into thinking its actually connected to a battery
float fvolt = ((val / (resistorFactor / 10.0)) * 5);
return fvolt * 100;
}