If statement with the condition of if a certain keyboard input is pressed

Hi, I am trying to make my servo turn 90 degrees if I press for example, 'n'. I can't figure out how to though. I thought I could do

if (Keyboard.press = 'n'){
  }
  servo1.write(90);

but it doesn't work. Arduino IDE keeps saying

'Keyboard not found'. Does you sketch contain the line '#include <Keyboard.h>'

Here's the full code:

#include <Keyboard.h>
#include <Servo.h>
Servo servo1;
int servoPin = 9;

void setup(){
  Keyboard.begin;
  servo1.attach(servoPin);
}

void loop(){
  if (Keyboard.press = 'n'){
      servo1.write(90);
  }
}

Welcome to the forum

Which Arduino board are you using ?

You have used the wrong syntax for the Keyboard functions. For instance

Keyboard.begin;

should be

Keyboard.begin();

also, the press() function simulates the pressing of a key rather than reading whether a key is pressed and, anyway, in C, == is used for comparison of values rather than =

Hi there, I'm using an Arduino Uno R3. I just started learning Arduinos. Can I ask what function is used to read if a key is pressed?

Then the Keyboard library will not work (wrong processor) , nor do you need it

To determine whether a key has been pressed you can do something like this

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  if (Serial.available()) //if a character is available to read
  {
    char inChar = Serial.read();  //read the character
    if (inChar == 'n')  //test the character
    {
      Serial.println("you pressed n");
    }
  }
}
1 Like

Right mate, thanks. I got it working after modifying your code. I can't thank you enough.:grin:

Hello
I´m using this small sketch to set values into a sketch during testing.

void checkKeyboard() {
  if (Serial.available()) {
    switch (Serial.read()) {
      case '1':  break;
      case '2':  break;
      case '3':  break;
      case '4': break;
      case '5':  break;
      case '6': break;
    }
  }
}

Have a nice day and enjoy programming in C++ and learning.
Дайте миру шанс!

1 Like

You are welcome

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.