Fix Serial.available() returning -1 on all CH32 series MCUs #225
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
The current HardwareSerial implementation has
Serial.available()
hardcoded to return-1
, making it impossible to use standard Arduino serial patterns like echo loops or data polling. This affects all CH32 series MCUs (CH32V003, CH32V203, CH32X035, CH32V103, CH32V307).Root Cause
available()
function returns-1
instead of the actual byte countNo RX buffering implementation
No interrupt-driven reception
Solution
This PR implements proper UART RX buffering with interrupt handlers for all CH32 series MCUs while maintaining backwards compatibility with other Arduino cores.
Changes Made
Added conditional RX buffering - Only enabled for CH32 series MCUs
Implemented interrupt handlers - For all UART variants (USART1-8, UART4-8)
Fixed core functions:
available()
- Returns actual buffered byte countpeek()
- Returns next byte without consuming itread()
- Reads from interrupt-filled bufferMaintained compatibility - Non-CH32 MCUs use original behaviour
Safe implementation - Only creates handlers for existing Serial objects
Technical Details
64-byte RX buffer per UART with overflow protection
Conditional compilation prevents linker errors
Interrupt priority set to 2 for all UARTs
Buffer variables are only allocated on CH32 MCUs
Testing
Verified on CH32X035 board
Serial.available()
now returns0
when no data (instead of-1
)Echo functionality works correctly
No compilation errors on any supported MCU
Backward Compatibility
Zero impact on existing projects
Non-CH32 Arduino cores unchanged
Existing CH32 code works without modification
Before:
Serial.available(); // Always returned -1
After:
Serial.available(); // Returns actual byte count (0, 1, 2, etc.)
Tested on CH32X035