-2

I have a problem while using serial communication for USB CDC. I'm working on embedded STM microcontrollers and i wanted to pass binary data with pySerial.

I wanted to send binary codes directly but I am blocked by this 0x00 .. My problem is when i want to send 0x00 byte, the next bytes seems to be ignored..

Here's the python script:

towrite = [ 0xFF, 0xx00 \xFF ] 
nbSend = s.write(b'\xFF\x00\xFF')
print(nbSend)                                 #Displaying 3 here, that means 3 bytes are successfully sended

Then the embedded script:

//Interrupt function that receive the data from serial com
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
  USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  USBD_CDC_ReceivePacket(&hUsbDeviceFS);

  char buffer[64];

  sprintf(buffer,"Length=%lu / Word=%c%c%c ",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);
  debugPrintln(&huart2, buffer)  //Function to print on serial to debug
  //Here that print "Length=3 / Word=ΓΏ "


  return (USBD_OK);
  /* USER CODE END 6 */
}

As you can see, the second and ultimate characters (0x00, 0xFF) are not taken into account even if the number of bytes received is good ... Any advice?

  • The null character terminates the string. Nothing after that is usable to `sprintf` – TomServo Jun 01 '20 at 00:02
  • Do not use a print function that expects _strings_, when attempting to print characters will a null byte. – chux - Reinstate Monica Jun 01 '20 at 00:02
  • Looks like your UART data is binary. `%c` won't print it too well (e.g. there's no viewable/printable ASCII char for that for 0x00 or 0xFF). How about (e.g.): `"Length=%lu / Word=%2.2X,%2.2X,%2.2X "`? – Craig Estey Jun 01 '20 at 00:03

1 Answers1

0

It's the debugging that's not working, but the data transfer is just fine.

sprintf(buffer,"Length=%lu / Word=%c%c%c ",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);

The second %c puts an actual NUL byte in the buffer, so everything else after it is ignored by the debugPrintln.

For testing, change to:

sprintf(buffer,"Length=%lu / Word=%02X %02X %02X",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);

and see if it shows you all the bytes.

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30