28
28
29
29
#define STLINK_VID 0x0483
30
30
#define STLINK_PID 0x3748
31
+ #define STLINK_PIDV21 0x374b
31
32
32
33
void print_help (char * argv []) {
33
34
printf ("Usage: %s [options] [firmware.bin]\n" , argv [0 ]);
@@ -37,6 +38,63 @@ void print_help(char *argv[]) {
37
38
printf ("\tApplication is started when called without argument or after firmware load\n\n" );
38
39
}
39
40
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
+
40
98
int main (int argc , char * argv []) {
41
99
libusb_context * usb_ctx ;
42
100
libusb_device_handle * dev_handle ;
@@ -63,7 +121,8 @@ int main(int argc, char *argv[]) {
63
121
64
122
res = libusb_init (& usb_ctx );
65
123
(void )res ;
66
-
124
+ /* Test for V21 device and sitch to DFU mode */
125
+ test_v21 (usb_ctx );
67
126
dev_handle = libusb_open_device_with_vid_pid (usb_ctx ,
68
127
STLINK_VID ,
69
128
STLINK_PID );
@@ -103,7 +162,7 @@ int main(int argc, char *argv[]) {
103
162
}
104
163
printf ("Current mode : %d\n" , res );
105
164
106
- if (res != 1 ) {
165
+ if (res & 0xfffc ) {
107
166
printf ("ST-Link dongle is not in the correct mode. Please unplug and plug the dongle again.\n" );
108
167
libusb_release_interface (dev_handle , 0 );
109
168
return EXIT_SUCCESS ;
0 commit comments