Try   HackMD

2020單晶片課程:USBHost解答

USB - 簡介

Universal Serial Bus 簡稱USB,中文稱之通用性串列匯流排,目前此介面已經非常廣泛運用在PC/NB的周邊裝置,甚至是移動式裝置對外設備輸出/輸入的應用。它的價值可以透過業界的泛用與使用者的愛戴,已經有很多文件與相關網路充分說明其優勢,其身影可從電腦周邊裝置的HID (Human Interface Device) 鍵盤滑鼠、隨身碟(USB Memory Stick、Pen Storage Drive、Flash Drive)到各種影像/聲音輸出入裝置(Webcam、Microphone、DVB-T Receiver),更擴大應用至其它通訊裝置與外掛裝置(Bluetooth, Infrared, DVD burner),甚至是取代和模擬舊式通訊Serial Port (如:RS232/422/485、PS/2),進而作為當代PC的基本配備。

How usb works

USB Host & USB device

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Library

USBHost

LAB 1

Mouse 顯示滑鼠資訊,並控制LED燈

左鍵led1 ; 右鍵led2 ; 中鍵led3

hint : 使用 Thread 、 attachEvent()

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

code

#include "mbed.h" #include "USBHostMouse.h" DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); int status = 0; void onMouseEvent(uint8_t buttons, int8_t x, int8_t y, int8_t z) { printf("buttons: %d, x: %d, y: %d, z: %d\r\n", buttons, x, y, z); status = buttons; } void mouse_task(void const *) { USBHostMouse mouse; printf("mouse started\n"); while(1) { // try to connect a USB mouse while(!mouse.connect()) Thread::wait(500); // when connected, attach handler called on mouse event mouse.attachEvent(onMouseEvent); // wait until the mouse is disconnected while(mouse.connected()) Thread::wait(500); printf("mouse seen disconnected\n"); } } int main() { Thread mouseTask(mouse_task); while(1) { if (status == 1){ led1=1; led2=0; led3=0; }else if (status == 2){ led1=0; led2=1; led3=0; } else if (status == 4){ led1=0; led2=0; led3=1; }else{ led1=0; led2=0; led3=0; } Thread::wait(100); } }

LAB 2

Keyboard 顯示使用者輸入字母或符號

hint : attach()

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

code

#include "mbed.h" #include "USBHostKeyboard.h" void onKey(uint8_t key) { printf("Key: %c\r\n", key); } void keyboard_task(void const *) { USBHostKeyboard keyboard; while(1) { // try to connect a USB keyboard while(!keyboard.connect()) Thread::wait(500); // when connected, attach handler called on keyboard event keyboard.attach(onKey); // wait until the keyboard is disconnected while(keyboard.connected()) Thread::wait(500); } } int main() { Thread keyboardTask(keyboard_task); while(1) { } }