This problem is on an Arduino Due. I am trying to populate a char array buffer that is receiving information over a serial port. I am reading the information off of the serial port and storing it into a buffer array and passing it back to the original function call.
First is the code that initializes the buffer and writes the data that the Serial requires in order to issue a response. This function compares many types of expected responses (uint32_t expect
) and returns a confirmation as an int
.
//Receive a cmd to send over serial and expect a certain response
int SendCommand(char * cmd, uint32_t expect){
int cmdSuccess = 0, j=0;
char buffer[500];
memset(&buffer,0,sizeof(buffer)); //0 out the buffer
Serial3.print(F(cmd));
delay(500);
Response(buffer);
if (expect == EXPECT_OK){
for(int i=0;i<sizeof(RESP_OK);i++){
if(buffer[i]==RESP_OK[i]){ //RESP_OK is an example of a response of length 6
j++;
}
}
if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
}
else{return 0;}
delete [] buffer;
}
void Response(char buffer[500])
{
int index = 0; //message index;
int count = 0; //used for timeouts
while(1)
{
if(Serial3.available()) //Data will be coming across serial3
{
char data = Serial3.read();
buffer[index]=data;
index++;
}
count++;
delay(100);
if(count == 50){
Serial.println(F("\nEnd of Response"));
break;
}
}
Edit: fixed the braces.
Right now, this code is hanging at the last part of Response
right before break;
. Am I having memory issues by the time it reaches the println
at the end?
That last println
was actually working until I began passing the buffer as a pointer and not returning it a char*
and declaring void Response
as char* Response
. But the problem with this approach was that the buffer
would reduce to sizeof(buffer) = 4
and would strip off the rest of the information when returned.
Edit: As Matt suggested down below, I declared a static const size_t bufferSize
and pass it into the Response()
call as well as passing in buffer
as char*
. Then I reset the buffer size by buffer = (char*)malloc(bufferSize)
.
What I still don't understand curious is the sizeof(buffer)
after Response
which is returning 4. However, 6 characters are stored into the array during Response
. I've changed the pointer call to Response(char* buffer, const int size)
with the following:
if(index<size){
buffer[index]=data;
index++;
}
else{Serial.print(F("Buffer length exceeded!"));}
Thanks so much for your time!
sizeof = 4
, leaving off some of the chars that are being read into it.