CommunityGD32Cores / ArduinoCore-GD32

Arduino core for GD32 devices, community developed, based on original GigaDevice's core
Other
92 stars 33 forks source link

CDCACM_::available() returns the count of what's already been read #56

Open algernon opened 2 years ago

algernon commented 2 years ago

This is not an issue in the current core, but in @bjc's bjc/gd32usb-test branch. As issues aren't available in the fork, and the feature will - hopefully - make it back here in the not too distant future, I'm opening the bug here.

The core of the issue is that CDCACM_::available() returns the count of what's already been read into the buffers, rather than what's really available, rendering the function almost useless.

To showcase the problem, use the following sketch:

#include "Arduino.h"

void setup() {
  Serial.begin(9600);
};

void loop() {
  if (Serial.available()) {
    uint8_t b = Serial.read();
    Serial.println(b);
  }
}

Feeding data onto the serial port from one terminal, and reading from the other, this currently never outputs anything.

If we change the sketch, and do a read before calling .available():

#include "Arduino.h"

void setup() {
  Serial.begin(9600);
};

void loop() {
  uint8_t b = Serial.read();
  if (Serial.available()) {
    b = Serial.read();
    Serial.println(b);
  }
}

And then feed the port with two bytes written at a time (eg, echo a >/dev/ttyACM1, which will send a newline along), we'll quickly discover that the first byte is read, and because we read more than one byte at a time into an internal buffer, .available() will return 1 too, and we'll read the second byte too.