Using a USB keyboard with Teensy to control motor (servo)

Hi, I am very new to coding and I am trying to find a way to make a USB keyboard control a Servo motor via a USB Host Cable with a Teensy 4.1. I understand that the two main codes that I have been looking at so far may not be able to be related, but they both work in a way that I could test to see if they worked so I've been trying to figure out a way to use them. If anyone could shed some light on this or point me to a resource I might find helpful it would be greatly appreciated!

The first one is a code that allows me to move a servo via the USB keyboard plugged directly into my laptop with the buttons "a" and "d". The second one is a code that confirms to me that the keyboard is being read by the Teensy via the USB Host Cable and then displayed in the serial monitor in the Arduino IDE.


#include <Keyboard.h>

#include<PWMServo.h> // include server library
PWMServo servo; // create servo object to control a servo
int poser = 0; // initial position of server
int val; // initial value of input

void setup() {
Serial.begin(9600); // Serial comm begin at 9600bps
servo.attach(9);// server is connected at pin 9
}

void loop() {
if (Serial.available()) // if serial value is available
{
val = Serial.read();// then read the serial value
if (val == 'd') //if value input is equals to d
{
poser += 20; //than position of servo motor increases by 20 ( anti clockwise)
servo.write(poser);// the servo will move according to position
delay(15);//delay for the servo to get to the position
}
if (val == 'a') //if value input is equals to a
{
poser -= 20; //than position of servo motor decreases by 20 (clockwise)
servo.write(poser);// the servo will move according to position
delay(15);//delay for the servo to get to the position
}
}
}


#include "USBHost_t36.h"

USBHost myusb;

KeyboardController keyboard1(myusb);

void setup()
{
while (!Serial) ; // wait for Arduino Serial Monitor
myusb.begin();
keyboard1.attachPress(OnPress);
}

void loop()
{}

void OnPress(int key)
{
switch (key) {

case KEYD_INSERT   : Serial.print("Ins"); break;
default: Serial.print((char)key); break;

}
}

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