Incorrect return for Serial.write() on Teensy 3.6?

Status
Not open for further replies.

Bill Greiman

Well-known member
There appears to be a problem with the return value of Serial.write().

I ran the following program on Teensy 3.6 with Teensyduino version 1.32.
Code:
void setup() {
  Serial.begin(9600);
  while(!Serial);
  size_t n = Serial.write("test\r\n", 6);
  Serial.print("n: ");
  Serial.println(n); 
}
void loop() {}

the output is:
Code:
test
n: 0

On an Uno the output is as expected:
Code:
test
n: 6

Is this a bug or am I missing something?

Here are some other programs that seem to return zero.

Code:
  size_t n = Serial.println("test");

  size_t n = Serial.printf("test\r\n");
 
I think I've always seen that behavior, but I never looked into it. I just tested it on teensy LC, and it outputs zero.
 
FYI - It is also true for Serial1, Serial2... Might take more of a fix as these functions internal do not return anything...
 
Yup, they "return void" and there's some more editing needed.
My fix will work, at least, for usb-Serial.
 
Last edited:
IF Paul merges my pullrequest, i'll edit the other Serials, too..

Look like a very general problem. Here is an SD.h problem.


Code:
  File file;
  file = SD.open("SD.txt", FILE_WRITE);

   // later in a for loop
  for (uint32_t i = 0; i < 40000; i++) {

  // calculate x, y, z  here

    int nc = file.printf("x: %.4f, y: %.4f, z: %.4f\r\n", x, y, z);
    if (nc <= 0) {
      Serial.print("ERROR ");
      Serial.println(nc);
      break;
    }
 }

The file has the correct text but nc is zero and the following is printed:
Code:
ERROR 0

I am very happy to see everyone working on a fix.
 
FYI - It is also true for Serial1, Serial2... Might take more of a fix as these functions internal do not return anything...

Kurt: Hm, i just tested Serial1 - it works (?!)

Edit: ALL Serialx work :)
With print, and printf, and write.
 
Last edited:
Kurt: Hm, i just tested Serial1 - it works (?!)
Yep -if you look at HardwareSerial.h, you see:
Code:
	virtual size_t write(const uint8_t *buffer, size_t size)
					{ serial_write(buffer, size); return size; }
Some of the others look interesting as well:
Code:
	virtual size_t write(uint8_t c) { serial_putchar(c); return 1; }
	virtual size_t write(unsigned long n)   { return write((uint8_t)n); }
	virtual size_t write(long n)            { return write((uint8_t)n); }
	virtual size_t write(unsigned int n)    { return write((uint8_t)n); }
	virtual size_t write(int n)             { return write((uint8_t)n); }
 
That looks right - regarding the size.

Edit: my PRs were merged by Paul (thank you, Paul)
 
Last edited:
Status
Not open for further replies.
Back
Top