I am new to the embedded programming. I am doing a UART communication in PIC32MX795F512L
MCU. I have somehow managed to transmit and receive data but not able to receive complete string.
I am doing something like this:
char Rx[5] ; //variable to store rx data
int i;
for(i=0;i<=4;i++)
{
while(!DataRdyUART1()); //This check if data is ready to be received
Rx[i] = getcUART1(); //This get one character from UART
}
putsUART1(Rx); //Putting all the Rx data on UART
But whats happening is If I type 12345
then I get 123452345&+
its taking the last values. Again if I type asdfg
then I get asdfg2345&+
. After the 5th character, its showing some garbage values.
This should not happen. I don't know why its taking up 2345&+
. How can I remove this. Please help. Thanks.!
-
\$\begingroup\$ This is a classic buffer overflow... \$\endgroup\$Paebbels– Paebbels2015年12月05日 14:30:16 +00:00Commented Dec 5, 2015 at 14:30
-
\$\begingroup\$ @Paebbels No, it is a classic "the programmer has not grasped string null termination" beginner bug... \$\endgroup\$Lundin– Lundin2015年12月07日 12:08:42 +00:00Commented Dec 7, 2015 at 12:08
1 Answer 1
The string needs to be zero terminated so that the sending function, putsUART1
, knows when it's reached the end. So make your array one character larger and add a null (zero) at the end.
Something like this:
char Rx[6] ; //variable to store rx data
int i;
for(i=0;i<=4;i++)
{
while(!DataRdyUART1()); //This check if data is ready to be received
Rx[i] = getcUART1(); //This get one character from UART
}
Rx[5] = 0; // add null terminator
putsUART1(Rx); //Putting all the Rx data on UART