Wednesday, July 1, 2015

Proper serial logging with arduino

In microelectronics, everything you do takes considerable time.
Sending data over serial link is quite heavy by itself.

Not only it takes CPU cycles. Serial.write() can block if the sending buffer is full. That's not okay.

My idea was to monitor output buffer and log only if it doesn't block.

Arduino documentation mentions that serial transmission is asynchronous, but doesn't hint how to deal with the output buffer. Searching web & stackoverflow didn't help. I even cloned the whole repository only to discover later the simple function in HardwareSerial.h:
int availableForWrite(void);
which tells how much bytes you can put in without blocking. Together with SERIAL_TX_BUFFER_SIZE that's just the right thing to know how much is enqueued.

As the result, I wrote the following little program:

unsigned char i = 1;

void setup() {
  Serial.begin(115200);
  Serial.print("start\n");
}

void loop() {  
  int inQueue = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite();

  if (inQueue < 8) {
    Serial.print(i); // that's heavy
    Serial.write('\n');
    i = 0;
  }

  i = i + 1;
}

Arduino Mega outputs ~22. Make it unsigned int and the output becomes 20. With unsigned long it's 18.

No comments:

Post a Comment