Faster printing

Hello,

I am working on a project and it is important that I can sample an (analog) ac signal of 500Hz. This means i want at least a sample frequency of 1kHz. The problem is that I cannot send this data over the serial port in that rate.

void setup() {
  Serial.begin(115200);
}

void loop() {
  long mfX = 1; //sensor 1
  long mfY = 2; //sensor 2
  long mfZ = 3; //sensor 3

  Serial.println(micros());
  char csv[40];
  sprintf(csv, "%ld,%ld,%ld,", mfX, mfY, mfZ);
  Serial.println(csv);
  Serial.println(micros());
}

When I use this code I get a 1444 difference between the first and second micros(); value. This means the frequency is around 692Hz (1/1444e-6).

It does not matter if I use separate Serial.println();s or sprintf(); (both get around 1444).

The sensor values can be -80000 to 80000, but i use 1, 2, 3 so I can cancel out the delay from the readings.

Is it true that the bottleneck here is the Serial.begin(115200)? Is there another way to speed up this serial data other than changing 115200 to a higher baud rate?

Thanks

noelvissers:
Is it true that this speed is limited by the Serial.begin(115200)?

No.

Is there another way to speed up this serial data other than changing 115200?

This comes to mind (I assume your question was poorly worded)...

  Serial.begin( 500000 );

A higher baud rate will help. I regularly use 500,000 baud.

If that is not enough then Serial.write() will be a lot faster than Serial.print() because it sends data in binary format. However you will need a complex program on your PC to interpret the received data.

My guess is that sprintf() is also slow on an Arduino.

As a half-way house between binary and human readable I have some code that converts numbers to base 64 values (for example 99 would be 1, 35 and then adds 48 to each of them making them '1' and 'S'. Obviously there is no advantage in sending "1S" rather than "97" except that the conversion is much faster. However two characters used like that could be "oo" which would be 63, 63 or 63 * 64 + 63 or 4095. (Hope I have remembered my own maths correctly).

Note that an array of characters such as "1S" can be sent using Serial.write

...R

Send the binary value. analogRead returns two bytes. The result if printing text is that you send between 1 and 4 bytes.

If it suites your needs is another question.

Thanks Robin2 and sterretje for the answers. I will try to use Serial.write and change the baud rate if needed.

@noelvissers: please stop using the "report to moderator" control for trivial peeves.