6

I'm using an Arduino MKR WiFi 1010, a SAMD ARM Cortex M3 board. I rely on the standard library a lot, using things like std::vector<> and std::string. I also want to use std::cout. I've managed to do this on an UNO R3 using the ArduinoSTL library, but that library neither works nor is necessary on the MKR WiFi 1010, because it has all the standard library stuff built in to the platform.

However, on MKR WiFi 1010, I cannot get std::cout to produce any output. I'm guessing its not really hooked up to anything.

I want std::cout to write to Serial (which is aliased to SerialUSB which is of type Serial_).

Is there a way of making std::cout write to the Serial stream?

3
  • Maybe try using preprocessor by creating a #define clause? It might work. Something like this, but in the other way around. It's not really "writing to serial", but it will at least look that way when you read the code. Oct 22, 2019 at 7:20
  • MKR1010 is SAMD21G which is Cortex M0. but it too uses ARM implementation of stdio
    – Juraj
    Oct 22, 2019 at 9:00
  • 2

1 Answer 1

5

The ARM gcc libraries offer a simple way to redirect standard outputs. It is enough to implement function _write(int fd, char *ptr, int len) and it will replace the default implementation used in library to direct the standard outputs to debugger semihosting. The function must be compiled as C to match.

#include <Arduino.h>
#undef max
#undef min
#include <stdio.h>
#include <iostream>

using namespace std;

extern "C" {
int _write(int fd, char *ptr, int len) {
  (void) fd;
  return Serial.write(ptr, len);
}
}

void setup() {

  Serial.begin(115200);
  while (!Serial);

  Serial.println("START");

  printf("HERE WE ARE\r\n");

  cout << "TEST COUT\r\n";
  cerr << "TEST ERR\r\n";
}

void loop() {

}

the #undefs undefine the Arduino macros, which are in conflict with includes used in <iostream>

4
  • it took me many hours to make it work and in the end it is so simple
    – Juraj
    Oct 27, 2019 at 11:03
  • @TimLong, did the answer help?
    – Juraj
    Jan 30, 2020 at 15:19
  • Hy Thanks for sharing. It doesn't work for me. Arduion IDE 1.8.19, Mega2560 and DUE board. iostream no found. I made some search on the net. And it seams that stl is not supported on Arduino but I found some alternatives: Silver-Fang/ArduinoSTL on Github for example Mar 31, 2023 at 7:57
  • @MajorLee6695, the question was about the SAMD plaform (MKR board)
    – Juraj
    Mar 31, 2023 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.