Go Down

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

martin1454

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:

 Serial.begin(230400);
 
 SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV2 ); // 8 MHz rate
 SPI.setBitOrder(MSBFIRST);
  pinModeFast(Slaveselect, OUTPUT);
  pinModeFast(CNV, OUTPUT);

  digitalWriteFast(Slaveselect,HIGH);
}

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


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



 
adcValue = SPI.transfer16(0x00);
Serial.println(adcValue);
time2=micros();
rate = time2-time1;
Serial.println(rate);
     
}


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);
time2=micros();
Serial.println(adcValue);
rate = time2-time1;
Serial.println(rate);


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

Robin2

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.

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

Go Up