I am currently trying to implement some FFT hardware on an arduino, which then passes the spectrum over the serial port to a python script which can then display the spectrograms. I'm fairly new to Arduino programming but do have some C++ experience.
As far as I'm aware calling print functions repeatedly has a hefty overhead, so I am trying to send the data in frames of 128 spectrum samples. At the moment I have this and it works:
for(int i=0; i<(SAMPLES/2); i++)
Where vReal is the real component of the frequency spectrum in a double array of length 128.
However, this repeatedly calls println for each sample, and if i decide to increase the size of a frame this will only make the overheads worse. I'm trying to get my head around the difference between the Serial.prinln and Serial.write. From what I understand I should be able to send the double array as:
but then I keep getting error: no matching function for call to 'HardwareSerial::write(double , int) when I try to compile.
Simply put, what is the best way of sending blocks of numerical data in frames over a serial connection?
no matching function for call to 'HardwareSerial::write(double , int)
The write function (https://www.arduino.cc/reference/en/language/functions/communication/serial/write/) takes an array of bytes. You are trying to feed it an array of doubles.
Ah I see, so I need to convert the double array into an array of bytes and then just re-construct on the other end?
Yes. Using unions (http://www.cplusplus.com/doc/tutorial/other_data_types/) is one way to do that.
Sets up a union where the 4 bytes of num and the 4 bytes of bytes occupy the same memory locations. So if you do:
sampleBuffer.num = thisSample;
You can send the 4 bytes:
for(int n = 0; n < 4; n++)
On the other end you have an identical union. Receive the bytes and put them into the unions byte array (bytes) and then the new union's num member (sampleBuffer.num) will have the float.
Easier to just cast it:
Serial.write((uint8_t *) vReal, sizeof(vReal));
You must be running a devastatingly efficient FFT for Serial to be the bottleneck. Maybe just send the data less often?
What baud rate? Can you increase it? Maybe 500000?
println() sends carriage return and newline after each print. You could save time by not sending those.
What resolution do you need? println sends two decimal places by default. You can reduce that or send 100 times the value and save sending the decimal point character.
Serial.println(f); //7 chars
Serial.print(f); Serial.print(";"); //6 chars
Serial.print(f,1); //1 decimal place, 5 chars with separator
Serial.print(f*10,0); //4 chars
Serial.print(f,0); //3 chars
//convert to byte, allows only -128 to +127
Serial.write((byte)round(f)); //1 char
//convert to 16-bit int, equivalent to 2 bytes
//range -32768 to +32767
int16_t i = round(f*10); //choose a good multiplier