Skip to content

Commit 6339e26

Browse files
committed
Handle Stlink V21.
1 parent 8cbdffe commit 6339e26

File tree

1 file changed

+61
-2
lines changed

1 file changed

+61
-2
lines changed

src/main.c

+61-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
#define STLINK_VID 0x0483
3030
#define STLINK_PID 0x3748
31+
#define STLINK_PIDV21 0x374b
3132

3233
void print_help(char *argv[]) {
3334
printf("Usage: %s [options] [firmware.bin]\n", argv[0]);
@@ -37,6 +38,63 @@ void print_help(char *argv[]) {
3738
printf("\tApplication is started when called without argument or after firmware load\n\n");
3839
}
3940

41+
#include <string.h>
42+
#define USB_TIMEOUT 5000
43+
int stlink_dfu_mode(libusb_device_handle *dev_handle, int trigger) {
44+
unsigned char data[16];
45+
int rw_bytes, res;
46+
47+
memset(data, 0, sizeof(data));
48+
49+
data[0] = 0xF9;
50+
if (trigger) data[1] = 0x10;
51+
/* Write */
52+
res = libusb_bulk_transfer(dev_handle,
53+
1 | LIBUSB_ENDPOINT_OUT,
54+
data,
55+
sizeof(data),
56+
&rw_bytes,
57+
USB_TIMEOUT);
58+
if (res) {
59+
fprintf(stderr, "USB transfer failure\n");
60+
return -1;
61+
}
62+
if (!trigger) {
63+
/* Read */
64+
libusb_bulk_transfer(dev_handle,
65+
1 | LIBUSB_ENDPOINT_IN,data,
66+
2,
67+
&rw_bytes,
68+
USB_TIMEOUT);
69+
if (res) {
70+
fprintf(stderr, "stlink_read_infos() failure\n");
71+
return -1;
72+
}
73+
}
74+
return data[0] << 8 | data[1];
75+
}
76+
77+
int test_v21(libusb_context *usb_ctx)
78+
{
79+
libusb_device_handle *dev_handle;
80+
int res = 0;
81+
dev_handle = libusb_open_device_with_vid_pid(usb_ctx,
82+
STLINK_VID,
83+
STLINK_PIDV21);
84+
if (dev_handle) {
85+
fprintf(stderr, "StlinkV21 found\n");
86+
res = stlink_dfu_mode(dev_handle, 0);
87+
if (res != 0x8000) {
88+
libusb_release_interface(dev_handle, 0);
89+
return 0;
90+
}
91+
stlink_dfu_mode(dev_handle, 1);
92+
libusb_release_interface(dev_handle, 0);
93+
}
94+
usleep(1000000);
95+
return 1;
96+
}
97+
4098
int main(int argc, char *argv[]) {
4199
libusb_context *usb_ctx;
42100
libusb_device_handle *dev_handle;
@@ -63,7 +121,8 @@ int main(int argc, char *argv[]) {
63121

64122
res = libusb_init(&usb_ctx);
65123
(void)res;
66-
124+
/* Test for V21 device and sitch to DFU mode */
125+
test_v21(usb_ctx);
67126
dev_handle = libusb_open_device_with_vid_pid(usb_ctx,
68127
STLINK_VID,
69128
STLINK_PID);
@@ -103,7 +162,7 @@ int main(int argc, char *argv[]) {
103162
}
104163
printf("Current mode : %d\n", res);
105164

106-
if (res != 1) {
165+
if (res & 0xfffc) {
107166
printf("ST-Link dongle is not in the correct mode. Please unplug and plug the dongle again.\n");
108167
libusb_release_interface(dev_handle, 0);
109168
return EXIT_SUCCESS;

0 commit comments

Comments
 (0)