Jei naudojamas STM32 čipas palaiko USB HOST režimą, tai prijungti USB įrenginį labai paprasta. Mano hardwarė labai paprasta- čipas ir dvi USB jungtys. Viena jungtis suprogramuota kaip virtualus COM portas skirta peržiūrėti rezultatus, o kita USB jungtis tai USB host. Čia galima prijungti pelę ir klavietūrą. Kiti HID įrenginiai nepalaikomi.
Primenu, kad HID klavietūra palaiko iki 6 klavišų nuspaudimus (neįskaitant modifikatorius: shift, control, alt…) ir atskirai siunčiami klavišų paspaudimai ir atleidimai.
Kad viskas veiktu, tereikia savo programoje pasirašyti callbacką:
void USBH_HID_EventCallback(USBH_HandleTypeDef *phost) { char txt_buf[100]; char t[4]; strcpy(t,"[x]"); if(USBH_HID_GetDeviceType(phost) == HID_MOUSE) // if the HID is Mouse { HID_MOUSE_Info_TypeDef *Mouse_Info; Mouse_Info = USBH_HID_GetMouseInfo(phost); // Get the info int8_t dX_Val = Mouse_Info->x; // get the delta x value (note unsigned - signed conversion) int8_t dY_Val = Mouse_Info->y; // get the delta y value int len = sprintf (txt_buf, "dX=%d, dY=%d, Button1=%d, Button2=%d, Button3=%d\r\n", dX_Val, dY_Val, Mouse_Info->buttons[0],Mouse_Info->buttons[1], Mouse_Info->buttons[2]); user_usb_tx((uint8_t *) txt_buf,len); } if(USBH_HID_GetDeviceType(phost) == HID_KEYBOARD) { HID_KEYBD_Info_TypeDef *Keyboard_Info; Keyboard_Info = USBH_HID_GetKeybdInfo(phost); // get the info txt_buf[0]=0; unsigned char i; for(i=0;i<6;i++) { if(Keyboard_Info->keys[i] != OLDKEYS[i] ) { if (Keyboard_Info->keys[i]==0) {strcat(txt_buf,"UPKEY:"); hex8(txt_buf,OLDKEYS[i]);t[1]=Scan2Char(OLDKEYS[i]); strcat(txt_buf,t);} else if (OLDKEYS[i]==0) {strcat(txt_buf,"DOWNKEY:"); hex8(txt_buf,Keyboard_Info->keys[i]);t[1]=Scan2Char(Keyboard_Info->keys[i]); strcat(txt_buf,t);} else {strcat(txt_buf,"ERR:"); hex8(txt_buf,Keyboard_Info->keys[i]); strcat(txt_buf,"-");hex8(txt_buf,OLDKEYS[i]);} } OLDKEYS[i]=Keyboard_Info->keys[i]; } strcat(txt_buf,"\r\n"); user_print_usb( txt_buf); } }
Pačiam HID reporte visada transliuojami visi nuspausti klavišai, todėl, jei reikia susiderinti su PS2 ar senesniu standartu, reikia tikrinti, koks klavišas nuspaustas ir koks paleistas. Ta daro ciklas 24-33 eilutėse.
Rezultatas:
UPKEY:12[o] DOWNKEY:13[p] UPKEY:13[p] DOWNKEY:2F[[] UPKEY:2F[[] DOWNKEY:30[]] UPKEY:30[]] DOWNKEY:31[\] UPKEY:31[\] DOWNKEY:04[q] DOWNKEY:16[s] DOWNKEY:07[d] DOWNKEY:09[f] DOWNKEY:2C[ ] UPKEY:16[s] UPKEY:07[d] UPKEY:09[f] UPKEY:04[q] UPKEY:2C[ ] DOWNKEY:0B[h] UPKEY:0B[h]
Visas demo softo source code čia: STM32CubeMX USB host HID demo source code.