Adventures in Arduino by Becky Stewart

Page 279

when messages are being sent, they aren’t sent too fast. Now if you connect a wire between switchPin (Pin 4) and GND, the code that you put inside the if statement is run. If you don’t connect anything to the switchPin, the pull-up resistor causes the value read from switchPin to be 1 and the code inside the if statement is skipped. Time to start adding some keyboard messages! The Keyboard functions look a lot like the Serial functions. In the setup() function you need to start the Leonardo’s keyboard messaging by calling: Keyboard.begin();

You can then write messages using Keyboard: Keyboard.println("This is your Leonardo acting like a keyboard.");

When the code is all put together, you get the following sketch: int switchPin = 4; // input pin for switch void setup() { // make the switchPin and input // with an internal pull-up resistor pinMode(switchPin, INPUT_PULLUP); // initialize control over the keyboard: Keyboard.begin(); } void loop() { // read the pushbutton: int switchState = digitalRead(switchPin); // if the switch is open (not connected to ground), if (switchState == LOW) { Keyboard.println("This is your Leonardo acting like a keyboard."); } delay(500); }

Upload the code to your Leonardo and then open any word processing program. Use the jumper wire to connect your switchPin to GND. You should see your Leonardo typing out messages like those in Figure 7-4!


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.