總瀏覽量

2012年9月20日 星期四

Arduino USB Keyboard = Arduino UNO + USB Host shield + USB keyboard

這次把做好許久的Arduino USB keyboard的做法及程式公開, 讓想學如何用USB host連接 keyboard的網友做參考(有不少網友寫mail來希望可以post出來).

DIY的材料:
1. Arduino UNO or compatible
2. USB host shield
3. USB keyboard

參考連接圖:



程式如下:  完整程式 (sketch)
------------------------------------------------------

#include <avr/pgmspace.h>

#include <avrpins.h>
#include <max3421e.h>
#include <usbhost.h>
#include <usb_ch9.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <address.h>
#include <hidboot.h>

#include <printhex.h>
#include <message.h>
#include <hexdump.h>
#include <parsetools.h>

class KbdRptParser : public KeyboardReportParser
{
        void PrintKey(uint8_t mod, uint8_t key);
        
protected:
virtual void OnKeyDown (uint8_t mod, uint8_t key);
virtual void OnKeyUp (uint8_t mod, uint8_t key);
virtual void OnKeyPressed(uint8_t key);
};

USB     Usb;
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);
uint32_t next_time;
KbdRptParser Prs;

void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
    MODIFIERKEYS mod;
    *((uint8_t*)&mod) = m;
    Serial.print((mod.bmLeftCtrl   == 1) ? "C" : " ");
    Serial.print((mod.bmLeftShift  == 1) ? "S" : " ");
    Serial.print((mod.bmLeftAlt    == 1) ? "A" : " ");
    Serial.print((mod.bmLeftGUI    == 1) ? "G" : " ");
    
    Serial.print(" >");
    PrintHex<uint8_t>(key);
    Serial.print("< ");

    Serial.print((mod.bmRightCtrl   == 1) ? "C" : " ");
    Serial.print((mod.bmRightShift  == 1) ? "S" : " ");
    Serial.print((mod.bmRightAlt    == 1) ? "A" : " ");
    Serial.println((mod.bmRightGUI    == 1) ? "G" : " ");
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
    Serial.print("DN ");
    PrintKey(mod, key);
    uint8_t c = OemToAscii(mod, key);
    
    if (c)
        OnKeyPressed(c);
}

void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
    Serial.print("UP ");
    PrintKey(mod, key);
}

void KbdRptParser::OnKeyPressed(uint8_t key)
{
  int moveSteps;
    Serial.print("ASCII: ");
    Serial.println((char)key);
}

void setup()
{
    Serial.begin(115200);
    Serial.println("Start.......");

    if (Usb.Init() == -1)
        Serial.println("Usb initial falied");
      
    delay( 200 );
  
    next_time = millis() + 5000;
  
    Keyboard.SetReportParser(0, (HIDReportParser*)&Prs);

}

void loop()
{
    Usb.Task();
}


---------------------------------------------

Video(control stepper motors) : http://www.youtube.com/watch?v=z4d_EpXNxgo


沒有留言:

張貼留言