SerialEvent improvement

In version 1.0 after loop() has finished serialEventRun is called to make serial events possible (see main.cpp below)

#include <Arduino.h>
int main(void)
{
	init();
	setup();
	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
	return 0;
}
void serialEventRun(void)
{
#ifdef serialEvent_implemented
  if (Serial.available()) serialEvent();
#endif
#ifdef serialEvent1_implemented
  if (Serial1.available()) serialEvent1();
#endif
#ifdef serialEvent2_implemented
  if (Serial2.available()) serialEvent2();
#endif
#ifdef serialEvent3_implemented
  if (Serial3.available()) serialEvent3();
#endif
}

I think it would improve if the number of bytes available were passed as a parameter to serialEvent(int bytes);
That way it would not be necessary to check the available bytes in the event handler again.
If one wants to handle a single byte/char => just ignore the param

So I propose something like (removed defines for readability)

void serialEventRun(void)
{
  uint8_t count = Serial.available()
  if (count ) serialEvent(count );
  count = Serial1.available()
  if (count) serialEvent1(count);
  count = Serial2.available()
  if (count) serialEvent2(count);
  count = Serial3.available()
  if (count) serialEvent3(count);
}

Opinions why this is a bad idea?

Opinions why this is a bad idea?

Aside from the while idea of serialEvent() as a callback being silly, I see nothing wrong with passing the number of bytes available to the callback.

I'd prefer to see the use of an optional pointer, so the callback definer can define whether to be told, or not. But, that's rather confusing to newbies, so I wouldn't make it any kind of priority to do it that way.

Of course, the number of bytes available could change between when it is determined in loop() and when the callback is entered, especially at high baud rates.

Of course, the number of bytes available could change between when it is determined in loop() and when the callback is entered, especially at high baud rates.

Good point Paul,
So the parameter will give the number of bytes that are at least in the buffer, if the #bytes has increased in the mean time, they will be noticed in the "next event" OR the implementer of SerialEvent() must decide to call Serial.Available() anyway. Which I just wanted to prevent with this proposal because it was called to check if SerialEvent() had to be called anyway

point taken

Thanks,

You will always have the chance of available() returning < the actual chars available, obviously with a function call between reading and using there’s more chance but the issue is always there.

I see no problem with this, you either get those chars next time or if it really matters (unlikely) do another call to available().


Rob

The idea is posted as a proposal here - https://github.com/arduino/Arduino/issues/1190 -