Difference between revisions of "Serial Debugging"

From Stm32World Wiki
Jump to navigation Jump to search
Line 1: Line 1:
 
[[Category:STM32]][[Category:STM32 Development]][[Category:STM32CubeMX]][[Category:STM32CubeIde]][[Category:STM32 HAL]]{{metadesc|How to redirect printf to USB Serial Port}}
 
[[Category:STM32]][[Category:STM32 Development]][[Category:STM32CubeMX]][[Category:STM32CubeIde]][[Category:STM32 HAL]]{{metadesc|How to redirect printf to USB Serial Port}}
Redirecting printf to a Virtual COM port is really easy:
+
Creating and using a virtual COM port over USB is really easy (provided the USB port is not used for anything else).
 +
 
 +
First step is to enable USB in device mode under Connectivity in [[STM32CubeMX]]:
 +
 
 +
[[File:USB Mode.png|400px]]
 +
 
 +
Next, set the USB Device Middleware to Communication Device Class:
 +
 
 +
[[File:USB Device Mode and Configuration.png|400px]]
 +
 
 +
Generating code and the device should now show up as a virtual COM port.
 +
 
 +
Final step is to redirect output from "printf" to go to this virtual COM port rather than one of the UARTS.
  
 
<pre>
 
<pre>
Line 6: Line 18:
 
     CDC_Transmit_FS((uint8_t *)ptr, len);
 
     CDC_Transmit_FS((uint8_t *)ptr, len);
 
     return len;
 
     return len;
 +
}
 +
</pre>
 +
 +
You can now use printf to print debugging statements - for example:
 +
 +
<pre>
 +
uint32_t then = 0, now = 0;
 +
 +
while (1) {
 +
 +
now = HAL_GetTick();
 +
if (now % 1000 == 0 && now != then) {
 +
 +
printf("Tick (now = %lu)\n", now / 1000);
 +
 +
then = now;
 +
 +
}
 +
 +
}
 
}
 
}
 
</pre>
 
</pre>

Revision as of 05:24, 30 April 2021

Creating and using a virtual COM port over USB is really easy (provided the USB port is not used for anything else).

First step is to enable USB in device mode under Connectivity in STM32CubeMX:

USB Mode.png

Next, set the USB Device Middleware to Communication Device Class:

USB Device Mode and Configuration.png

Generating code and the device should now show up as a virtual COM port.

Final step is to redirect output from "printf" to go to this virtual COM port rather than one of the UARTS.

int _write(int file, char *ptr, int len) {
    CDC_Transmit_FS((uint8_t *)ptr, len);
    return len;
}

You can now use printf to print debugging statements - for example:

	uint32_t then = 0, now = 0;

	while (1) {

		now = HAL_GetTick();
		if (now % 1000 == 0 && now != then) {

			printf("Tick (now = %lu)\n", now / 1000);

			then = now;

		}

	}
}