getnewpacket

closed account (4w7X92yv)
Hello

This is a piece of code from serial communication.
It gets data from the usb and returns them.
The problem is that it for some reason places ffffff at random pieces of the correct code.
How can i adjust it so it forgets the ffffff?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
std::string getNewPacket()
{
  std::string code;
  char recvBuffer[40];
  DWORD dwBytesRead;
  static char totalBuffer[2048];
  static int nextBytePosition = 0;
  
  while(1)
  {
      if(!ReadFile(hSerial, recvBuffer, sizeof(recvBuffer), &dwBytesRead, NULL)) 

      {
          cout << "Error during reading" << endl;
          break;
      }
      if (dwBytesRead == 0)
      {
          break;
      }
      else
      { 

          memcpy(&totalBuffer[nextBytePosition], recvBuffer, dwBytesRead);
          nextBytePosition += dwBytesRead;
      }
  }

  int stop = 0;

  int state = 0;

  for(int i = 0 ; (i < nextBytePosition) && (stop == 0) ; i++)
  {         
      switch(state)
      {
          case 0:
               if(totalBuffer[i] == 0x10) 
               {
                   state = 1;
               }
               break;
               
          case 1:
               if(totalBuffer[i] == 0x10)
               {          
                   i++;
                   stop = 1;    
  
                   for(int j = 0 ; j <= i ; j++)
                   {
                       char temp[5];
                       sprintf(temp, "%.2x", totalBuffer[j]);
                       code.append(temp);
                   }

                   memmove(&totalBuffer[0], &totalBuffer[i + 1], sizeof(totalBuffer) - (i + 1));
                   nextBytePosition -= (i + 1);
               }  
               break;
               
      }
  }
  return code;
}
closed account (4w7X92yv)
help
It's not clear what that algorithm's doing.

Can you describe what you want to do, then we can check the implementation.
closed account (4w7X92yv)
the serial communication is devided in 3 parts: opening, sending to it and recieving. this part has to recieve data from the serial port and returns the data recieved from the port as the string code.

only problem with it is that i think that there is something wrong with it: it places randoms f's inside the string recieved from the port.

so my question is: it the code wrong, is some sort of filter forgotten? , ....
Line 57 is the problem. You got memmove wrong. Look at this:

http://www.cplusplus.com/reference/clibrary/cstring/memmove/

the third parameter is number of bytes to copy. So

memmove(&totalBuffer[0], &totalBuffer[i + 1], sizeof(totalBuffer) - (i + 1));
Topic archived. No new replies allowed.