this code is receiving either '1' or '0' through usb serial com port. If it is '1' then the LED turns on. If it is '0' the LED turns off. The following code works just fine if i use it in the file "usbd_cdc_if.c"....
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);
if(Buf[0] == '1'){
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_13, GPIO_PIN_SET);
}
else if(Buf[0] == '0'){
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_13, GPIO_PIN_RESET);
}
return (USBD_OK);
/* USER CODE END 6 */
}
But instead, i wanted to have the if statement in the "main.c" file rather than the "usbd_cdc_if.c" file. So both would look like this:
"usbd_cdc_if.c" file:
extern char serialCopy[];
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);
memcpy(serialCopy,Buf,*Len);
return (USBD_OK);
/* USER CODE END 6 */
}
"main.c" file:
char serialCopy[MAX_LEN];
while (1)
{
if(strcmp(serialCopy, "1") == 0){
HAL_GPIO_WritePin(GPIOK, GPIO_PIN_3, GPIO_PIN_SET);
}
else if(strcmp(serialCopy, "0") == 0){
HAL_GPIO_WritePin(GPIOK, GPIO_PIN_3, GPIO_PIN_RESET);
}
}
When trying to copy the variable value from "usbd_cdc_if.c" to "main.c". The LED wouldnt work when i use my method. Why? Thanks
CodePudding user response:
You changed the code. Buf[0] == '1'
does not mean the same as strcmp(serialCopy, "1") == 0
since the latter assumes a null terminated string. Characters sent over serial buses are not null terminated unless you explicitly sent them as such.
Additionally, strings entered from a terminal on a PC are followed by a line feed character \n
(*nix-like systems) or \r\n
(Windows). Meaning that strcmp("1", "1\n");
will fail even if the string is correctly null terminated.
You should view the received data in the rx buffer using a debugger to see what you actually got.
CodePudding user response:
Solved. The problem was that memcpy() in the usbd_cdc_if.c file is ony copying the data once but the loop in the main.c file keeps checking. Needed to use a global variable....
usbd_cdc_if.c file:
uint8_t newVariable = 0;
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
USBD_CDC_ReceivePacket(&hUsbDeviceFS);
newVariable = Buf[0];
return (USBD_OK);
}
main.c file:
extern uint8_t newVariable;
while (1)
{
if(newVariable == '1'){
HAL_GPIO_WritePin(GPIOK, GPIO_PIN_3, GPIO_PIN_SET);
}
else if(newVariable == '0'){
HAL_GPIO_WritePin(GPIOK, GPIO_PIN_3, GPIO_PIN_RESET);
}
}
Now, it is working. I am not sure why all my tries didnt work. Thank you.