From e2a9e7f81b04f77c4ea4fc10339f63a19a201038 Mon Sep 17 00:00:00 2001 From: liu shiwei Date: Wed, 9 Mar 2022 17:22:10 +0800 Subject: [PATCH] add Serial rx callback function example: //return false drop char, bool rxcap(char ch) { if (ch == '1') { //if get char '1' Serial.println("callback!"); Serial.setRxCallBack(0); //disable CallBack return false; //del char '1' from rx buff } return true; } void setup() { Serial.begin(115200); Serial.setRxCallBack(rxcap); } void loop() { while(Serial.available()) Serial.write(Serial.read()); } ~ --- cores/arduino/HardwareSerial.h | 3 ++- cores/arduino/HardwareSerial_private.h | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/cores/arduino/HardwareSerial.h b/cores/arduino/HardwareSerial.h index 6ff29d0b9..6793d46f0 100644 --- a/cores/arduino/HardwareSerial.h +++ b/cores/arduino/HardwareSerial.h @@ -106,6 +106,7 @@ class HardwareSerial : public Stream volatile rx_buffer_index_t _rx_buffer_tail; volatile tx_buffer_index_t _tx_buffer_head; volatile tx_buffer_index_t _tx_buffer_tail; + bool (*_rxcallback)(char); // Don't put any members after these buffers, since only the first // 32 bytes of this struct can be accessed quickly using the ldd @@ -137,8 +138,8 @@ class HardwareSerial : public Stream // Interrupt handlers - Not intended to be called externally inline void _rx_complete_irq(void); void _tx_udr_empty_irq(void); + void setRxCallBack( bool (*CallBackFun)(char)) { _rxcallback = CallBackFun; } }; - #if defined(UBRRH) || defined(UBRR0H) extern HardwareSerial Serial; #define HAVE_HWSERIAL0 diff --git a/cores/arduino/HardwareSerial_private.h b/cores/arduino/HardwareSerial_private.h index 2e23cec0c..b3771417a 100644 --- a/cores/arduino/HardwareSerial_private.h +++ b/cores/arduino/HardwareSerial_private.h @@ -92,7 +92,8 @@ HardwareSerial::HardwareSerial( _ucsra(ucsra), _ucsrb(ucsrb), _ucsrc(ucsrc), _udr(udr), _rx_buffer_head(0), _rx_buffer_tail(0), - _tx_buffer_head(0), _tx_buffer_tail(0) + _tx_buffer_head(0), _tx_buffer_tail(0), + _rxcallback(0) { } @@ -104,6 +105,8 @@ void HardwareSerial::_rx_complete_irq(void) // No Parity error, read byte and store it in the buffer if there is // room unsigned char c = *_udr; + if(_rxcallback != 0 && !_rxcallback(c)) + return; rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE; // if we should be storing the received character into the location