1
- // Serial, Serial1 and Serial2 are all of the type HardwareSerial.
1
+ # define BUFFER_SIZE 8
2
2
3
- static void IRAM_ATTR onSerialRX (uint8_t c, void * user_arg){
4
- Serial.print (c);
3
+ static volatile char inputBuffer[BUFFER_SIZE];
4
+ static volatile size_t inputBufferLength = 0 ;
5
+
6
+ // Please keep in mind, since the ESP32 is dual core,
7
+ // the interrupt will be running on the same core as the setRxInterrupt function was called on.
8
+ static void IRAM_ATTR onSerialRX (uint8_t character, void * user_arg){
9
+
10
+ // Cast the user_arg back to a array
11
+ char [] buffer = (char *)user_arg;
5
12
6
- // Cast the user_arg containing a void* to the Serial device, to HardwareSerial* to be used
7
- HardwareSerial* serial = (HardwareSerial*)user_arg ;
8
- serial-> print (c);
13
+ if (inputBufferLength < BUFFER_SIZE){
14
+ buffer[inputBufferLength++] = (char )character ;
15
+ }
9
16
}
10
17
11
18
void setup ()
@@ -14,11 +21,22 @@ void setup()
14
21
Serial2.begin (115200 );
15
22
16
23
// The user_arg is expected to be a void pointer (void*),
17
- // so take the reference of Serial2 , and cast the HardwareSerial* to a void*
18
- Serial2.setRxInterrupt (onSerialRX, (void *)&Serial2);
24
+ // so take the reference of the variable , and it to a void*
25
+ Serial2.setRxInterrupt (onSerialRX, (void *)&inputBuffer);
19
26
}
20
27
21
28
void loop ()
22
- {
23
- delay (1 );
29
+ {
30
+ if (inputBufferLength == (BUFFER_SIZE - 1 )){
31
+ for (size_t i = 0 ; i < inputBufferLength; i++){
32
+ Serial.write (inputBuffer[i]);
33
+
34
+ // Clear the buffer
35
+ inputBuffer[i] = ' \0 ' ;
36
+ }
37
+ // Clear the bufferLength
38
+ inputBufferLength = 0 ;
39
+ }
40
+
41
+ delay (1000 ); // Wait for one second
24
42
}
0 commit comments