I just started with experimenting and trying out the code, etc.
But when I try to use a button or emulate a key it goes into a loop.
It keeps sendig the message.
I just used the standard available code:
const int buttonPin = 2; // input pin for pushbutton
int previousButtonState = HIGH; // for checking the state of a pushButton
int counter = 0; // button push counter
void setup() {
// make the pushButton pin an input:
pinMode(buttonPin, INPUT);
// initialize control over the keyboard:
Keyboard.begin();
}
void loop() {
// read the pushbutton:
int buttonState = digitalRead(buttonPin);
// if the button state has changed,
if ((buttonState != previousButtonState)
// and it's currently pressed:
&& (buttonState == HIGH)) {
// 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;
}
I build my setup just like the schematics.
But it also sends the commands to my Mac even when I don't have a setup and only the Leonardo connected and running the code. This is not normal in my opinion, but then again, I just started with Arduino.
Danton:
But it also sends the commands to my Mac even when I don't have a setup and only the Leonardo connected and running the code. This is not normal in my opinion, but then again, I just started with Arduino.
Yes this is normal.
Input pins that are not tied to 5V or GND are called "floating." Floating pins will randomly read HIGH or LOW. So when your Leonardo is connected without the button and pull-down resistor shown in the schematic, it will random print keyboard characters.
If you do not wire the button exactly as the schematic shows (with pull-down resistor), you will not get reliable operation.
For this specific tutorial the diagram calls for a 220 ohm resistor but the sketch mentions it's a 10-kilohm.
Also the sketch has a led interface using pin12 that suppose to turn off when the switch is pressed, but the schematic
doesn't reflect this connection.