Go Down

Topic: Serial.println is my bottleneck - anything that can be done? (Read 58 times) previous topic - next topic


Hello - Im trying to sample an External SPI ADC and send the data over usb/serial directly to USB, but it seems like the Serial interface is a bottleneck in my setup.

Here is my current code:
Code: [Select]

#include <SPI.h>
#include <digitalWriteFast.h>

int CNV= 11; //Convert on pin 11
int Slaveselect=8;
unsigned int adcValue;
unsigned long time1;
unsigned long time2;
unsigned long rate;

void setup() {
  // put your setup code here, to run once:

SPI.setClockDivider(SPI_CLOCK_DIV2 ); // 8 MHz rate
  pinModeFast(Slaveselect, OUTPUT);
  pinModeFast(CNV, OUTPUT);


void loop() {
  // put your main code here, to run repeatedly:

digitalWriteFast(CNV,HIGH);//starts conversion
digitalWriteFast(CNV,LOW); //starts to transmit MSB on data line

adcValue = SPI.transfer16(0x00);
rate = time2-time1;

and by that I get my "rate" to being 192 micro's - if i change the placement for time2=micros(); to
Code: [Select]

adcValue = SPI.transfer16(0x00);
rate = time2-time1;

i get around 10 micro's - So why is Serial.println so slow and is there anything i can do about it?

- Running on the ATMEGA32u4


The Serial.println() function contains a very large body of code which makes it slow.

If you need speed then you should send the data in binary format using Serial.write() but then your PC program will have to know how to interpret the data properly.

If you are using a Leonardo or Micro with a 32U4 MCU then the baud rate is irrelevant - it will send at the full USB speed.

You may find that you get better throughput on the USB system by saving up (say) 32 values in an array and sending that all at once rather than sending each value separately. When the amount of data in a message is less than 64 bytes the USB system can be surprisingly slow.

Two or three hours spent thinking and reading documentation solves most programming problems.

Go Up