Hardware Serial: Passing serial.read() into a own function

Hi all, I've got a problem which I can't solve by my slefe, so maybee one of you can give me some support.

I'm reading on serial from SIM chip. Sometimes the Arduino reads chars which are no ascii's. It's not because SIM it's transmitting streamed data, it's an error in the connection. I know it would be best do become the connection that good, that there will not be any errors, but this is not possible.

So I will catch the response from the SIM by checking each received char from serial.read() with the isAscii() function. This is fine so far.

It would be no problem to just write a new function like this:

char SerialReadAscii(int error) { char b = 0; b = Serial.read(); if(isAscii(b) { return b; } else { error++; return b; }

}

I don't like this option, because this function i would need for each Serial Port like Serial1, Serial2,...

My question is now, how can I create something like a Sub Class to use it like Serial.readAscii() without changing the hardwareserial stuff. I would like to pass the Serial.read() into a new Serial.readAscii(). I think this should be possible and is more a C++ subject. But I can't do it by myselfe.

Thanks for your support!

BR!

Just have it take a Stream reference. The Serial objects are instances of classes that all inherit from the Stream class.

char readAscii(Stream &s, unsigned int &errors) {
    char b = s.read();
    if (!isAscii(b))
        errors++;
    return b;
}
static unsigned int errors = 0;
char c = readAscii(Serial, errors);

I don't really see the added benefit of that function, though , you still need to check if it was an error.

Pieter

How about this?

int SerialReadAscii(Stream &stream, char &cCh)
{
   int nError = 0;

   cCh = stream.read();
   
   if (!isAscii(b)
   {
        nError ++;
    }
    return nError;
}

char cCh = 0;

while (SerialReadAscii(Serial, cCh) == 0)
    Serial.print(cCh)