I’m a beginner with C++ and trying to create a program for my Arduino. The code below compiles fine, but the result is different from what I expect it to be.
What I expect to receive on my PC is: 0x04 , 0x61 , 0x62 , 0x63.
What I receive on my PC is: 0xff 0x00 0xb1 0x00.
I tried to minimize the code in such a way that it only addresses the problem that I run in to.
byte *assembleFrame() {
byte frame[] = { 4 , 'a' , 'b' , 'c' , 'd' };
return frame;
}
void setup() {
Serial.begin( 115200 );
};
void loop() {
byte *frame = assembleFrame();
Serial.write( frame , 4 );
// should send 0x04 0x61 0x62 0x63, leaving out 0x64 being 5th element.
while ( 1 ) {
}
}
I think it has something to do with pointers, but can’t figure it out.
FYI:
Serial.write( buf , len ) arguments:
buf: an array to send as a series of bytes
len: the length of the buffer
EDIT:
Solution so far:
int assembleFrame( byte *frame ) {
int octetCounter = 0;
frame[ octetCounter++ ] = 'A'; // preamble
frame[ octetCounter++ ] = 'B'; // preamble
frame[ octetCounter++ ] = 0; // frame length set at end of function
frame[ octetCounter++ ] = h;
frame[ octetCounter++ ] = m;
frame[ octetCounter++ ] = s;
frame[ 2 ] = octetCounter; // frame length
return frame[ 2 ];
}
void loop() {
int bytes_in_frame = assembleFrame( frame );
Serial.write( frame, bytes_in_frame ); // assuming ptr + bytes to send
delay( 1000 );
}
It gives the desired result.
+Krister’s answer is a good one, I would improve on it by suggesting you pass the buffer into your assembly function, if at all possible.
That way you don’t create the possibility of a memory leak later on.