After thinking about this problem I figured that it would be plain odd if the Serial class didn't support byte pointers instead of arrays. Hoping I could create one I found the following:
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while (size--) {
n += write(*buffer++);
}
return n;
}
This code seems to do exactly what you want! So why didn't you get it to work? I tried myself and modified my sketch above to be able to test it with the same console app. It works! Don't be thrown off by the "Print" class, the Serial class borrows this function.
This is the sketch now, it produces exactly the same results:
unsigned long data = 4294967295;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.write((byte*)&data, sizeof(data));
data -= 1;
delay(3000);
}
The address-of operator will convert the variable into a pointer (of the same type) which you can then cast to a byte pointer.
Maybe I should have looked into this a little more but I guess that the documentation threw me off.
Something else I noticed is that the HardwareSerial class contains this:
inline size_t write(unsigned long n) { return write((uint8_t)n); }
inline size_t write(long n) { return write((uint8_t)n); }
inline size_t write(unsigned int n) { return write((uint8_t)n); }
inline size_t write(int n) { return write((uint8_t)n); }
So basically this casts unsigned and signed longs and ints to byte when calling HardwareSerial.write. This made me scratch my head a little, is it just me or will you never want to do that? :
Anyway, the Serial_ class (which is defined in USBAPI.h) doesn't have these overloads so I decided to create them:
inline size_t write(unsigned long n) { return write((byte*)&n, sizeof(n)); }
inline size_t write(unsigned int n) { return write((byte*)&n, sizeof(n)); }
Inserting that code into the public section of USBAPI.h will allow you to do this:
unsigned long int32 = 4294967295;
unsigned int int16 = 65535;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.write(int32--); // Writes 4 bytes
Serial.write(int16--); // Writes 2 bytes
delay(3000);
}
So tell me Arduino community, what do you think? Do you think these simple adaptations will benefit everybody? My take is that this would definitely suit the expectations of consumers of the Serial_ class, especially for beginners.
Who exactly architects and maintains the Arduino core source code? Is that team open for pull requests on Github? And what about those potentially unwanted casts in the HardwareSerial classes?