OutbreakInc / nitride

A new approach to embedded development.
11 stars 5 forks source link

The io.serial.write code does not handle byte variables #10

Open IanAber opened 11 years ago

IanAber commented 11 years ago

The code supplied handles signed char types but treats everything else as an integer and tries to send the ASCII representation of it. The header declares several format types but only Character is handled. I reworked the code to use a case statement to handle byte and char as single characters and everything else as numeric. The case statement allows further differentiation for more types to be added.

I also changed the type of buffer used by the NumberFormatter to byte from char to keep it simple.

Here is the original and the reworked code lifted from GalagoAPI.cpp

// IanA - Rewritten to handle the other types such as unsigned byte. /Task IO::UART::write(unsigned int w, IO::UART::Format format) { char buffer[11]; int length = 0; if(format == Character) { buffer[0] = (char)w; length = 1; } else { length = NumberFormatter::format( buffer, w, ((int)format) & ~1, (((int)format) & 1)? NumberFormatter::DecimalSigned : NumberFormatter::DecimalUnsigned ); } return(write((byte const)buffer, length)); } */ // IanA - Rewritten to use a case statement for expandability to other types (see above) Task IO::UART::write(unsigned int w, IO::UART::Format format) { byte buffer[11]; int length = 0;

switch(format)
{
    case Character      :   ;
    case UnsignedByte   :   buffer[0] = (byte)w;
                            length = 1;
                            break;
    default             :   length = NumberFormatter::format(buffer, w, ((int)format) & ~1, 
                                            (((int)format) & 1)? NumberFormatter::DecimalSigned : NumberFormatter::DecimalUnsigned);
                            break;
}
return(write(buffer, length));

}

And NumberFormatter changes...

class NumberFormatter { public: typedef enum { Hexadecimal = 16, DecimalUnsigned = 10, DecimalSigned = 11 } Base;

// IanA - Changed parameter to byte* from char* so it correctly handles 8 bit characters
static int      format(byte* output, unsigned int number, int fractionBits, Base base)
{
    static char const charTable[] = "0123456789ABCDEF";
kuym commented 11 years ago

Could you fork, edit, test and submit a pull request for this one too? Thanks!