在此示例中,當(dāng)按下按鈕時,文本字符串作為鍵盤輸入發(fā)送到計算機。字符串報告按鈕被按下的次數(shù)。一旦你完成了Leonardo版的程序化和接線,打開你最喜歡的文本編輯器來查看結(jié)果。
警告 - 當(dāng)你使用 Keyboard.print()命令時,Arduino將接管你的計算機鍵盤。為確保在使用此功能運行草圖時不會失去對計算機的控制,請在調(diào)用 Keyboard.print()之前設(shè)置可靠的控制系統(tǒng)。這個草圖包括一個按鈕來切換鍵盤,以便它只在按下按鈕后運行。
你將需要以下組件:
按照電路圖連接面包板上的組件,如下圖所示。
在計算機上打開Arduino IDE軟件。使用Arduino語言進行編碼控制你的電路。通過單擊“New”打開一個新的草圖文件。
/* Keyboard Message test For the Arduino Leonardo and Micro, Sends a text string when a button is pressed. The circuit: * pushbutton attached from pin 4 to +5V * 10-kilohm resistor attached from pin 4 to ground */ #include "Keyboard.h" const int buttonPin = 4; // input pin for pushbutton int previousButtonState = HIGH; // for checking the state of a pushButton int counter = 0; // button push counter void setup() { pinMode(buttonPin, INPUT); // make the pushButton pin an input: Keyboard.begin(); // initialize control over the keyboard: } void loop() { int buttonState = digitalRead(buttonPin); // read the pushbutton: if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: { // increment the button counter counter++; // type out a message Keyboard.print("You pressed the button "); Keyboard.print(counter); Keyboard.println(" times."); } // save the current button state for comparison next time: previousButtonState = buttonState; }
將按鈕的一個端子連接到Arduino上的引腳4。將另一個引腳連接到5V。使用電阻作為下拉電阻,通過將其從引腳4接地來提供接地參考。
一旦你程序化了電路板,拔下USB電纜,打開一個文本編輯器并將文本光標(biāo)放在打字區(qū)域。再次通過USB將電路板連接到計算機,然后按按鈕在文檔中寫入。
通過使用任意文本編輯器,將顯示通過Arduino發(fā)送的文本。
更多建議: