I am trying to use a byte array as a buffer in Serial.readBytes (Arduino IDE 1.0.5-r2):
byte serialData[10];
int nBytes = 0;
nBytes = Serial.readBytes(serialData,10);
but it fails with the following error message:
error: invalid conversion from 'byte*' to 'char*'
error: initializing argument 1 of 'size_t Stream::readBytes(char*, size_t)'
...even though the Serial.readBytes reference page states:
Serial.readBytes(buffer, length)
buffer: the buffer to store the bytes in (char[] or byte[])
length : the number of bytes to read (int)
What am I missing?
Hi Zoran
You can cast the pointer from byte pointer to char pointer:
nBytes = Serial.readBytes((char*)serialData,10);
But I appreciate that doesn't answer your question on why the reference page talks about byte[ ].
Regards
Ray
That is an Arduino foul up on the documentation I think, but it is still correct... sort of,
IDE 1.0.x Stream.h
https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/Stream.h#L76
IDE 1.5.x
bool find(char *target); // reads data from the stream until the target string is found
bool find(uint8_t *target) { return find ((char *)target); }
// returns true if target string is found, false if timed out (see setTimeout)
bool find(char *target, size_t length); // reads data from the stream until the target string of given length is found
bool find(uint8_t *target, size_t length) { return find ((char *)target, length); }
// returns true if target string is found, false if timed out
bool find(char target) { return find (&target, 1); }
bool findUntil(char *target, char *terminator); // as find but search ends if the terminator string is found
bool findUntil(uint8_t *target, char *terminator) { return findUntil((char *)target, terminator); }
bool findUntil(char *target, size_t targetLen, char *terminate, size_t termLen); // as above but search ends if the terminate string is found
bool findUntil(uint8_t *target, size_t targetLen, char *terminate, size_t termLen) {return findUntil((char *)target, targetLen, terminate, termLen); }
long parseInt(LookaheadMode lookahead = SKIP_ALL, char ignore = NO_IGNORE_CHAR);
// returns the first valid (long) integer value from the current position.
// lookahead determines how parseInt looks ahead in the stream.
// See LookaheadMode enumeration at the top of the file.
You can see in the 1.5.x versions, the uint8_t methods have been added. ( uint8_t is byte, or unsigned char ), and you can see the 1.0.x versions only support char.
It only wraps the old function and does the cast for you. Might as well keep your code portable and add in the cast posted by Ray yourself.
Thanks guys. Works for me.
md3848
July 7, 2015, 12:13pm
5
incorrect
nBytes = Serial.readBytes(DATA,10);
correct
Serial.readBytes(DATA,10);
data save in DATA>>>> then , what is nBytes >>> O_o