My program stores data into a buffer and then the numbers are extracted into a 2-D array before the are place into a single integer array. The code give correct output during the first run, but during the consecutive run gives garbage value along with some correct values. Can somebody debug the program
Data RECEIVED: 42#111#106#180#81#122#88#126#55#76#92#136#145#76#180#55#$
OUTPUT:42 -27679 1249 18081 81 12288 88 12655 55 76 92 -16912 14576 76 18055 55
#include<avr/io.h>
#include<stdlib.h>
#include<stdio.h>
char store_data[65]; // acts as buffer
int values[16] = {0}; // stores numbers as integer
int flag=0;
char fcall[16][3]; // used to extract number from sting as characters
int i =0, j = 0, k=1 , x=0 , z=0, m=0,n=0;
int incomingByte=0;
void setup()
{
Serial1.begin(9600);
}
void loop()
{
if (Serial1.available())
{
flag=0;
incomingByte = Serial1.read();
if(incomingByte !='
)
{
store_data[x]=incomingByte; //store in buffer
delay(50);
Serial1.print(store_data[x]);
delay(50);
x++;
if(incomingByte == '#') //# indicates end of a number ,there are 16 # in the code
{
k++;
}
}
else if((k<16))
{
Serial1.print(" Resend Data "); //acknowledgement
k=0;
}
else if((incomingByte =='
) && (k=16)) // $ indicates end off message
{
store_data[x]=incomingByte;
delay(50);
Serial1.print(store_data[x]);
delay(50);
x++;
Serial1.print(" Data Recieved "); //acknowledgement
delay(50);
Serial1.print(k,DEC); // counts number of #
delay(50);
Serial1.print(" ");
delay(50);
Serial1.print(x,DEC); //counts number of bytes
delay(50);
Serial1.print(" ");
k=0;
x=0;
z=0;
flag = 1;
}
if (flag)
{
while(z<65)
{
if(store_data[z] == '
) // $ - End of message
{
for(m=0;m<16;m++)
{
Serial1.print(values[m],DEC);
Serial1.print(" ");
delay(100);
z=65;
}
int values[16] = {0};
fcall[i][j] = 0;
i = 0;
j = 0;
x=0;
flag=0;
}
else if(store_data[z] == '#') // # - End of a particular value
{
values[i]=atoi(fcall[i]); //converts character to number
fcall[i][j] = 0;
i++;
j = 0;
delay(2);
}
else
{
fcall[i][j] = store_data[z]; //extracts number from string bit by bit
delay(10);
j++;
}
z++;
}
}
}
}